title: How to TDD test that objects are being added to a collection if the collection is private?

text: Assume that I planned to write a class that worked something like this:               public class GameCharacter {         private Collection<CharacterEffect> _collection;              public void Add(CharacterEffect e) { ... }         public void Remove(CharacterEffect e) { ... }         public void Contains(CharacterEffect e) { ... }     }      When added an effect does something to the character and is then added to the _collection. When it is removed the effect reverts the change to the character and is removed from the _collection. **It's easy to test if the effect was applied to the character, but how do I test that the effect was added to _collection?** What test could I write to start constructing this class. I could write a test where _Contains_ would return true for a certain effect being in _collection, but I can't arrange a case where that function would return true because I haven't implemented the _Add_ method that is needed to place things in _collection. Ok, so since _Contains_ is dependent on having _Add_ working, then why don't I try to create _Add_ first. Well for my first test I need to try and figure out if the effect was added to the _collection. How would I do that? The only way to see if an effect is in _collection is with the _Contains_ function. The only way that I could think to test this would be to use a _FakeCollection_ that Mocks the Add, Remove, and Contains of a real collection, but I don't want _collection being affected by outside sources. I don't want to add a _setEffects(Collection effects)_ function, because I do not want the class to have that functionality. The one thing that I am thinking could work is this:               public class GameCharacter<C extends Collection> {         private Collection<CharacterEffect> _collection;              public GameCharacter() {             _collection = new C<CharacterEffect>();         }     }      But, that is just silly making me declare what some private data structures type is on every declaration of the character. **Is there a way for me to test this without breaking TDD principles while still allowing me to keep my collection private?**


title: Sending files via HTTP to web service

text: I am bit frustrated at the lack of information about this online. Here is the issue: I am in charge of creating a iOS application which sends sound data back and forth between the server and the app. The Audio is in small files and thus does not need to be streamed over, but rather it can be sent. Right now, I am using a TCP server I wrote to handle applications like this. However, I want to keep the system as simple as possible and writing your own server and client sockets can get a bit complex and leaves room for crashes. Overall it slows down development because I need to account for packet structure and other things. My question is, can I write an ASPX or PHP web service that lets me pass the files back and forth through GET or POST?


title: Practical Primes In P

text: Or rather, practically _applying_ PRIMES in P. I've heard a lot about "PRIMES in P", or the "AKS algorithm". It is, to oversimplify slightly, a very fast way of finding prime numbers. However, while I've tried reading the original paper (the revised "V3" seems to have vanished from the internet), it's a bit above my comprehension. I've also tried using Google to find practical implementations of the algorithm, but they too are incomprehensible (which is to say, they're all written in comment-free C++). Can someone produce a hobbyist/freshman-level explanation of how to implement the AKS algorithm? Or am I misinterpreting exactly what it it does and is for?


title: Entity Framework - Loading Related Entities Explicitly

text: I have been using Entity Framework for a few years. I have flip-flopped between calling out to repositories in my business logic or using lazy loading to retrieve data as I work my way through the code. The problem with the first approach is that a single business object can end up relying on a lot of repositories (in the case of repository per table). The resulting logic is heavily mixed with calls out to the data layer, which makes it harder to test (lots of mocks). The problem with the second approach is that lazy loading leads to surprises sometimes. Novices call out to the database within loops without realizing it. Even using `Include` requires a lot of care. Too many `Include`s and the generated query can be very slow. So I was getting a little frustrated. A few weeks ago, I discovered the newer `DbEntityEntry<TEntity>` classes in Entity Framework. This allowed me to load related entities explicitly and check if they were already loaded. This led to a hybrid approach where I pass a single root object and a "loader" class. Before accessing a navigation property, I would ask the loader to load it. If the object was already loaded, it would just do nothing. Since it didn't cost anything, I just called it every time I referenced a navigation property. I have added this class to an existing open source project for anyone wanting to see it: https://github.com/jehugaleahsa/TestMvcApplication/blob/master/DataModeling/EntityLoader.cs. A co-worker pointed out this class really only solved some problems. Just like lazy-loading, it meant either using `Include`s or dealing with multiple database hits within a loop. Then the other day I had another idea: I could grab the related entities for a collection of entities. For instance, getting all of the roles for a list of users. This way, I can grab the all of the related entities in a single database hit outside of a loop. I ended up with this class: https://github.com/jehugaleahsa/TestMvcApplication/blob/master/DataModeling/EntityCollectionLoader.cs. This class dynamically builds a query based on the entities. Under the hood, it builds a join that filters the related entities by the main entities' primary keys. Both loader classes provide methods that return an `IQueryable<TRelated>` to allow for further filtering, sorting, etc. The problem with these methods is that it is impossible to know whether the related entities have already been loaded, so they always result in a database hit. This is still useful for doing multiple `Include`s in a single query. My business objects now just accept a loader factory in their constructors. The business object method getting called just takes the top-level object(s). So, I really only have a single dependency on my data layer. This dependency is hidden behind an interface. I am wondering what the drawbacks are to this approach. It still mixes calls to the data layer object, throughout, except now I can navigate to the results from the top-level object's navigation properties. Plus it is a single dependency that is easily mocked out (everything becomes a no-op). It can be used right along with lazy-loading so it won't be a disaster if you forget to call `Load` first. At first I was concerned that I would be building queries in my business layer, but I realized I was just saying `Load(u => u.Role)` and then immediately accessing `user.Role`. The loader class and Entity Framework are dealing with how to populate the navigation property. Am I missing something? This seems like a really awesome compromise between pure lazy-loading and eager-loading.


title: Moving between sites using SAML

text: I'm tasked with developing an SSO system, and was guided towards using the SAML spec. After some research I think understand the interaction between a Service Provider and an ID Provider and how a user's identity is confirmed. But what happens when I redirect the user to **another** Service Provider? How do I ascertain the user's identity there? Do I send his SAML assertion tokens along with the redirect request? Or does the second Service Provider need to contact the ID Provider all over again?


title: What language is better for working with databases?

text: I am going to develop a software that works with different databases and I'm considering whether to use .NET languages or C++. I've known that .NET features LINQ and ADO.NET but are there features like that in the native C++? Which one works better, faster with databases?


title: Why are structs/arrays zero based?

text: How was it decided that if you have an array/struct or anything similiar in a programming language it should be zero-based? Wouldn't it have been easier if it was 1-based. Afer all, when we are taught to count, we start with one.


title: How would a new language look if it was designed from scratch to be easy to TDD?

text: With the some most common languages (Java, C#, Java, etc) it sometimes seems that you are working at odds with the language when you want to fully TDD your code. For example, in Java and C# you will want to mock any dependencies of your classes and most mocking frameworks will recommend that you mock interfaces not classes. This often means that you have many interfaces with a single implementation (this effect is even more noticeable because TDD will force you to write a larger number of smaller classes). Solutions that let you mock concrete classes properly do things like alter the compiler or override class loaders etc, which is pretty nasty. So what would a language look like if it was designed from scratch to be great to TDD with? Possibly some way language level way of describing dependencies (rather than passing interfaces to a constructor) and being able to separate the interface of a class without doing so explicitly?


title: Automated Testing Using Virtual Machines

text: I am working on making a system for the automated testing of student assignments. The biggest hurdle I am facing right now is figuring out how to sandbox the testing of the code yet still get and process the results of the test. I need to run it on a VM as there is no guarantee the code will not be malicious. I would like to have a process similar to the following:   1. Student submits assignment   2. VM is created and is given the source code submitted by the student   3. VM runs the tests on the source code   4. VM returns results of the test back to the host operating system   5. Results are processed Steps 2 and 4 are the ones I am looking for a good solution for. I am not sure what would be a good way automate the passing of files to the VM and the passing of results back from the VM. It seems like this is a problem that might have a solution already and I would rather not reinvent the wheel.


title: How can I ensure a portion of my project's code remains in all derivative works?

text: I had an idea for a website. After much coding and thinking out the idea, I've got it to a decent stage. If I were someone else, potentially a more commercially-minded person, I might want to sell it, or slather it with ads. However, I've fallen somewhat in love with open-source, and I'd like to host the project on GitHub and give it a nice open-source license. However, the project seems to be getting better all the time and, in fact, I think that it'll quickly grow to be fairly popular. So I want to put ads on it that benefit charity. How can I ensure that one small text advertisement benefiting charity remains in all derivative works? Are there any licenses that would let me do this? p.s. My other requirement for a license is that it gives me attribution (in the same form as the MIT license would be fine) [EDIT] I've decided to just let it be Apache licensed. I'm hoping that people will just leave charity-benefiting ads in.


title: Why are there proxy processes between clients and logic processes in C/S application?

text: In real world networking software following c/s model, there are always proxy server processes between clients and server processes dealing with business logic, why we need proxy to isolate the logic part and clients? What's the benifit of this architecture?


title: How to render RSS feed in a desktop RSS reader?

text: Consider one feed like this: http://feeds.feedburner.com/codinghorror It has the entire content inside the description tag of the feed, so you don't need to access the website to read the post. Now I have the problem of creating an interface for a feed like this on a desktop client. What's the best way to render the text in a pleasant way to the user? My first thought was to parse the entire HTML as if I was a web browser, but that looks really hard to do in a satisfying way. Are there any better (faster) alternatives? Rephrasing: how a desktop rss client such as feeddamon parses the input to display it nicely? Does it have a web browser inside it?


title: UML: Going from Use Case to Class Diagram

text: In simple steps how can one make the transition from a Use Case diagram to a Class diagram?


title: What happens between sprints?

text: I'm working on a project loosely following the scrum model. We're doing two week sprints. Something I'm not clear on (and don't have a book to consult) is exactly what is supposed to happen between sprints: there should be some "wrap" process, where the product gets built and delivered, but:   * how long does this typically take?   * should the whole team be involved?   * does it strictly have to finish before developers start working on the next sprint items?   * is this when code review and testing take place? There are three developers, adding up to about 1 FTE. So the sprints are indeed very short.


title: Program to verify all words in a crossword puzzle are valid

text: I have my own solution and wanted to check it against something online but couldn't find any examples. How would you solve this one. (I can post my code if necessary). I just want to see if someone has a better approach that I didn't think of or if my code misses any edge cases. This is for practice for a programming interview. I've written it in Java so I'd prefer to see other code in Java but any language would be fine- or even just an english explanation of what you'd do if you don't want to actually code it (but I'd prefer code since you might not realize certain things that you'd realize once you started coding). The grid is represented by a 2d array.


title: Working on someone else's code

text: I have hardly a year's experience in coding. After I started working, most of the time I would be working on someone else's code, either adding new features over the existing ones or modifying the existing features. The guy who has written the actual code doesn't work in my company any more. I am having a hard time understanding his code and doing my tasks. Whenever I tried modifying the code, I have in some way messed with the working features. What all should I keep in mind, while working over someone else's code?


title: Longest subsequence without string

text: Does there exist a dynamic programming algorithm to find the longest subsequence in a string X that does not contain Y as substring? Just that this problem seems so similar to other DP string algorithms such as longest common subsequence and string. It must be able to handle occurrences of Y that overlap. It seems that this might be a 2-state DP problem, with the state [s_pos, t_pos] being the longest subsequence of string S starting at s_pos that does not have sting T[t_pos..M] as a substring. N is the length of string S and M is the length of string T. However, my transitions are not correct: it does not get the case where S=`aaabc` and T=`aabc`. The problem is in the _else_ statement - I don't know how to transition if the characters are equal. **Actually I feel that the if branch is wrong... anyone know what could be wrong?** It even fails the case S=`aaab` and T=`aab`. I can explain why it fails: assuming I call solve(0, 0). solve(0, 0) calls solve(1, 1). solve(1, 1) calls solve(2, 2). Since s[2] != t[2], it restarts the search from solve(3, 0). However, aab is a substring and it never checks this or considers this case...               int solve(int s_pos, int t_pos)     {         if (s_pos >= N || t_pos >= M) return 0;         if (t_pos == M - 1 && s[s_pos] == t[t_pos]) return 0;         int ret = 0;         if (s[s_pos] != t[t_pos])         {             int tmp = solve(s_pos + 1, 0);             ret = max(ret, tmp + 1);         }         else         {             for (int i = s_pos + 1; i < N; i++)             {                 int tmp = solve(i, t_pos + 1);                 if (tmp != 0)                 {                     ret = max(ret, 1 + tmp);                 }             }         }         return ret;     }


title: How do I inject test objects when the real objects are created dynamically?

text: I want to make a class testable using dependency injection. But the class creates multiple objects at runtime, and passes different values to their constructor. Here's a simplified example:               public abstract class Validator {         private ErrorList errors;              public abstract void validate();              public void addError(String text) {             errors.add(                 new ValidationError(text));         }              public int getNumErrors() {             return errors.count()         }     }          public class AgeValidator extends Validator {         public void validate() {             addError("first name invalid");             addError("last name invalid");         }     }      (There are many other subclasses of Validator.) What's the best way to change this, so I can inject a fake object instead of ValidationError? I can create an AbstractValidationErrorFactory, and inject the factory instead. This would work, but it seems like I'll end up creating tons of little factories and factory interfaces, for every dependency of this sort. Is there a better way?


title: Search substring using suffix array (and LCP)

text: I'm searching for a best way to improve suffix array run time using LCP. My text (about 2 500 000 chars) seems like: 0ricco0eric0america0polo0.... My thoughs:               SA=suffixArray     char=firstChar(input)     s = suffix array index of a first value char           currentWord is area (string) in the text from 0 to next 0 where the substring is found, hence: for founded substring icco would be currentWord ricco          repeat         if pattern in text[SA[s]:SA[s]+len(input)]             break         s+=1     results.append(currentWord)          repeat         if lcp[s]>=len(input)             results.append(currentWord)             s+=1         else:              break      Is this a correct way? Or could you give me an advice how it should be?


title: How to learn from open source

text: I see this problem quite often. I like a certain value proposition of an open- source project. I try out the basic tutorials. Great. It works! But if I move on to more complex problems, I spend hours of doing research, debugging, frustrations, etc. What are your strategies to keep motivation in open-source going? What is the reward of open-source after success of basic tutorials? What "success" of open-source did you experience?


title: How to protect intellectual property when oursourcing software development?

text: I'm a small company needing to outsource software development. I've written both functional and technical specifications for GUI developers and back-end (C or PHP) developers to implement my software application. I'm a little nervous handing over copies of these documents to request bids from numerous companies. Looking for recommendations to protect my work while outsourcing. What's the conventional wisdom? Is there generic NDA someone could send me a link to. How do others handle this situation. What would the outsource companies expect, or not expect, from me?


title: Why is + so bad for concatenation?

text: Everybody keeps saying that one of JavaScript's problems is using `+` [example] for string concatenation. Some say the problem is not using `+`, it's type coercion [see the comments from the previous example]. But strongly- typed languages use + for concatenation and coerce types without any problem. For example, in C#:               int number = 1;     MyObject obj = new MyObject();          var result = "Hello" + number + obj;     // is equivalent to     string result = "hello" + number.ToString() + obj.ToString();      So why is it that string concatenation in JavaScript is such a big problem?


title: New sequential testing framework with the same rigor as xUnit?

text: Looking for books (published or upcoming) and frameworks (preferably free/open-source) for sequential tests. My understanding of sequential tests is that it is very similar to a Workflow System, with the following elements:   * A collection of Setup/Exercise/Verify routine-sets (suites) - same as in xUnit      * Optionally, a routine-set may also contain:        * Teardown - which marks the end of the sequential test, after which the entire software state will be unrolled to the beginning.       * Undo - which rolls back just a single operation, back to before the "Setup" of the current routine-set.       * If a programmer provides an Undo, the programmer vouches for the correctness of that Unfo. (Assertions can be used, though it is best not to use any unreliable Undo.) If programmer is not certain, don't provide an Undo.   * Each routine-set must _either_ provide a StartUp, or one or more "preceding step(s)" - the new part for sequential tests      * A StartUp basically re-initializes the entire software state in a guaranteed way.     * The "preceding steps" are references to other routine-sets.   * **Unlike unit testing, sequential tests are allowed to pass on objects to the next step, in a carefully-controlled way.** **Example:**   * Routine A      * Create an empty "readme.txt". (stop the test if it already exist; preconditions not met.)     * Verify "readme.txt" exists.     * Undo function: Delete "readme.txt" if it exists.    * Routine B,      * `follows` routine A     * Open file "readme.txt" for writing (erase previous content) *  Related: Are scenario tests groups of sequential unit tests? * * * Dear all, sorry the question was lost in the midst of an unexpected machine failure; so this was recovered from a previous autosave draft. Since that crash I had extended the idea a little bit, and I'll need several days to clean it up and update this question. * * * The keywords are:   * `Initial` [new] (initializes the whole world)   * `Setup` (checks for pre-conditions are met for the beginning of one step, and create temporary objects that help with this one step - these temporary objects will cease when this one step finishes. You may call these "local" objects)   * `Exercise`   * `Verify` (assertions that the step has been successful)   * `Undo` [new] This optional method, if provided, means that there is a way to fully revert the world state to before this step. If one is provided, the programmer vouches for the correctness of that Undo. If unsure, don't provide one.   * `Final` [new] Wraps up the whole world for disposal. After that, Initial can be called again to re-initialize a second new world.   * `Follows` [new] this defines how steps can be chained together.      * Each test step that is not an `Initial` step must have one or more `Follows` statement. Each statement can include one or more peer steps - those peer steps need to happen first before this step can be invoked. **Now the gist. Once you specify all those rules, the sequential test execution engine enumerates ALL of possible sequencing of those sets of steps.** It enumerates all paths from `Initial` to `Final`, using whatever intermediate steps that allows a path to be formed. It will also warn you about loops and other potential problems, and let you choose how to deal with those loops.


title: Using Git in Enterprise environment

text: Git is an excellent version control system. If we exclude the fact that, it doesn't have an excellent GUI support, it's really good and fast. But the source controls like Clearcase has large support for enterprise customers. Companies are investing huge amount for source control servers and licesense. Of late most of the large companies like Google are adopting Git over other version control system. But this company has a strong open source group which consistently provide development and support for the tool (They might even have a custom version of Git of their own). At the same time, large companies are not really bothering about adopting open source projects and making them relevant to them.   * Is Git really a reliable tool for enterprise environment, especially on Windows Platform?   * The support is in question for Git as it's an open source product.   * Are there any company that provides solutions and support? How are the server costs compared to other version controls like Clear-case?


title: Are ads within average Android applications profitable?

text: I presume this question is acceptable here-- because it's a part of software development but not specific to programming. If it's better suited for another area, could someone kindly help move me? I know ads can be profitable for some incredibly popular applications, but how do average applications fare? I am about to release an application and I think it will be pretty popular, but it's not the next Angry Birds. I guess there will be a few thousand users. Would a few thousand users that use the application about 15~20 minutes once or twice a day net any actual profits? What are you experiences with ads like? What kinds of numbers do we need to net anything worthwhile? Thanks~


title: Has "Not everyone can be a programmer" been studied?

text: An old adage that many programmers stick to is "It takes a certain type of mind to learn programming, and not everyone can do it." Now I'm sure that we all have our own trove of anecdotal evidence, but has this been studied scientifically?


title: How can I close my Open Source project and what is required from me in order to make it closed source?

text: Let's say I wanted to close my "GPL v 2.0 (or similar)" licensed project, to which I'm the only contributor, and make it closed source.   * Do I still need to make the existing "GPL v 2.0 (or similar)" licensed code available after closing the project or can I refuse giving out the source code for old revisions that was previously "GPL v 2.0 (or similar)" licensed?   * Can I theoretically keep the the code "GPL v 2.0 (or similar)" licensed even after removing the public source code or do I have to distribute the source code if I'm using a "GPL v 2.0 (or similar)" license?


title: Suggestions for finding code to review, that is for CodeReview.SE

text: Looking for suggestions on finding code to review, or to be more clear, code on SE sites with excepted working code -- to suggest be posted to CodeReview.SE for optimization. The source of this question was another question I posted on CodeReview.SE.meta Growing Code Review, One Idea... :-) In which I got this reply: * * * > Sure, you can, as long as people are clear what code review is for -- > essentially, functioning, working code that needs to be improved in some > subjective, perhaps even aesthetic, way. > > If the code is in any way broken or does not work, that is not the purpose > of Code Review. > > Jeff Atwood * * * If anyone has suggestions on how to improve this question, just comment.


title: How do you keep emails short but complete?

text: I'm the odd kind of developer that likes writing and explaining - emails, specs, you name it. I enjoy helping people understand things deeply. I hate ping-pong communications where groups go through 30 or 40 emails, phone calls and meetings because 25% of the group misunderstood the previous dashed-off email in which the writer only half-explained their position, or was in a hurry and miswrote a critical word or left out a negative or two. This trait is great for documentation, but my emails are long, so people simply don't read them. A couple strategies I've used are formatting long emails as attached Word documents to encourage people to view them as documentation (works surprisingly well sometimes), or trying to use more bullet points instead of free paragraphs. These strategies increase readership, but the content is still long. Of course I want to yell and scream that complex technical topics require a lot of exposition and clarification, but that doesn't help anyone. Obviously there are tradeoffs that can be made, but I have a hard time justifying making statements that aren't clear or that will result in a million questions, misunderstandings, or added "terms and conditions" later on. How do you keep your communications short but complete?


title: JavaScript for a non-programmer

text: 2 years ago I starded learning AS3 in order to get hired at a web design company. A few months later, I ditched it, because I discovered that I'm better at design; so now I'm a web designer. Recently, I decided that knowing JavaScript would be nice and helpful, so i started with Essential JavaScript Training from Lynda.com. Untill today, I was under the impression that my knowledge of programming was somewhat basic. What happened today...? I learned (through trial and error) that variables are only valid in the functions that they're defined in. This turned my world upside down. I was like: "that makes sense now..." thinkin of the all the headaches that the lack of this specific piece of knowledge gave me. How could I have missed such a fundamental thing while learning AS3 (and now JS)? I didn't. And I remember reading a at least three books on AS3, but none of them taught me about programming. So what I want to ask you, is if you could recommend me a good JavaScript book from which i can learn programming, too, besides syntax. Thanks! And sorry for my bad english :)


title: Unix as opposed to Windows (Java and C++)

text: Firstly I should explain the background. I am interested in high frequency trading programming roles. After looking at many job specs it is very clear that there is a big demand for programmers who have programmed Java and C++ on Unix as opposed to Windows. My question is what are the differences a High Freq programmer would come across? It cannot be something in the language itself because syntactically they do not differ over OS? Therefore I thought it must be something which the programming language has to interface, resources etc? Could anyone please help me out as I am trying to improve my C++/Java on Unix, in order to aim for this type of career? ps I'm guessing part of this answer lies with the socket infrastructure on Unix?


title: Java code generation from class diagram

text: I'm on the way developing a Java application where user can provide a class diagram and get the corresponding Java code. I don't know how can I let the user interactively _draw_ a class diagram in Java. I am currently getting the required parameters like attributes, functions directly from the user, and then I render a class diagram for him. I show the class diagram on a jdialog.But when it comes to multiple class diagrams, it screws me. Is there a better way to do this? This is an example of a class diagram, I need to generate this from a Java program, given the values and relationship. ![enter image description here](http://i.stack.imgur.com/MgwsJ.jpg)


title: What is the pattern behind respond_to / respond_with in Rails?

text: Is there a specific name to this? For me it looks like a view router, or a presenter router (I would name it like that) but maybe there is a better name and explication.


title: Is using something other than XML advisable for my configuration file?

text: I have a small tool I'm designing which would require a configuration file of some sort. The configuration file in my case is really more of a database, but it needs to be lightweight, and if needed the end-user should find it easily editable. However, it also will contain a lot of things in it. (depending on certain factors, could be 1Mb or more) I've decided I'd rather use plain ol' text, rather than trying to use SQLite or some such. However, with using text, I also have to deal with the variety of formats. So far, my options are   * XML   * JSON   * Custom format The data in my file is quite simple consisting for the most part of key-value type things. So, a custom format wouldn't be that difficult... but I'd rather not have to worry about writing the support for it. I've never seen JSON used for configuration files. And XML would bloat the file size substantially I think. (I also just has a dislike of XML in general). What should I do in this case? Factors to consider:   * This configuration file can be uploaded to a web service(so size matters)   * Users must be able to edit it by hand if necessary(ease of editing and reading matters)   * Must be able to generate and process automatically (speed doesn't matter a lot, but not excessively slow)    * The "keys" and "values" are plain strings, but must be escaped because they can contain anything. (unicode and escaping has to work easily)    * **Multiple** configuration files. Basically, each config file is tied to one "project"


title: Help identify terminology for pattern substituion?

text: This is a badly titled question...maybe a moderator can make it better. Nearly two decades ago, I took a computer graphics class as an undergraduate. We got to do whatever we wanted for a final project as long as it demonstrated what we learned about CG. So, I read a book (I can't think of the name at all) that described a methodology to generate fractal images starting with a simple shape and mutating it using substitution. It described abstract fractals and tree/flower fractals. I do recall implementing the Sierpinski Triangle in one of my sample imputs as well as a 3D tree. The input to the program was basically a series of arbitrary symbols defined by the program. `-----=` might represent a rose. Then you apply some substitutions for a given pattern. `--= > -+=---=` might represent a longer rose with thorns. So, applying that pattern to the initial string you get `----+=---=`. Finally you loop over this string `N` number of times to create some desired effect. The book itself offered a ton of inputs with sample pictures, but no actual source code. The implementation was completely left up to the developer. I would like to know if somebody can help me with the terminology for this technique and bonus points for the name of the book (or a book) that described this process?


title: When are request headers read by ASP.NET code

text: I've got an issue with my MVC 4 website where iOS Safari is automatically sending the DNT header with the first request to the site. Here's my question on StackOverflow. Even though the iPhone has the DNT setting turned off, it still sends this header. So, my hack to fix this is to create an ActionFilter that will remove that header if it exists. My first attempt was to just add my custom ActionFilter to the FilterConfig.RegisterGlobalFilters method. That did not work (though I didn't have Fiddler in front of my at the time to see what was really going on). As long as my browser (iOS Safari) stays open, it will always remember me, but I want it to remember me between browser sessions. So my next thought is to try adding the removal of that header inside either the Application_BeginRequest, or Session_Start methods in Global.asax file. Here's a handy site that showed what methods were available in the Global.asax file and what order they process in. That leads to my question, at what point in the process of processing a request, do the headers (specifically the DNT header) get analyzed that are used by Forms Authentication [session/cookie]? It would seem that by the time the request gets to my ActionResult method, that the DNT header has already been read and "processed". I want to be able to strip it out at the earliest possible moment. Btw, I'm not at my home computer right now which is where my code is. I'm not going to be able to start working on this until the wife goes to bed (11:00pm) so I want to make sure I have all my eggs in a row before I start working so I can get as much accomplished as quickly as possible. I need to have a big production release tonight, and I'd LIKE to get this fixed as well... Thanks for any help/input if you're able... Edit: Any other suggestions for either this question, or the one that I have referenced/linked above on StackOverflow?


title: How important is the Acid3 Test anymore and what should replace it?

text: For a long while the default guide to latest standards support for browsers was the Acid 3 Test. I've just run this on Windows 7 (x64) for Chrome 15.0, Firefox 7.0, Safari 5.1 and IE 9.0 and they all score 100. Some of the animations could be smoother but on the whole there's not much to differentiate them. I've then looked at the scores for html5test.com which show much wider variation:   * 343/450 : Chrome 15.0    * 298/450 : Firefox 7.0   * 293/450 : Safari 5.1    * 141/450 : IE 9.0 Are there other tests that are a useful measure for browser feature support? What minimum score on the HTML5 test is a 'good' score? How important is the HTML5 test score and can it really test all the new features properly? Is it a good replacement for the Acid 3 test? Are the modern browsers now compliant enough that the end user can remain ignorant of the level of standards support?


title: Is there a way to run javascript on a present webpage

text: I don't have programming background. I have started learning javascript recently. I'm wondering if there is a way to run javascript on a webpage ? for example I would like to write a javascript on this webpage which runs through all the questions posted in past 1 hour and does something. Is it even possible ?


title: What camera to choose for using with JMF (Java Media Framework)

text: For the past 2-3 weeks I've been searching for different ways to implement custom video streaming and in more general video capturing and manipulating, going through DVR-cards, Video Capture Cards and stuff like that. Somehow JMF was able to stay out of my sight for all this time, but since I find out about it I'm more and more sure that this is a comfortable level for me to start playing around with video and stuff. One major topic that occurs to me while searching for more info was the presence of many posts where people were complaining about the fact that any particular camera ( most of the time I think they mean web cameras) doesn't work with JMF. Even though there are a lot of different cameras (not necessarily a web cam) that are not that expensive I want to play it safe and buy one that is proven to work well with the JMF. Also due to lack of experience maybe this is irrelevant but since I'll buy the camera mostly for learning and experimenting I want to have the maximum freedom possible to mess with different features, options and so on.


title: Why friend in C++ should be in the header file?

text: Friend function/class, FriendOfX for some arbitrary class X is an implementation detail of class X. Why in C++ we have to declare them in the header file? Are there any compelling reasons to make this contract (between X and FriendOfX) explicit? I understand there could be valid reasons to make this contract explicit but in some cases I would not want my client using interface class X to know about FriendOfX since FriendOfX happens to handle certain collaboration aspects of interface class X which are implementation specific


title: Quality Assurance tools discrepancies

text: It is a bit ironic, yesterday I answered a question related to this topic that was marked to be good and today I'm the one who asks. These are my thoughts and a question:   Also let's agree on the terms: QA is a set of activities that defines and implements processes during SW development. The common tool is the process audit. However, my colleague at work agrees with the opinion that reviews and inspections are also quality assurance tools, although most sources classify them as quality control.   I would say both sides are partially right: during inspections, we evaluate a physical product (clearly QC) but we see it as a white box so we can check its compliance with set processes (QA). Do you think it is the reason of the dichotomy among the authors? I know it is more like an academic question but it deserves the answer :)


title: How to tell the View to create a cookie?

text: I have a `LoginService` class with `loginUser($email, $password, $remember = false)` method in the application layer of my model layer. Now, if `$remember` is `true` it needs to create a persistent user login cookie on the client's browser, but since that is the responsibility of the View, what is a good way of reaching the view through the controller to let it know it should create the cookie for it?


title: PHP frameworks - should I use them?

text: First of all let me explain who I am: I am a PHP Developer working for a company developing their CMS which handles online stores, data feeds and other content like blogs. I have been programming for 6 years and 4 of those have been in PHP. (I used to be a C# developer). My question is regarding PHP frameworks. I see so many jobs asking for zend, cakephp and other MVC types of frameworks. However, even as an experienced developer I have never used a PHP framework. Should I start learning? If so where do I even start as there are so many. I am about to re-write so much of my work's CMS and I'm wondering whether I could help myself a lot by using a framework. What do people think? Considering I will be re-writing a lot of the online store stuff... I am experienced in OO and I have used the .NET framework in the past. Thanks in advance for the replies.


title: Minimal Refresh(F5) Web App Development

text: Although questions similar to this one has already been asked and I can perhaps assemble the answer for myself by reading already posted materials. Still I am going ahead with the question, cause I feel it has elements of new flavor and I would like to see the views of others on how to tackle this. I have developed several Web Applications of various scale. In some of them, I was only Developer, in another I led small teams and was part of a big team in another. Most of these were developed using PHP. One of them used Kohana Framework, the rest were all developed using Raw PHP. The main difficulty that I faced in regards to speedy development was, whenever a small change was done to fix a bug or modify a feature, I had to refresh my web browser, go through several pages until I reached the page which included the fix. I would like to know, what should be the development approach so that I can test out my code without having to, or at least minimize the number of refreshes required to test out changes in code. Although, the concepts maybe applicable for developments of any nature, for this question, let us stick to PHP and it's framework.


title: The benefits of using RAII in C++

text: Suppose I'm a teacher and I want to explain to my students what are the benefits of using RAII in C++: I need a very good example, full of details, but that is easy to understand.   Which approach would you use?


title: How do you educate your customers?

text: Customers need some education because they think different. Customers think:   * changes are not a problem in any time of the project   * details are not important (exceptions even less)   * time does not cost money (they have a fix price agreed)   * one sentence in the specification can be extended/read freely to fit the actual needs - and this does not affect the contract. (here we see often the "common sense" discussion - example: "Of course we need a invoice management screen when we talk about accounting managment - this is common sense!")   * the list goes on... The main problem is that customer (no matter if external or internal/department) do not want or can not understand. It took me many years to understand software creation process and I am still learning, so how can they in just a few months. What is your experience, what is the best approach to educate customers?


title: Play or Lift: which one is more explicit?

text: I am going to investigate web development with Scala, and the choice is between learning Lift or Play: probably I will not have enough time to try both, at least at first. Now, many comparisons between the two are available on the internet, but I would like to know how do they compare with respect to being explicit and involving less magic. Let me explain what I mean by example. I have used, to various degrees, CakePHP, symfony2, Django and Grails. I feel a very clear distinction between Django and symfony2, which are very explicit about what you are doing, and Grails and CakePHP, which try to do their best to guess what you are trying to achieve and often feel "magical". Let me give some examples comparing Django and Grails.   * In Django, views are functions that take a request as input and return a response. You can instantiate explicitly an instance of `HttpResponse` and populate its body with a string, or you can use shortcut functions to leverage the template system. In any case the return value from your view always has the same type. In contrast, the `render` method from Grails is highly polymorphic. You can throw a context at it and it will try to render a template which is found by convention using that context. Or you can pass it a pair of a template path and a context and that will work too. Or a string. Or XML. Grails tries hard to make sense of whatever you return from your controller.   * In the Django ORM, each model class has a static attribute representing the manager for that class. That manager exposes a fluent interface to build querysets. In Grails, you can have a similar functionality by composing detached criteria. Still, the most common way to query objects seems to be the use of runtime-generated methods like `FindUserByEmailNotNull` or `FindPostByDateGreaterThan`. I will not go further, but my point is that in Django-like frameworks you have control over the whole flow of the request/response process, while in Grails- like ones I feel I only have to feel the blanks and the framework will manage the rest of the flow for me. This is not to criticize Grails or CakePHP; which type you prefer is mainly a matter of preference. In fact, I happen to like some aspects of Grails, but I feel more comfortable with a framework which does less for me. Back to the point of the question: which one among Play and Lift is more explicit about what you do and which one tries to simplify more what you have to do with a layer of "magic"?


title: Multiplayer Game Listen Servers: Ensuring Integrity

text: I'm making a simple multiplayer game of Tic Tac Toe in Python using Bridge (its an RPC service built over a message queue - RabbitMQ) and I'd like to structure it so that the client and the server are just one file. When a user runs the game, he is offered a choice to either create a game or join an existing game. So when a user creates a game, the program will create the game and also join him as a player to the game. This is basically a listen server (as opposed to a dedicated server) - a familiar concept in multiplayer games. I came across a really interesting question while trying to make this - **how can I ensure that the player hosting the game doesn't tamper with it (or atleast make it difficult)**? The player hosting the game has access to the array used to store the board etc., and these must be stored in the process' virtual memory, so it seems like this is impossible. On the other hand, many multiplayer games use this model for LAN games.


title: Recursion -- is it "divide and conquer" or "code reuse"

text: _**Recursion_** \-- as we all know -- is one of those problems -- that wrapping your head around feels like achieving a "milestone" in your programming voyage. But when it comes to actually using it in real world problems -- knowing the mechanics of recursion is NOT enough -- one must also understand the nature of the problems where recursion is the most suitable solution. So my question is this...   * what are the "problem patterns" that call for the solution of recursion   * is recursion a form of "divide & conquer" strategy or a form of "code reuse" -- or, is a design pattern in its own right   * can you give us an example of a real world problem where recursion comes to mind as an immediate solution _**\-- UPDATE --_** a lot of answers are referring to "real problems" as tree traversing, of factorial, etc. I would prefer "the REAL real problems" -- let me give you an example... We had a LARGE chuck of text (about 30 MB of text as a linked list of `structs`), and we needed to make an index of it for full text searching. We needed keep the entire index in the memory and re-index the text every 10 minutes. Every 10 minutes we'd compare the entire text (two linked lists, line by line) with a newly generated chunk of text -- to see what line was changed -- and then we would re-index only that line -- that way we could avoid having to re- index the ENTIRE text. Remember -- we needed to find the diff points between two 30 MB linked lists. One of my colleagues came up with a fantastic program which used HEAVY recursion to compare the lines -- and then collect the positions where the chucks differed in an array -- yes i know it sounds puzzling -- how could recursion help here -- but it did. The point is -- how could he see that this problem could be solved smartly with heavy use of recursion?


title: DDD + POCO does this makes sense?

text: DDD promotes rich domain models with behavior in it, POCO naked objects without any objects in it. **Is it possible to have them both combined?** I have a Multi Layer Solution   * Core - has POCO Entieties, interfaces for Repositories and Services   * Data - Repository implementations   * Service - Service Implementations   * Infra - IoC Locator/registrar, viewmodels, (could be merged to webui)    * WebUI - asp.net mvc presentation layer I was saying that I use DDD but recently I've been told that I'm not because my Entities don't have behavior, **is this true?**


title: So I've gotten the hang of iOS app development, but how do I become a great app developer?

text: I've spent the past 2 years teaching myself and taking classes on object oriented programming. I have done quite a bit of Java programming, and lately I've been spending a lot of time doing objective-c. I really enjoy programming, but one thing that I have noticed (with some frustration) is that I'm not amazing at finding elegant solutions to problems. I'm beginning to notice that it isn't enough to just solve a problem, but that the way you approach and implement a solution says a lot about you as a developer and depth of your knowledge and understanding. Being that I am looking to make a career out of iOS development (I'm still in college), I want to be sure that I am doing everything I can to learn elegance, as opposed to just getting it done. Case in point: For one of my first programming projects for school (this was a long time ago!), we needed to populate arrays with tons of information. I went through and added each element line by line just hard coding the index! When the TA came by he laughed at me and was like: "Why didn't you just use a for- loop?" and I thought to myself, well who cares? It works doesn't it? **My Question to iOS devs out there:** What are some things that I can study/try to implement to increase the elegancy of my design habits? What are examples of things that are often done in the app development world by rookies that just shouldn't be done? Instead of just being able to throw a quick and dirty hack job of a solution together, I want to be able to consistently come up with awesome ways to solve problems! And I've realized that those types of solutions don't always come quickly to me. Is this skill something that can only be acquired through experience and doing it wrong tons of times before you realize that there is a better way? Are there any areas that you can recommend I try to cover and make a point of understanding? While I am happy that I can keep up with many of the q's posted to sites like this, I get frustrated when I see some that are just in a whole different universe! I want to close the gap, and so I am throwing this out there to any who may be interested/able to help. Thanks!!


title: Java Phones: How to set up JTAPI?

text: I want to use JTAPI (1.4 - latest) to create an app that will call my phone whenever I need it to. I downloaded JSR043 (JTAPI specification) and have been reading the API docs and it seems pretty straight forward with respect to _how to code JTAPI_. However I seriously doubt that getting a Java app on my laptop to call my cell phone doesn't require some 3rd party or middle man service provider and possibly other entities/configurations as well. So I ask: besides using the JTAPI in my Java code, what do I need to install or set up to have a Java app that calls my phone? Thanks in advance!


title: Are there any special advantages of SQL Server with Visual Studio?

text: I have seen the forum dba.StackExchange, but this question involves Visual Studio as well, therefore I wanted to post this question here. One of my old application was built on VS-2008 and MySQL back-end. After three years, I don't have any major issues with it and the database performance is also good. I am scaling this application to a WPF application and want to know whether SQL Server has any added advantages when used with VS-2010, other than that it is from Microsoft, over MySQL? In most scenarios, I notice query execution in MySQL is faster as compared to SQL Server.


title: Web Application that is independent of web server software

text: # Scenario I haven't faced this requirement before, so I'm not confident with my solution. Our team drew up a plan to design a web application using a basic HAT stack for a project with a 4 month development time. We presented it to the client, who added two big new requirements. The requirements were:   * The application must be runnable on any web server (IIS, Apache, Nginx, Lighttpd, etc...)   * The application must be able to work with any database (MySQL, MongoDB, etc...) His reasoning is that he has no control over the environments where the web application will be installed on. He plans on re-selling our solution to other customers. We pushed back to the client saying that this would increase development time, but he has already committed to his clients. However, he said he is willing to put as much money into it to get it done. ## Possible Solution? The only solution I could think of was building the application in Perl CGI script as that seems the most universal, then having a variety of database adapters to plugin into an ORM, which is customized through a config file. ## Question   * What alternatives are there to creating a web application where we have no control over what modules, etc.. are installed in the web server?   * Is this even possible?


title: Version control workflow for semi-bespoke software

text: I have a web app product (PHP, MySQL) for which I offer a bespoking service. That is, you can buy the main product, which is quite extensive, and then have it customised however you like. This might include new features, adjusting fundamentally how existing features work, disabling features, making changes which require a different database schema, etc. I want to find a sensible way of managing a large number of different releases of the product in version control such that I can make changes to the core and pull changes out to the releases as required, and also make changes to a release independently. Sometimes I might want to pull a change from release back into the core. My instinct was to use Git, and have the releases as branches. It is possible to pick specific commits to merge back into the trunk, so I think this could work. However everywhere I have looked suggests that it is a bad idea to have permanently separate code in branches. The suggestion is to use a single codebase and have all the differences in features configurable, so that each release can behave separately. This sounds fine for software which is sold in multiple editions, which have different features enabled, but I think it would be a complete mess for my software. I'm looking for a good development workflow for a setup like this, which may or may not be based on version control.


What is the best approach for Single Sign On Application Development that is lightweight? By lightweight I mean not too much javascript. I know stackexchange does use single sign-on. Basically is the login credential stored as cookie? Or combination of IP-Address and other specific information about the logged in user?


title: Can we still consider that Moore's law still holds true regarding the consequence on CPU speed?

text: Moore's law is an empirical law and in simple terms states that the number of transistors on integrated circuits doubles approximately every two years. One of the consequences of Moore's law is that CPU performance doubles every 18 Months. I've seen 'Why is Moore's Law seen as an absolute truth?' and although curious does not answer my question. Currently we are partly achieving that by making multi core CPU's. **Can we still consider that speed of CPU's doubles every 18 months?** Multi-core CPU's can be looked at just as distributed computing. A "good old" single threaded sofware/algorithm won't be able to take full advantage of such CPU as before and It's not true that all algorithms are paralelizable with speed gain.


title: Criteria for selecting timeout value?

text: Situation: a piece of software reads frames of data from a file in a seperate thread and puts it on a queue, emptied by another thread. That second thread periodically checks on the queue and fails rather gracefully, by showing an error message stating the read timed out, if no data is available within a certain amount of time. Initially this timeout was set to 200mSec. There was no real reasoning behind that constant though, but it worked fine. We measured on a couple of machines and for large data frames, larger than what would be used by customers, a read took like 20mSec whith no other load on the machine. However one customer now gets timeout errors now and then (on the second try all is fine, probably the file is in cache or the virus scanner leaves it alone). The programmers are like 'well, yeah, but that customer's machine is full of cruft, virus scanners, tons of unneeded background processes etc'. Of course the customer is like 'hey this should just work, shouldn't it'? While the programers have a point, since the software is heavy enough to validate the need for a dedicated machine, that does not make the customer happy. Increasing the timeout to 2 seconds, for example, solves the problem. But I'd like to make a proper decision now instead of just randomly pick some magic constant that is probably ok in 99% of cases. What criteria should be used for that? We could just pick a large number, but that feels wrong. (and then we end up with a program that has the horrible bahaviour of hanging when trying to read from a disconnected drive for instance, whereas we'd rather make it show an error right away). Or we could make the timeout value a user setting, but then we need to ducument it clearly and even then not all customers are tech savy enough to really understand what it does. Or we could try and wait until another customer reports timeouts and increase the value again. And again. Until we find something ok for 99.99% of the cases.. Any good practice for this type of situation?


title: DDD: Developing the Domain Model alone

text: In DDD examples it seems the common method for developing the domain model is to sit with domain experts and iterate over versions of the model, say on a whiteboard, continually modifying it and changing it until presumably an agreement is made on how the model looks. On my project I've spent a couple of days with a domain expert, discussing the domain, and now I want to lock myself away and produce a draft model based on my understanding, rather than producing the model collaboratively with the domain expert. He could then review it, and I could update it according to our subsequent discussions. Has anyone else worked like this, or does anyone think its a good / bad idea? I think maybe I just find it easier to think creatively when alone.


title: Problem in working with async and await?

text: I am trying to upload files to Azure Blob Storage and after successful upload adding the filename to a list for my further operation. When i am doing synchronous it works fine but when i am doing async the error occured. Error : Collection was modified; enumeration operation may not execute.               foreach(var file in files)     {        // .....        await blockBlob.UploadFromStreamAsync(fs);        listOfMovedLabelFiles.Add(fileName);     }     if (listOfMovedLabelFiles.Count > 0) // error point     {         // my code for further operation     }      Is there any way to wait till all the async operations get completed.


title: Is adding support for another operation system a minor version or a patch?

text: Let's say I use Semantic Versioning for a my project. I'm developing it under FooOS, but the language uses virtual machine(either interpreted language or bytecode based) so any operation system can run it. The thing is, the project interacts heavily with OS-managed things(e.g. pipes, processes, the file system) so if you try running it under a different operation system - BarOS - it gets so buggy and so many things don't work that the project is practically useless. Now, at some point I want to make my project work for BarOS, and I want to release a version just to add that support. The question is - does that count as a _minor version_ or as a _patch_? It seems like it's a patch:   * All I do is fixing all the bugs that appear when running the project under BarOS.   * Users of my project shouldn't notice any change in functionality, since they are using FooOS in the first place.   * For BarOS users my whole project is new - but getting new users is not something that should result in a version increment. But even with all that reasoning, it just doesn't seem right to label a release as big as new OS support as a patch...


title: Defining error codes

text: We are designing an error-handling framework for a cryptographic library written in C. The approach we are taking is that relatively few errors are propagated back to the user since on most occasions he cannot do anything about them (notable exception: parameter validation errors. Of course we tell the user if a call succeeded. We'd also create log entries for fault investigation.) In short, just because we have an error condition somewhere inside the library it does not mean that we need a public (user-facing) error code for it. Also, from past experience we think that a significant portion of error conditions that require error codes pertain to very narrow areas of code, it is often the case that a particular error is only returned from (or set by) one function. Therefore we would like to define error codes at the lowest possible level. For example, if only one function can return/set a particular error code we would define that code in the .h file where the function prototype is declared. However, in such case we might get error code conflicts - the same error code value for different errors. Can someone please propose an elegant approach to avoid such conflicts? Or at the very least an automated mechanism to check for such conflicts (which can then be fixed by hand)?


title: Dealing with API and error messages

text: We are in the process of constructing an API (using WCF). So far I noticed 2 ways in which methods could go wrong due to problems with the parameters sent.   1. wrong format, for example we have a string date parameter which should be in a certain format, if it's in a different format the method cannot continue.   2. if a method role is to do something identified by an ID, but that ID does not exist in the application (DB) First we thought throwing an exception, but I realize now that this is not truly an "exceptional" situation, these kind of things is pretty common. Right now we deal with it in the following way: We have an abstract class which is called APIResponse. it has a boolean success variable, and an array of messages for the API's client. Each group of methods has a corresponding implementation of this class and that will be the returned object. **is this kind of approach ok?**


title: Is there a limit on how many global consts are used before an application is considered bad programming?

text: Basically, I develop websites, some large with many crud operations, etc... However I've gotten into the habit of storing re-usable data as a constant in my PHP applications I currently have 44 constants defined in one application. These range from:   * Database config   * Home page for admin and guest   * url slug names   * declaring development mode   * declaring maintenance mode   * a few directory shortcuts ( instead of writing /admin/templates/images ill use const ADM_IMAGES )   * session names   * cookie names   * random things like MAX_IMAGE_SIZE, THUMB_SIZE and MAX_LOGIN_ATTEMPTS I don't have any problems using all these constants... It's kind of helpful having all these in my application. I just wanted to know if its a 'good practise' to use them in this excess If not, how else could this data be encapsulated to be useful AND easy enough to reach in my application? Also bearing readability in mind.


title: How to explain that sample size does not influence project length

text: We have big enterprise projects they normally involve copying data from a source database to a destination database and then setting up a number of additional applications that sync this data etc. The last project contained 250,000 items (rows of data). The next project will only contain 4,000 items. Project managers / business people believe the project should be 1/10 the time to complete because its only a fraction of the size of the last project. What is a good **analogy** I can use to explain that writing code to transfer data from one system to another takes the same amount regardless of the number items - writing it for 1 item or for 100,000,000 will take roughly the same amount of time from a programming point of view.


title: Alternative methods for maintaining JavaScript source

text: I'm looking for other options for maintaining my personal JavaScript namespace. The problem I'm having boils down code _Organization_ Vs. _Performance_. I would simply LOVE to be able to separate major sections of my code into a more "traditional" style. But I haven't because if I were to do that I would probably quadruple the amount of HTTP requests I send out. Essentially I am including two different js files. `jQUery/jQueryUI/my namespace` in one and my implementation in the other. Great for performance in my web-apps... but looking at my JavaScript source makes me scared, confused, and horrified all at the same time. What am I missing here?


title: Rails application - how to optimize/reduce database calls when iterating over a collection

text: What's the best way to optimize a Rails app where you need to pull info from the database for a collection of items? For example, if I am building an online forum system... I would have a number of `Posts` and the posts would have_many `:recommendations` and `:comments` and `:favorites`. When I display the posts in my view, I might need to display this info - like a count of how many comments there are, and whether or not my current user has favorited/recommended the post. I was playing around with this and it seems there are a huge number of DB queries being executed! First I'm grabbing my collection of posts - then, iterating through each one, I am going to the comments table, the favorites table, etc... to get counts or see if records exist for that particular post. So for every post I have, I'm executing 3 separate queries! **Is there a more efficient way to get this data, or are tons of queries like this normal for a scenario like I describe?**


title: Exception Handling in Java web application

text: I know exception handling is a topic often discussed in the world of Java. I've read a few threads on here and SO as well. http://stackoverflow.com/questions/2169339/exception-handling-in-a-java-web- application I find myself identifying with principles such as _Do not suppress or ignore exceptions_ , _Do not catch top-level exceptions_ , and avoid anti-patterns like _Log and Throw_. http://today.java.net/article/2006/04/04/exception-handling- antipatterns#throwingException http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2 **Question #1, is there a different standard of practice when it comes to web applications?** For example, is it a legitimate use case to catch `Exception` for logging purposes and then throw it up the stack?               function void xyz() throws Exception {         try {         } catch (Exception e) {             LOG.error("ERROR: " + e);             throw e;         }     }          function void otherFuncA() throws Exception {         xyz();     }          function void otherFuncB() {         try {             xyz();         } catch (Exception e) {             LOG.error("ERROR: " + e);             throw e;         }     }      I am finding it very hard to accept as a practice because it is generating so much unnecessary code (see `otherFuncA` and `otherFuncB`), affecting the function calls all through the different layers (DAO, Service, Controller, etc.) **Question #2, do I lose information about an error (let's say what caused a`NullPointerException`) if I let unexpected, unchecked exceptions float up to the Controller layer and then, and ONLY then, handle it there (catch `Exception` and throw stack trace)? As opposed to logging immediately, and re- throwing (seen above).**   Of course, I will still check for specific exception types where applicable. I seem to find the stack trace is often a better indicator of what went wrong vs. which specific field was causing an error... I am really interested in input from more experienced developers and what best practices/reasoning guide your exception handling.


title: How do I visualise the feature space partitioning in random forest?

text: I am learning about random forest and found this video https://www.youtube.com/watch?v=gdnIqGbqiYs&list=UUb9svouAi1XHRqlOs8LXbBg very useful. The first 8 minutes explain how to visualise how the feature space is partitioned as the tree is populated during training. In the video however, the partitioning is only explained with respect to two feature vectors throughout the entire tree. It was pretty easy to understand how the feature space is partitioned for two features, as the feature space plots feature 1 vs feature 2. However if I have multiple features selected at random to be used in any node of a given tree, how do I visualise the feature space and how it is partitioned? For example if one branch contains 5 nodes, with 5 features being selected before reaching the leaf node, how is the feature space partitioned to include all 5 features?


title: Writing java doc comments for unit test cases

text: In my opinion, the unit test cases itself serve as a documentation for the code. My company wants me to write detailed java doc comments on top of unit test cases. Is it necessary to do so? Do you write comments like that ?


title: System testing - making sure the system conforms to specification. Validation?

text: After weeks of research I have nearly completed my thesis, yet I am unable to clear up my confusion contained in all previous threads here (and in many books): During system testing, we check the system function against system analysis (functional system design) - but that would fit to a definition of verification according to many books. But I follow ISO12207, which considers all testing as validation (making sure work product meets requirement for intended use). **How can I justify that unit testing or system testing is validation, even though when I check it against specification? Which fullfils the definiton of verification?** When testing that e.g. "Save button" works, is it validation? This picture shows my understanding of V&V, so different from many other sources, including ISTQB etc. ![This is my understanding of V&V - picture taken from the net](http://i.stack.imgur.com/7I040.gif) Essential problem I have is that a book using the same picture also states on another place that: > test activities in the area of validation are usability, alpha and beta > testing. For verification, testable system requirements are defined whose > correct implementation can be tested through system tests. Isn't that the opposite of what the picture says? Most books present the following picture, where validation is just making sure that customer needs are satisfied. Mind you that according to ISO, validation activity is testing. ![enter image description here](http://i.stack.imgur.com/0Enyb.gif)


title: how to properly credit authors of MIT license program

text: Although I have found similar questions on this site they were not what I was looking for. I have modified the source code of an MIT licensed project, and I have added new classes to it as well. Please correct me if I am wrong, but I think that it is legal to add my copyright notice above the license and remove the other one. But how should I attribute the contribution of the previous authors? Should I use a separate file? There are also some html files with no license or copyright notice in them which I also modified. Do I have to handle them differently? My question is different than this question in that I have also modified some of the files of the project I am extending.


title: NoSQL as file meta database

text: I am trying to implement a virtual file system structure in front of an object storage (Openstack). For availability reasons we initially chose Cassandra, however while designing file system data model, it looked like a tree structure similar to a relational model. Here is the dilemma for availability and partition tolerance we need NoSQL, but our data model is relational. The intended file system must be able to handle filtered search based on date, name etc. as fast as possible. So what path should i take? Stick to relational with some indexing mechanism backed by 3 rd tools like Apache Solr or dig deeper into NoSQL and find a suitable model and database satisfying the model? P.S: Currently from NoSQL Cassandra or MongoDB are choices proposed by my colleagues.


title: For user defined data, is it better to use a table of tables or dynamically created tables?

text: In an application that allows users to define their own tables and columns (details of that are not the focus of this question, but imagine a tool that lets users create their own forms and automatically handles storage, just to get the idea) is it better to store each table and column they create in a "table" table and a "column" table, or to dynamically create tables and columns? This "one table to rule them all" question is somewhat related, but in that case the "table" table is more clearly a bad idea. In this case, if you don't go that route then all your queries will have to be dynamically generated. Even though the argument "don't write yet another application designer tool for non-programmers, so you can keep adding features until you are basically having users develop in a crummy version of, say, Visual Studio, using your custom crummy language" is pretty reasonable, I've had a lot of projects with some version of the user defined tables requirement and this question is about _how_ to implement it. _Whether_ to implement it is another question, but probably too specific to particular applications to be a good question here.


title: Hiring Developers - Securing Source Code

text: I have a popular web-based app, and now suddenly my main developer has disappeared. Although I've found other great developers but I don't want to distribute the source code to everyone. Is there any way I can have them work on it while keeping the source code safe? Thanks


title: Design pattern for configuring objects

text: ### Context In a Cocoa application I am developing, I need to load a data model that is defined in plist files. So, I have something like:               root (Array)     ---- item (Dictionary)     -------- name : "objects" (string)     -------- prefab : "object" (string)     -------- children : (Array)     ...     ---- item (Dictionary)     -------- name : "actions" (string)     -------- prefab : "action" (string)     -------- children : (Array)      So, the previous data model is loaded in the code to become an object representation using the language's primitives (arrays, dictionaries, strings, ... etc). No custom classes here. When I load that model, I know that an item in the table view can have children if the "prefab" key is set. When "add child" is pressed, I go to the prefabs (some other plist) and fetch that prefab's structure. e.g:               root (Array)     ---- item (Dictionary)     -------- name : "object" (string)     -------- parameters : (dictionary)     ------------ key "object_id" : value ""     ------------ key "x_position" : value 0     ...      As you can see, from the prefab in the first model, I can go to the second plist and fetch a structure that is defined in a plist. All loaded using a plist library, without any subclass creation whatsoever. There is a single prefab factory class that contains the prefab structures, and instantiates and initializes the object from the prefab with the configuration data. ### Problem I hope you see the grave danger in this design. The model contains both user generated data as well as configuration data!! _EEEEK!!!_ ... Sheesh, that's so bad... The problem haunted me when I started exporting the model after the user of the app interacted with the model though the UI. The exported model would contain the configuration data (such as the prefab key), which makes the exported data rigid and un-upgradable. If I were to change the prefab key in later version of the app, to something else, and you load an old model, that model will load the old configurations with it, in our case, referencing the old prefab. ## Question I need help find a proper design pattern that clicks with this data driven design that I have, by providing the configuration data from a separate file, and somehow, linking it with the data model.


title: What are typical responsibilities and achievements recorded on a CV, for a programming job?

text: I'm brushing up my CV/resume and trying to think of responsibilities and achievements from my past jobs and projects. It seems there aren't many, but probably there're some that I just don't identify as worth mentioning to a employer. What kind of responsibilities and achievements does your job include and which of them do you list on your CV/resume?


title: Javascript Use of Window Object through alternate means

text: Disregard your usual paradigms for a mere moment here.... I've seen a few sites who have used the following logic:               a=[];     b=a["sort"];     c=(b)();     c["alert"](1); // intended output: Alert displaying "1"...      supposedly to access (I'm guessing here) the primitive of the sort function to gain access to the window object, and then using that to access "alert"... I've tried executing this ages ago, and it worked a charm... But some twelve months or so later, I tried to run it again... and it's failed to execute, and given the following error:               TypeError: can't convert undefined to object      My question is, why wouldn't this logic work? It seems quite sound... Or is it? And yes, I know that I could just do `alert(1)` and be done with it, but I'm trying to get an understanding of alternate ways of coding... I work in IT security and I know certain people have ways of using XSS to find alternative ways to perform generic functions to compromise systems...


title: Where to start fixing a complex bug?

text: I'm trying to solve a complex bug in our codebase , but the problem seems to be coming from a lot of places to the point that i dont know what to change first . do you have any procedure or guidelines todo in such a situation ?


title: Capitalization convention in assembly?

text: Is there any convention on what to capitalize in (x86) assembly? For example, which one of these 'looks best'? (Or maybe none of them do?)               [BITS 32]     %define MACRO 1     MyLabel:         MOV EAX, 2      versus               [bits 32]     %define macro 1     MY_LABEL:         mov eax, 2      versus               [Bits 32]     %define MACRO 1     MyLabel:         mov EAX, 1      versus all the other possibilities?


title: How do I go about releasing my application as open source?

text: I have created my own forum on ASP.NET MVC 3 and Razor. It's a decent forum with, say, version 1 functionality. I plan to work on other features as well after my release of this version. 1) What site apart from Codeplex can I post my application on as open source? 2) What are the guidelines I need to follow before posting my application regarding my code etc? 3) I want my application to be used by others, so do I have to worry about anything like making a documentation about my code, etc?


title: Where's the unix philosophy community?

text: I am trying to implement my computer system following the unix philosophy i.e. I want to edit files, read/send email, store data and browse the web, all using tools that comply with the unix philosophy. Others have defined the unix philosophy better than I, but suffice it to say that I mean tools that "do one thing well", work with unix pipes and can be easily scripted. I'm looking at tools like ed, edbrowser, nmh and uzbl. However, I wonder where like-minded people on the internet 'hang out' (e.g. a wiki or forum)? Is there any internet community, or linux distribution community, that has a large group of people who also wish to implement all their work through unix philosophy tools? Any suggestions would be much appreciated.


title: How to adopt agile methodology for developing firmware/embedded-systems-software?

text: I've always wondered how to apply agile methods really are in large complex embedded system software (100+ engineers). Firmware development has some unique characteristics that make it difficult to do agile (ie. Hardware is not available until late in the dev cycle; Once product is released, can't easily update firmware; etc...) The norm in this kind of development is thick documentation and grueling peer reviews. You can't get a simple code fix like renaming a variable without 2-3 signatures. (I exaggerate a little but this is typical. Additionally, a lot of people do take shortcuts and the Project Managers even approve them especially in the face of hard market deadlines.) I would like to hear any tips or guidelines on how to adopt agile methodology for firmware development projects.


title: Is NoSQL a good fit for a graphing app, and how can I compare different NoSql Servers?

text: I am traditionally a MsSQL or MySQL developer - I have been prototyping a new application that involves storing data from many targets. I have seen that the app appears to get slow after scaling to 10k targets after inputting around 300k results for each (64 bit ints) - especially once I start trying to average and/or graph a few targets at once. Once the app is deployed I will need to add around 1k targets a month and store one data point from each for each and every minute for approx 2 years. I have never used NoSql, but from reading, it sounds like a good fit - create a document for each target and keep adding fields for each target. So, I was just wondering, is NoSQL the way to go for this project or should I be sticking with traditional SQL - and/or can anyone offer any advice? And the second part - If NoSQL is a solution can anyone recommend a fair comparison as I am getting lost in biased reviews that seem to say each solution is superior!?


title: Offensive programming / coding

text: Last time I heard about "offensive programming/coding". I am not sure what it exactly mean. Why it is better, from defensive programming? Can someone give me some examples or answers?


title: What industry/programming is right for a careful coder?

text: My approach to programming is very deliberative. I spend a lot of time planning and designing before I code, even for the most basic tasks. I always try to make my code very simple, design everything very elegantly, and always to leave space for flexible changes later on. Some might say I think too much about what else could happen. I wonder, what industry and what tasks would be best suited to someone who works the way I do? Are there jobs out there that require high precision without a lot of schedule pressure, and if so, where should one look for them?


title: Is .NET WCF worth the effort?

text: Maybe it's me, but I've never encountered nearly as many problems, annoying challenges, indirect error messages and general frustrations with any other technology as I have with WCF. What are the ACTUAL benefits? Not the MS Press Release benefits of 'a unified architecture for something something that's not going to work anyway.' And are those benefits worth the annoying frustrations? I'm normally a big MS fanboy over here, but I just can't get behind WCF.


title: Why do we write mock objects when writing unit test cases?

text: We are currently writing unit test cases in our project . The implementations for database methods exist and is working fine . In this case why do we need to write mock objects ? Is there any specific reason ? Why can't I test the DAO implemntation directly?


title: Does unit testing lead to premature generalization (specifically in the context of C++)?

text: ### Preliminary notes I'll not go into the distinction of the different kinds of test there are, there are already a few questions on these sites regarding that. I'll take what's there and that says: _unit testing in the sense of "testing the smallest isolatable unit of an application"_ from which this question actually derives ### The isolation problem What is _the smallest isolatable unit_ of a program. Well, as I see it, it (highly?) depends on what language you are coding in. Micheal Feathers talks about the concept of a _seam_ : [WEwLC, p31] > A seam is a place where you can alter behavior in your program without > editing in that place. And without going into the details, I understand a seam -- in the context of unit testing -- to be a place in a program where your "test" can interface with your "unit". ### Examples Unit test -- especially in C++ -- require from the code under test to add _more seams_ that would be strictly called for for a given problem. Example:   * Adding a virtual interface where non-virtual implementation would have been sufficient   * Splitting -- generalizing(?) -- a (smallish) class further "just" to facilitate adding a test.   * Splitting a single-executable project into seemingly "independent" libs, "just" to facilitate compiling them independently for the tests. ### The question I'll try a few versions that hopefully ask about the same point:   * Is the way that Unit Tests require one to structure an application's code "only" beneficial for the unit tests or is it actually beneficial to the applications structure.   * Is the code generalization that is needed to make it unit-testable useful for anything _but_ the unit tests?   * Does adding unit tests force one to generalize unnecessarily?    * Is the shape unit tests force on code "always" also a good shape for the code in general as seen from the problem domain? I remember a rule of thumb that said don't generalize until you need to / until there's a second place that uses the code. With Unit Tests, there's _always_ a second place that uses the code -- namely the unit test. So is this reason enough to generalize?


title: options for data analytics for time series store

text: I'm building an Internet of Things solution that has a number of real time feeds. I need to make a couple of design decisions with regards to the data store and reporting and looking for input. I have two deployment models, local where a small Linux server captures multiple streams usually a new data point each second and record length is small, basically a fixed format message of about 20 bytes. The other model is cloud based where the transaction rate will be much higher, up to 1000 data points a second. Concentrating on the local model first, my prototype uses SQLite under MONO and works fine in a traditional RDMS manner. However I'm aware that RDBMS isn't optimal for time series systems and possibly a NOSQL solution might be better. I'm having a re-think on the SQL approach due to my real time analytics requirement. I want to be able to easily report on SUM, COUNT, AVERAGE, MEAN, SD, MIN, MAX on potentially each of the time series datasets, basically have the system recalculate these for each new data point. Although I haven't done any performance testing, I can see if I have a year or more data the dataset size is going to be pretty large (20 bytes / second over a year is 600MB and I could have up to 30 different time series datasets) and won't be great for real time calculation of averages etc. in normal SQL. I also want to keep the size / cost of the server low so won't be able to add gobs of CPU or memory but disk space should be OK. The other option I have is that my system can store the delta (changes) to the real time feeds instead of the regular data point, which will save about 80% of the disk space. However I don't know of an easy way to do set calculations like running averages if I am storing deltas (as far as I know not possible with standard SQL statements but I could be wrong). Given my use case above I have 3 questions: 1) Should I seriously consider a NOSQL data store? Do you have any suggestions on the advantages of a NOSQL store for this model? 2) How I can best do real time set calculations like average without a lot of complexity or hardware? I have platform options of either MONO or NODE on Linux or Windows. 3) How to do efficient real time set calculations (especially averages which will be the majority of calculations) on either SQLite or a NOSQL DB when I'm storing deltas?


title: Abstract exception super type

text: If throwing `System.Exception` is considered so bad, why wasn't `Exception` made `abstract` in the first place? That way, it would not be possible to call:               throw new Exception("Error occurred.");      This would enforce using derived exceptions to provide more details about the error that occurred. For example, when I want to provide a custom exception hierarchy for a library, I usually declare an abstract base class for my exceptions:               public abstract class CustomExceptionBase : Exception     {         /* some stuff here */     }      And then some derived exception with a more specific purpose:               public class DerivedCustomException : CustomExceptionBase     {         /* some more specific stuff here */     }      Then when calling any library method, one could have this generic try/catch block to directly catch any error coming from the library:               try     {         /* library calls here */     }     catch (CustomExceptionBase ex)     {         /* exception handling */     }      Is this a good practice? Would it be good if `Exception` was made abstract? EDIT : My point here is that even if an exception class is marked `abstract`, you can still catch it in a catch-all block. Making it abstract is only a way to forbid programmers to throw a "super-wide" exception. Usually, when you voluntarily throw an exception, you should know what type it is and why it happened. Thus enforcing to throw a more specific exception type.


title: Software license restricting commercial usage like CC BY-NC-SA

text: I want to distribute my software under license like Creative Commons Attribution - Non commercial - Share Alike license, i.e.   * Redistribution of source code and binaries is freely.   * Modified version of program have to be distributed under the same license. Attribution to original project should be supplied to.   * Restrict any kind of commercial usage. However CC does not recommend to use their licenses for software. Is there this kind of software license I could apply? Better if public license, but as far as I know US laws says that only EULA could restrict usage of received copy?


title: Benefits of using config files over making many small classes?

text: My friend and I are building a mobile game and ran into the following design problem: We will have many different types of units all with different stats and abilities. However, all unit types should have a few commonalities (for example, they would all have a totalhealth attribute). We were trying to decide what the best way of representing these units would be. My friend suggested simply making a new class for each unit type. I feel that having hundreds of different classes feels wrong, but can't quite figure out what's so bad about it. My alternative is to put the unit type information into either configuration files or a database (which will also solve the issue of enforcing every unit type to have a few common attributes with a schema). And then have a master unit class to instantiate types of units from the db. What is the proper way of architecturing this?


title: Pitfalls of combining dependant traits and exceptions in same file as interface in php

text: What are the potential pitfalls of combining related class like objects (interfaces, traits, custom exceptions) in the same source file? For code reuse and only loading what I need I always separate out full class's into separate files. But interfaces, traits, and extended exceptions don't seem to need that same level of granularity. I have been trained that all classes and class like objects (interfaces, extended exceptions, etc.) should be given their own source files. But now I am starting to work with traits and after getting advice about combining traits and interfaces, to have the ability to have something along the lines of multiple inheritance, I am combining the interface and the trait in the same source file. That way the only way to access traits is to implement the corresponding interface. Once the class calls the autoloader to get the source for the interface it also loads the trait. Not all classes that implement the interface will use the trait for functionality, but most will, and those that don't will just not _use_ the trait. I also will use extended Exceptions for an interface along the lines of PDOException. These are exceptions only thrown by classes that extend or implement a class. So now my **Stackable.php** interface file looks like:               interface Stackable{       public function add($content);       public function _registerParent($parent);       public function _checkLoop($child);     }          trait StackableTrait{       private $containter_contents = array();       private $container_parent = NULL;            public function add($content){         if(is_a($content, "Stackable")){            $content->_registerParent($this); //prevents adding twice and creating loops.         }elseif(!is_string($content)){            $this->_checkLoop($content);         }         return $this->container_contents[] = $content;       }       public function _registerParent($parent){         if(empty($this->container_parent)){           $this->container_parent = $parent;           return;         }         throw new StackableException("Object has already been added to a parent");       }       public function _checkLoop($child){         if(in_array($child,$this->container_contents,TRUE){           throw new StackableException("Object has already been added to a parent");         }elseif(!empty($this->container_parent)){           $this->container_parent->_checkLoop($child);         }       }     }          class StackableException extends Exception{}      As you can see all of the contents of the file are interrelated, any class that wants to use the StackableTrait will need to also implement the interface so the class checking in the trait functions will work. And only things using _StackableTrait_ or implementing _Stackable_ will have access to throw _StackableException_.


title: What kind of transform is this?

text: I have a function that linearly "remaps" a value from a given interval to an other interval? The function remaps a value from a given interval [oldMin, oldMax] to another interval [newMin, newMax] using this formula:               newVal = newMin + (newMax - newMin) * (oldVal - oldMin) / (oldMax - oldMin)      If it helps identify what type of transform it is, the above formula is just a reformulation of the following equation. All I did was re-arrange the terms to express `newVal` on the left hand side of the equation so it is a function of all the other parameters: ![enter image description here](http://i.stack.imgur.com/wukZX.png) Is there a standard name for the remapping transformation?


title: What is the advantage of a programmers VM apart from portability

text: I can understand the benefits of Java running on a JVM. Portability. Nice simple reason. But I have always been puzzled as to why Microsoft brought out their own version of a JVM - .NET. C# is supposed to be a fine language (haven't used myself) but could Microsoft have launched product to use native. ie to generate an exe? My colleague is learning F#. The reason it has to be a language which runs on .NET is because the Microsoft Lync API which will be used is only available on .NET. ie there is no C API for Lync. A cynical view may be that the reason is vendor lockin. F# will only run on a Microsoft platform (or C# for that matter) and so program is locked in. But maybe I am missing some other benefit of a VM platform?