Learning on the Job: JavaScript, CoffeeScript, BackBone and jQuery

I have avoided JavaScript for as long as I could. I simply think that it is a very, very dirty scripting language. I have nothing against curly braces, I work with PHP almost every day, I'm fine with them. I think the biggest issue is that I'm pretty much self taught and started out with PHP. I've worked previously with jQuery, so that dealt pretty much with my JSfobia (as manipulating a few elements on a page did the trick for me, as well as the tons of pre-made plugins out there). Now I just have to take a step further. I've recently done some exploration, and I must say that I like the way that RoR looks like. And well - there is a similar way of writing JS - CoffeeScript. On top of that, there is an project coming up for me ( a week or so ) to develop an iPhone app, now I already know that I'll be storing data on the phone and then displaying it. Nothing too complicated yet, but these are new grounds for me. I will probably be working with PhoneGap to make it an app, since I don't really want to start messing in Objective-C (although I could, but without C/C++ knowledge it may take a lot more time than I'd want it to) So - this brings to my question. Is it okay if I start learning CoffeeScript with just basic understanding of JS, and start trying to use Backbone.js with jQuery/+jQuery Mobile for the project ? Open for any additional suggestions as well.


How to refactor code to some common code?

**Background** I'm working on an ongoing C# project. I'm not a C# programmer, primarily a C++ programmer. So I was assigned basically easy and refactoring tasks. The code is a mess. It's a huge project. As our customer demanded frequent releases with new features and bug fixes, all other developers were forced to take brute force approach while coding. The code is highly unmaintainable and all other developers agree with it. I'm not here to debate whether they did it right. As I'm refactoring, I'm wondering if I'm doing it in the right way as my refactored code seems complex! Here is my task as simple example. **Problem** There are six classes: `A`, `B`, `C`, `D`, `E` and `F`. All of the classes have a function `ExecJob()`. All six implementations are very similar. Basically, at first `A::ExecJob()` was written. Then a slightly different version was required which was implemented in `B::ExecJob()` by copy-paste- modification of `A::ExecJob()`. When another slightly different version was required, `C::ExecJob()` was written and so on. All six implementations have some common code, then some different lines of code, then again some common code and so on. Here is a simple example of the implementations:               A::ExecJob()     {         S1;         S2;         S3;         S4;         S5;     }          B::ExecJob()     {         S1;         S3;         S4;         S5;     }          C::ExecJob()     {         S1;         S3;         S4;     }      Where `SN` is a group of exact same statements. To make them common, I've created another class and moved the common code in a function. Using parameter to control which group of statements should be executed:               Base::CommonTask(param)     {         S1;         if (param.s2) S2;         S3;         S4;         if (param.s5) S5;     }          A::ExecJob() // A inherits Base     {         param.s2 = true;         param.s5 = true;         CommonTask(param);     }          B::ExecJob() // B inherits Base     {         param.s2 = false;         param.s5 = true;         CommonTask(param);     }          C::ExecJob() // C inherits Base     {         param.s2 = false;         param.s5 = false;         CommonTask(param);     }      **Note that, this example only employs three classes and oversimplified statements. In practice, the`CommonTask()` function looks very complex with all those parameter checking and there are many more statements. Also, in real code, there are several `CommonTask()`-looking functions.** Though all the implementations are sharing common code and `ExecJob()` functions are looking cuter, there exists two problems that are bothering me:   * For any change in `CommonTask()`, all six (and may be more in the future) features are needed to be tested.   * `CommonTask()` is already complex. It will get more complex over time. Am I doing it in the right way?


Pointer indexing

I am currently reading a book titled "Numerical Recipes in C". In this book, the author details how certain algorithms inherently work better if we had indices starting with 1 (I don't entirely follow his argument and that isn't the point of this post), but C always indexes its arrays starting with 0. In order to get around this, he suggests simply decrementing the pointer after allocation, e.g.:               float *a = malloc(size);     a--;      This, he says, will effectively give you a pointer that has an index starting with 1, which will then be free'd with:               free(a + 1);      As far as I'm aware, though, this is undefined behavior by the C standard. This is apparently a highly reputable book within the HPC community, so I don't want to simply disregard what he's saying, but simply decrementing a pointer outside of the allocated range seems highly sketchy to me. Is this "allowed" behavior in C? I have tested it out using both gcc and icc, and both of those results appear to indicate that I'm worrying over nothing, but I want to be absolutely positive.


Python API: Extension Module or Pure Module

We have a C++ application, with C++ interfaces changing regularly during development. We also have a C API which is designed to be stable in spite of such changes; the C API is tighly focused on operations which client code might want to do. Now, we want to add a Python API to make it easy for outside clients (or our own team) to create scripts controlling the application. Given the volatility of the C++ code and the by-design stable nature of the C API, it makes sense to build the Python API over the C one. I know the way to do this is to provide an extension module (implemented in C++) which will be usable in Python and wrap the C API functions. What I am considering is whether I should make this extension module _the_ Python API (and thus make it as Pythonic as possible), or whether I should keep this an "implementaion detail" of the Python API and build a pure Python module on top of it, which would serve as the actual external API. The extension module would then be a very thing wrapper around the C functions, resigning on being nice Python code. I see the following pros and cons: **Python API is a C++ extension** This would be more efficient, as there are less intermediary layers. At the same time, it requires boilerplate code to provide Pythonic behaviour in C++, and the code is generally harder to write and maintain (reference counting, pointer tables etc.). **Python API is a module wrapping the C++ extension** This allows us to write Pythonic code in Python, which is easier and less error-prone. It would probably lead to a richer, more complete API as well, since adding functionality is easier and faster in Python than in C++. As a downside, there's runtime and memory overhead of the extra layer, as well as the need to maintain two separate bits of code for one thing. * * * My primary question is: are there any obvious upsides or downsides to some of the approaches that I failed to consider, especially ones that make one choice clearly superior to the other? Also, is there a widely accepted "best practice" for this type of thing? Or a "checklist" to help choose the correct approach for a particular situation?


Do you track progress during a agile sprint (iteration)

We have recently adopted (or are trying) to adopt managing our projects in an Agile manner. During our first sprint I asked our Scrum master ( _who also happens to be our primary resident Agile go-to person_ ) if it was possible to see the progress of our sprint so we could identify if we were on schedule or not (an possible risk). They turned around and said you don't do that at a sprint level? I'm really new to agile but I thought it would be very beneficial to know if a sprint is on target or not. However perhaps this is too hard to do at this stage? If so, are there any suggestions/methods on how you could identify if a sprint is at risk?


Is it easier to define and recognize poor application design than good application design?

A couple recent questions focused on "well designed applications" and "poorly designed applications". Looking at the responses it appears to me that it might be easier to recognize and define poor code and poorly designed applications than it is to define what good code and good/correct application design is. What do you think?


What should be a fair amount of time in an interview before rejecting a candidate?

As a panelist for technical interviews, you often come across candidates who have all the requried educational qualifications, skill sets and experience level on resumes, but struggle to answer even the most basic questions. Ideally, technical interviews should try to check different aspects of a candidate and test them on various skills. So, if the candidate falters on one aspect, one should test the other ones before coming to a conclusion. But often, if a candidates falters on the first few questions, the red flag rises up pretty quickly. What in your opinion should be the bare minimum time spent with a candidate before making a fair accessment of his/her skills and suitability for the job?


What is the formal definition of a meta package?

There are several examples of packaging where an application package is built, named, described, even licensed, but contains only setup code and dependencies -- it has no first-class runtime software of its own. I would call this "meta- packaging". This seems to be particularly popular in the open-source world, including examples like _kde-meta_ (Gentoo Portage), _Plone_ , and I'm sure lots of others. I can see how it's a useful practice, but despite it existing as a practice, I couldn't find a formal definition of either "meta-packaging" or "meta-egg" (Python) in searching the web. Is that not the correct term? If it is, is it such common-sense that it needs no formal definition? If not, what is the correct way to put it?


Fast lookup hash map implementations

I'm in the process of implementing a programming language on top of LLVM. For my polymorphic system, I'm looking for suggestions for a ultra-fast dictionary. I am not concerned with insert time, as these maps are only written to a dozen times or so. But I'm looking for super fast lookup. I did some research on the open addressing dict implementation in Python, and it seems pretty fast (a few shifts and bitmasks in the best case). However, I want to do my research. Does anyone know of a super fast dictionary/hashmap implementation? In this case my data will most likely be pointers as keys and pointers as values. Or if it works out better, I could probably get by with integers as keys. Any papers or discussions on the subject would be great.


Why do C arrays not keep track of their length?

What was the reasoning behind not explicitly storing an array's length with an array in `C`? The way I see it, there are overwhelming reasons _to do so_ but not very many in support of the standard (C89). For instance:   1. Having length available in a buffer can prevent buffer overrun.   2. A Java-style `arr.length` is both clear and avoids the programmer from having to maintain many `int`s on the stack if dealing with several arrays   3. Function parameters become more cogent. But perhaps the most motivating reason, in my opinion, is that usually, no space is saved without keeping the length. I would venture to say that most uses of arrays involve dynamic allocation. True, there may be some cases where people use an array allocated on the stack, but that's just one function call* - the stack can handle 4 or 8 bytes extra. Since the heap manager has to track the free block size used up by the dynamically allocated array anyway, why not make that information usable (and add the additional rule, checked at compile time, that one can't manipulate the length explicitly unless one would like to shoot oneself in the foot). The only thing I can think of on the other side is that no length tracking may have made compilers simpler, but not _that_ much simpler. *Technically, one could write some kind of recursive function with an array with automatic storage, and in this (very elaborate) case storing the length may indeed result in effectively more space usage.


Suggestions for Programs to develop for learning

i wonder apart from those very simple hello world apps, what other programs should i try developing for learning. i am entering uni next year and wonder what kind of programs will be developed in that environment. this is not really a language specific thing, but if you want to know what i use currently mainly   * windows: C#/WPF - i studied java/vb etc in poly but i think C# is the way to go, maybe even F#   * web: PHP/MySQL, Zend Framework/Doctrine, + HTML/CSS/JS(jQuery) of course. looking to try google app engine with python too.  for now, i am thinking of   * todo lists   * apps that integrate with api eg. twitter/tumblr which i use   * text editor - i am currently trying to develop a text editor that uses markdown and generates html files for viewing (link to blog entry). not very pratical after i started developing it. cos when editing theres no formatting and in HTML format, i cannot edit directly    * blog software (for web)


Does Abstract Factory Pattern scale?

I'm still trying to understand design patterns here, after learning the Abstract factory pattern , I realised that this pattern will not scale well. Take a look at the uml diagram of the abstract factory pattern ![uml diagram](http://s11.postimg.org/okmvliygj/Abstract_Factory.gif) If I have to create a new 'AbstractProductC', I will have to add an abstract method 'CreateProductC' in 'AbstractFactory' which effects the implementation of both ConcreateFactory1, ConcreateFactory2. My question here is, does Abstract Factory pattern scale at all (or) I'm I thinking in the wrong direction here ? thanks in advance


How Do You Estimate Project Hours Using Pivotal Tracker If You Are a Services Firm?

I am new to Pivotal Tracker and trying to learn how best to use it for our business. We are an app development consulting services firm. As you guys know, clients want to have an idea of total time and cost before they sign any contract. How are you guys mapping your project on Pivotal to total hours and timelines? Any best practices? Pointers? Right now my team and I have broke the project into stories (love how Pivotal gets us thinking on a much lower level) and have roughly mapped out points to hours.   * 1 - 1 hour    * 2 - 2 hours    * 3 - 6 hours    * 5 - 10 hours Then we are basically thinking of 2 as a quarter day, 3 as 3/4 a day, and 5 as a full day or a bit longer. I then calculate how many 1s, 2s, 3s and 5s we have to get a rough estimate of total hours. Pivotal gives me an estimated completion date based on default velocity (I know this can change). I then report the rough total hours, cost, and due date to my client. I do understand that this is agile and iterative where things change, but when people hire you as a consultant they want costs up front.


Composition vs. Inheritance

Here's what is given:               public interface Request {}          // there are 20 subclasses of Request     public class CreateUserRequest implements Request {       @NotEmpty       public String userName;     }          // request processor is a thing that aimed to process requests     public interface RequestProcessor<TRequest extends Request> {       boolean processRequest(TRequest request);     }          public class ServiceFacade {       // 20 processors like this one       private final RequestProcessor<CreateUserRequest> createUserRequestProcessor;            public ServiceFacade(         RequestProcessor<CreateUserRequest> createUserRequestProcessor) {         this.createUserRequestProcessor = createUserRequestProcessor;       }            // 20 methods like this one       public boolean createUser(CreateUserRequest request) {         createUserRequestProcessor.processRequest(request);       }     }      An object implementing `RequestProcessor<T>` is aimed to process requests of type `T`. Moreover, it is responsible for handling all the related errors (like invalid request, DB access failure and so forth). So, the workflow for `CreateUserRequest` should look like this:               request     validate/throw     make sure user doesn't exist yet/throw     create user      As usual, other types of requests may require more steps to be performed. **As an illustration** : in case of `AddUserAsFriendRequest` we'll have to check that both users exist and that friend candidate has allowed others to add him as friend. Oh, and also, if one user adds more than 10 friends in a day, he's then limited to 1 friend per 2 hours for the rest of the day. **The question is** , which hierarchy/structure/approach should I use in order to be able to extend this functionality in both "number of request types" and "request process workflow". There are only 2 approaches I see. # Inheritance               public abstract class ValidatingRequestProcessor<TRequest extends Request>     implements RequestProcessor<TRequest> {       protected final Validator validator;            public ValidatingRequestProcessor(Validator validator) {         this.validator = validator;       }            public boolean processRequest(TRequest request) {         Set<ConstraintViolation<TRequest>> violations =            validator.validate(request);         if(!violations.isEmpty()) {           return false;         }              return processValidatedRequest(request);               }            protected abstract boolean processValidatedRequest(TRequest request);           }          public class CreateUserValidatingRequestProcessor     extends ValidatingRequestProcessor<CreateUserRequest> {       public CreateUserValidatingRequestProcessor(Validator validator) {         super(validator);       }            protected boolean processValidatedRequest(TRequest request) {         // request is valid, so I can try to create user here       }     }      and so forth here. In case of `N` "logical steps", I'm going to have `(N-1)` nested `extends` and `N` classes:               class A implements RequestProcessor {}     class B extends A {}     class C extends B {}     class D extends C {}     ...     class Z extends Y {}          RequestProcessor requestProcessor = new Z(); // TADA!      * * * # Composition               public class ChainingRequestProcessor<TRequest extends Request>     implements RequestProcessor<TRequest> {       private final RequestProcessor<TRequest> processorA;       private final RequestProcessor<TRequest> processorB;            public ChainingRequestProcessor(         RequestProcessor<TRequest> processorA,         RequestProcessor<TRequest> processorB) {               this.processorA = processorA;         this.processorB = processorB;       }            public boolean processRequest(TRequest request) {          return processorA.processRequest(request) &&           processorB.processRequest(request);       }     }          public RequestValidatorProcessor<TRequest extends Request>     implements RequestProcessor<TRequest> {       private final Validator validator;            public RequestValidatorProcessor(Validator validator) {         this.validator = validator;       }            public boolean processRequest(TRequest request) {          return !validator.validate(request).isEmpty();       }     }          public CreateUserProcessor     implements RequestProcessor<CreateUserRequest> {       public boolean processRequest(CreateUserRequest request) {          // not sure whether request is valid or not         // can try to create user here       }     }      and so forth. In case of `N` "logical steps" I'm just going to have `N` classes. So:               class A implements RequestProcessor {}     class B implements RequestProcessor {}     class C implements RequestProcessor {}     class D implements RequestProcessor {}     ...     class Z implements RequestProcessor {}          // just guess     RequestProcessor requestProcessor = new A(new B(), new C(new D())); // TADA!      * * * **Which approach is better for this task? Better means:**   * Easier to modify logic   * Easier to add logic   * Easier to test


Are Data Warehouses bespoke products that are tailored towards the specific needs of one single organisation?

Are Data Warehouses bespoke projects that are developed to meet the needs of a specific organisation or can you buy off the shelf products that would meet the needs of many organisations? I am talking about a product that will integrate information from many different systems e.g. finance system, sales system, production system etc for management reporting. Different organisations have different systems that have different database designs. For example, organisation A may use finance system A, which has a completely different design to finance system B used by organisation B. Therefore I believe that Data Warehouse products are bespoke products and it is not possible to develop a product that could be used by many organisations e.g. organisation A and organisation B; that have the same types of systems e.g. Finance, Sales etc. Am I correct in this analysis?


Should I use WCF, raw Sockets, or something else to send receive data from a command line app?

I have a command line app, that will be multi-threaded and serve inbound and outbound clients. It will send and receive Binary data structures generated by protobuf.net My question is, how should I go about having the clients send and receive data? Does my usage of protobuf.net mean that WCF is less relevant? or just certain serialization features?


WCF service and security

Been building a WP7 app and now I need it to communicate to a WCF service I made to make changes to an SQL database. I am a little concerned about security as the user name and password for accessing the SQL database is in the App.Config. I have read in places that you can encrypt the user name and password in the config file. As the username and password is never exposed to the clients connected to the WCF service, would security in my situation be much of a problem? Just in case anyone suggests a method of security, I do not have SSL on my web server.


How much harder is it to learn Open GL ES 2.0 than 1.x

I have to learn open GL and get a basic open GL app built. Is it easier to learn open GL 1.x ES as apposed to 2.0 which uses shader language? Also is it advisable to learn 1.x before 2.0?


Arguments againts checking-in binary files into SCMs

I work for a company that primarily builds Java applications and I'm trying to convince everybody to stop checking-in binary files (dependencies and final products) to SCM. They know it is a bad practice but they think that "it works" and it is not really a problem even when many people know about Maven and other tools for building besides Ant. Both PMs and programmers (around 50 people) are ready to listen to any argument against and even acknowledge that it is a waste of backup space but I want to be really convincing because the habit change would involve a lot of effort. What arguments do you use to support a change? **Edit:** Okay, it makes sense to make a distinction between files that almost do not change, like dependencies, and generated files. Even so, I'm interested in reasons against the latter.


How to convert a word document (.doc /.docx) to RTF format ?

I have a requirement for an application that takes Doc, Docx content (means whole document) and converts them to RTF content. I am trying but it does not convert document content to RTF content. But it just change the extension .doc/.docx to .rtf, not content of document.


How to solve this problem without the use of if-else statements?

I have just started my C++ lecture class. And the teacher has given us the following assignment. > Write a program that determines whether a number is even or odd. The logic I would use for the program is.   1. Get input `a`.   2. Store `a % 2` as `b`.   3. If `b` is 0, then `a` is even, else `a` is odd. The catch though, is that we have to write the program without the use of a `if-else` statement. I have been thinking on how to approach the problem for the past few hours, but I have no clue what to do. Any hints or suggestions?


Strategy to use version control on a modular system

Let's suppose (for simplicity) that we have an application featuring client and server; is there a better idea to use one repository for both or a pair of separate repositories? Mixing them will probably make easier to track correlated changes and maintain correlated branches (i.e. protocol evolution), but on the other hand will make the individual development more cluttered...


It is inconsiderate to place editor settings inside code files?

I know this is kind of a subjective question, but I'm curious if there's any good reason to place (or not place) editor settings inside code files. I'm thinking in `vi` modelines, but it is possible that this applies to other editors. In short, a `vi` modeline is a line inside a file that tells `vi` how to behave (indent with spaces or tabs, set tabwidth to X, autoindent by default or not, ...) that is placed inside a comment, so it won't affect the program/compiler when running. In a `.c` file it could be similar to               // vim: noai:ts=4:sw=4      On one hand, I think this shouldn't be inside the file, as it is an editor setting and so belongs to an editor configuration file or property. On the other hand, for projects involving developers outside one company (that are not imposed an editor/settings) or collaborators on github/bitbucket/... it is an easy way to avoid breaking the code style (tabs vs spaces for example), but only for the ones that use that editor though. I cannot see any powerful enough reason to decide for or against this practice, so I am in doubt of what to do.


Flat addressing vs. segmented addressing

Is flat addressing model generally superior to a segmented one? If so, why? If not, what instances would call for each over the other and why? My understanding of memory models surrounds the IA32/x86-64 Architecture. So if you give architecture specific examples, they will be most helpful if kept relevant to that.


What's the simplest way to provide a portable, locally running webservice server application?

We have a large website running that offers a JsonRpc web service. For offline demonstration purposes, I want to realize a portable, locally running webserver with a minimalistic feature replication of the live webservice, and bundle this together with Html files which do Ajax requests to it. This local server executable should have as little dependencies as possible. It's going to be run and presented by non-devs on non-dev Windows machines, so I would prefer having a simple executable plus the service code. The language would need to be .NET, PHP or Java. I'll need a small database behind which probably will be Sqlite. It's important to say that, for reasons I won't get into here, we cannot use the original web service code, but we have to rewrite it new for the local demo server. This is why I want to put minimal effort in the local server tech. An installer for distribution is not mandatory, it's okay to have a zip file with an executable in it which starts up the local webserver. **What would you recommend realizing these requirements?**


Exceptions vs ErrorCodes when working with devices

Out team is at the cusp of a new project. One of the components at the boundary of the system is the component which interacts with a printer through an external COM component (referenced as a usual dll). The COM component returns integer codes if there were an error whilst command execution. Lets consider a concrete code.                 public class OperationException:Exception {         public int ErrorCode { get; private set; }         public string ErrorDescription { get; private set; }              public OperationException(int errorCode, string errorDescription) {             ErrorCode = errorCode;             ErrorDescription = errorDescription;         }     }          //The exception throwing way     public class Provider1:IFrProvider {         private readonly IDrvFR48 driver;              public string GetSerialNumber() {             //must read status before get SerialNumber             int resultCode = driver.ReadEcrStatus();             if (resultCode != 0) {                 throw new OperationException(resultCode, driver.ErrorDescription);             }             return driver.SerialNumber;         }     }          //The way of out parameters returning.     public class Provider2 : IFrProvider     {         private readonly IDrvFR48 driver;                    public string GetSerialNumber(out Result result) {             //must read status before get SerialNumber             int resultCode = driver.ReadEcrStatus();                        if (resultCode != 0) {                 result = new Result(resultCode, driver.ErrorDescription);                 return null;             }             result = new Result(0, null);             return driver.SerialNumber;         }     }          //The way of LastResult property setting.     public class Provider3 : IFrProvider     {         private readonly IDrvFR48 driver;              public Result LastResult {             get {                 return new Result(driver.ErrorCode, driver.ErrorDescription);             }         }                 public string GetSerialNumber() {             //must read status before get SerialNumber             if (driver.GetECRStatus() == 0)                 return driver.SerialNumber;             return null;         }     }          public class Result {         public int ResultCode { get; private set; }         public string Description { get; private set; }              public Result(int resultCode, string description) {             ResultCode = resultCode;             Description = description;         }     }          public class Caller {         public void CallProvider1() {             var provider = new Provider1();             try {                 string serialNumber = provider.GetSerialNumber();                 //success flow             }             catch (OperationException e) {                 if (e.ErrorCode == 123) {                     //handling logic                 }             }         }              public void CallProvider2() {             var provider = new Provider2();                  Result result;             string serialNumber = provider.GetSerialNumber(out result);             if (result.ResultCode == 123) {                 //error handling                }             //success flow         }              public void CallProvider3()         {             var provider = new Provider3();                  string serialNumber = provider.GetSerialNumber();             if (provider.LastResult.ResultCode == 123) {                                 //handling                            }             //success flow                         }     }      So we have three ways of error handling. The most specific thing in all this stuff is that each operation can fail, because it depends on a device. Our team think of using out parameters, because of unhandled exceptions propagation fear. The other reason, connected with the fear, is that we will have to cover all calls by try\catch blocks to stop to be afraid, but such a code will be pretty ugly. What pros and cons do you see and what could you advice?


Is there a difference between iterable and enumerable?

Many languages seem to have structures that are very similar called iterable or enumerable. These are structures that can be iterated or enumerated over, which seem to me extremely similar things. Are these words synonymous or is there a subtle semantic difference between iterable and enumerable which justifies the choice of term?


DRY way to write Javadoc on overload methods

I want to write Javadoc in DRY way. But the oracle document about Javadoc says write same thing again in overload method comment. Can't I avoid repetition?


Importance of diffing and merging for design specifications documentation

The context of this question is choosing tools for writing design specifications for software projects. These documents will be written and maintained by architects and developers, I'm not talking about marketing requirements. Some of them may be shared outside the team, but only in a processed, non-editable form (PDF, all the docs are assumed being able to be exported to this format). These are architecture documents, describing the structure of code components, implementation methods, protocols, data formats, etc. They take the form of text with diagrams and identifier names and the occasional code snippets, this isn't about API documentation that might be generated from source files. The docs will be under source control, fortunately nobody here needs to be educated about that. It's inevitable that versioning will arise over time: we do maintain old versions of the software. Issue tracking might not be adhered to as strictly for documentation as for code. **How important is it to be able to easily compare and merge such documents?** We have diverging opinions in the team, ranging from “nobody ever merges documentation and if needed Word has a merge tool” to “merging is crucial and `git merge` must work”. Note “Word has a merge tool” is something that I quote but don't agree with, having had the painful experience of merging two bugfixes _that I had made_ to two copies of the same document I have a vague memory of a rule in some company (Google, perhaps, since it's so often cited) that “if you can't merge it, it doesn't exist”, but I'm unable to find it now. I'm looking for either well-reasoned arguments, or authoritative-looking (and preferably motivated) citations.


what are the mathematical formulas/concepts used in implementing Chart API (bar chart, pie chart etc.,)

Trying to implement chart API in Java. But I am unsure of the mathematical formulas/concepts used in drawing each of the chart type. Can someone specify the mathematical concepts to be known for drawing each sort of the chart.


AJAX driven "page complete" function? Am I doing it right?

This one might get me slaughtered, since I'm pretty sure it's bad coding practice, so here goes: I have an AJAX driven site which loads both content and javascript in one go using Mootools' `Request.HTML`. Since I have initialization scripts that need to be run to finish "setting up" the template, I include those in a function called `pageComplete()`, **on every page** Visiting one page to another causes the previous `pageComplete()` function to no longer apply, since a new one is defined. The javascript function that loads pages dynamically calls `pageComplete()` blindly when the AJAX call is completed and is loaded onto the page:               function loadPage(page, params) {         // page is a string, params is a javascript object         if (pageRequest && pageRequest.isRunning) pageRequest.cancel();         pageRequest = new Request.HTML({             url: '<?=APPLICATION_LINK?>' + page,             evalScripts: true,             onSuccess: function(tree, elements, html) {                 // Empty previous content and insert new content                 $('content').empty();                 $('content').innerHTML = html;                 pageComplete();                 pageRequest = null;             }         }).send('params='+JSON.encode(params));     }      So yes, if `pageComplete()` is not defined in one the pages, the _old_ `pageComplete()` is called, which could potentially be disastrous, but as of now, every single page has `pageComplete()` defined, even if it is empty. Good idea, bad idea?


What is the difference in meaning between "software", "program", "application", and "gadget"?

It seems to be a naive question, but I was unable to find an explicit definition and difference in meaning of the words "software", "program", "application", and "gadget". What is the correct (at least theoretically) way to use each of these words?


Which is most important to learn OOP first or to learn the OOP language you want to learn?

I face a problem nowadays, I have a really good book that explain OOP but it uses a language which I do not want to learn which is Java because my goal is to learn C#. And I don't know if I should understand OOP with Java at first and then learn C# or should I find any C# book even if the Java book is excellent in teaching OOP?


Reference Passing Style Anti Pattern

I'm working on a legacy VB.Net code base. There are very few functions that return values, most of the code is in subs/void methods. The general strategy seems to be to pass everything in by reference, mutate it, and then observe the mutated state. There are some methods that have as many as a dozen parameters that are mutated in this fashion. I find it very difficult to reason about the code written in this way. It's also rather difficult to write tests to aid in refactoring. I'd like to know if there's a name for this, mainly in the hopes that I can find better ways of moving the application towards a better structure. EDIT I probably should have mentioned that calls tend to be limited to within their own multi-thousand line class files. Based on the answer below it looks like I need to use extract method to make the methods have meaningful names and to deal with the optional parameters. Once I've done this I can start using extract class to separate out functional unit. Fun times.


Can classes violate Single Responsibility if they delegate internal tasks?

I have two classes `Output` and `Timeline`, neither of which violate SR, but the two of them are linked together. So what I'd like to do is have a class called `Elco` (there's a reason behind the name) that has both of them as subclasses. For various reasons (this is just a simplified version) it's important that I don't violate the LoD (Law of Demeter). The issue is that technically `Elco` now has two responsibilities. It delegates those two responsibilities to two classes, which each have one responsibility. Is that not ok? Why? What's a better solution?


Best approach for writing a chess engine?

I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question: What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine? A little guidance would be much appreciated. **Edit:** So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience). P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.


How to translate a German Desktop App into English one

I am working on a desktop application which is in German. And this isn't comfortable for me to see the words and go to Google translate to translate it. So I am looking to make extra effort for myself to try to translate the App into English using Google translate web service. But the Application doesn't use a Spring or AOP in order to make a single point of calling the web service. My question is there a way to create a new project to introduce spring with AOP in order to achieve this. or there is another way to achieve this ?


Continuous integration and modifying existing UI automation tests

Our team is currently facing a situation where we are changing a feature that is in the product today. This feature has Selenium automation tests associated with it. We are performing a fairly major overhaul of the system, including its UI. We expect this work to take quite a few sprints. During this time, other teams may do work that would affect the feature as it exists today. For this reason, we want the existing automation tests for the feature to remain intact so that they can detect issues. Of course, we will need to write automation for the feature as it will be after our changes are done. The most efficient way for us to do this from a Dev/QA perspective would be to modify the existing test cases in a separate branch (testing locally) and then merge those changes in when the feature is ready. That way the existing automation continues to function and we don't have to do extra work duplicating each test. However, this separate branch doesn't fit well with the principles of continuous integration (which our organization likes to adhere to). Is our only CI-compliant option to do the extra overhead of duplicating the tests for modification?


Algorithm visualization app/plugin

I am looking for an application (or and IDE plugin) that I can use in order to test some algorithms I implement.   Mainly metaheuristics used in TSP, VRP and other optimization problems. I have already checked some common suggestions on the net, but they're rather too simple for example Zest. Any suggestions?


A decent git branching model for products that should accompany the version of another, third-party product (and pros and cons of one proposal)

**Note:** _My question is focused in my specific problem (which involves Liferay) but I hope it can be useful for anyone who needs to maintain various versions of a same project on git._ I work on a company which writes a lot of plugins for Liferay Portal. These plugins (portlets, themes etc.) are usually reusable and, of course, should be updated for new versions of the portal. However, it is usual to have to migrate, let us say, a portlet to a new version of Liferay _and_ to maintain its previous version. Also, frequently we have to create very specific customizations for some clients, which does not make sense to be added to the "main version". These requisites complicate our work but, fortunately, we can assume some simplifications. For example, the plugins are frequently updated by only one programmer at a time. It is very rare to have two or more features being added to a plugin at the same time. Now, we are migrating to Gitorious. We are trying to conceive a branching model for such a scenario. # My model What I proposed was:   1. Each plugin would have its own repository in Gitorious inside a project. For example, a portlet for displaying kittens would have a `kittens-portlet` repository inside the `liferay-portlets` project.   2. When creating a new plugin, create it at a branch named according to the Liferay version (for example, `lf5.2`).   3. Each time a update is made on the plugin, the update is approved and deployed in production, tag the plugin with a version (for example, `lf5.2v1`, `lf5.2v2` etc.)*   4. Every time a plugin should be ported to a new version of Liferay, we branch the most recent version (creating, for example, the branch `lf6.0`).   5. Once in production, the head of the new branch will receive a tag such as `lf6.0v1`.   6. Every time we have to customize a plugin in a client-specific way, we create a branch with the name of the client (for example, we would create a branch `lf5.2clientcorp` for our client "ClientCorp Inc.") This is an unusual model: it would have no `master` and a lot of not-merging branches. This is how I _suppose_ a repository with such model would look like: ![How I suppose my branches would work.](http://i.stack.imgur.com/IQ6jZ.png) A friend found this system rather complex and error-prone. He suggested the excellent and popular Vincent Driessen model, which I found still harder to manage and discipline-demander. It is great (and tested!) of course but seems too complex to our situation. # My friend's model Then he suggested another model: we would have a repository for each plugin in a Liferay version (so we would start creating a `kittens-lf5.2-portlet` and then a `kittens-lf6.0-portlet`), each one with a `master` branch and a `develop` branch. The `master` would be always ready for deployment. (Or it could be the other way around, `master` and `stable`, as suggested by Steve Losh). This is very simple, but I did not like this system:   1. it could result in an awful lot of repositories in a project, making Gitorious hard to browse.    2. The name of the directory of the project is relevant. If someone clone the repository to a `kittens-lf6.0-portlet` dir and generate the WAR with ant (as usual), the WAR name will be `kittens-lf6.0-portlet` as well. Old versions of this portlet (named `kittens-portlet` for example) would be considered as different (and probably missing) portlets in a upgraded portal. A bit of care can avoid it but I would prefer to avoid it.   3. The different versions of the same plugin would be maintained apart. I break my heart :(   4. `kittens-lf6.0-portlet` is a ugly name for a repository, I think. I suspect the two last points - which are the two more subjective ones, too - are the main reason for my unwillingness. Nonetheless, all four objections stand. OTOH, my own proposal seems strange to myself and I wonder if there is hidden bugs on it. OT3rdH git is so powerful and flexible that I think I should feel no shame on exploring its possibilities. So, I ask:   1. What would be the best model? My proposal? My friend's model? The now traditional Vincent Driessen system?   2. What other branching model would you suggest?   3. If you think my model is bad, why do you think so? I would love to learn what are the drawbacks and blind spots. * Actually, I would prefer to tag the commit with a version such as `v1` but apparently a tag in git is not scoped in the branch - that is, I could not have a 1 `v1` tag in `lf5.2` and another one in `lf6.0` \- so I have to name the branch. Is it correct BTW?


How to know if two images are the same?

I have over 10000 images which about 2000 are duplicates in other formats (as in JPEG, PNG, GIF). Both of these numbers are increasing every day. I need to delete those duplicates and for that I must know how to find them first. My first thought was to check an images pixels and find other pictures that have the same colored pixels in the same coordinates. But this option doesn't always work. Let's say I search for a duplicate. As for the searchable object I choose a 8 bit PNG file. It'll find all duplicates of that image, but only the 8 bit PNG, sometimes 8bit GIF and rarely JPEG (because of the images algorithmic I suppose?). My second thought was to duplicate all of those images and recolor them in a strict two color palette (let's say black&white) and do the same scan as stated above. Yet again the JPEG image is not 100% similar to the PNG or GIF format (the same reason as above?). The third thought was to _decrease_ the percentage on how much does the image needs to be familiar and _increase_ how much the colors can vary, resulting in unwanted image removal... Any thoughts?


How to start team programming

I work in a small (7 developer) development team and we all work on our own projects. Some of the barriers to team work are the languages and platforms we work on (.NET vs mainframe RPG programming) but other barriers are just that we're all so busy we haven't taken the time to take a step back and organize teams. Me and two other .NET developers are taking initiative to starting a small team but we're all a little stuck on what to do. We're starting with sharing knowledge on the products we work on so we can back each other up but we eventually want to tackle projects as a team instead of individually. What advice would you give a group of guys like us trying to start up team work?


Algorithm which suggests synonyms based on some term?

Is there an algorithm which I can use in order to generate synonyms for some term (word) in respect of a spam. I am writing a simple spam filter. For example, I set that the app must omit a word "viagra" and press a button which saves this term into a filter database. A script automatically creates synonyms of this word, such as: v.i.a.g.r.a, via_gra, via-gra, and similar. Or I filter a curse, and it generates all the tricks people use to have their curses appear in their comments.


Should these concerns be separated into separate objects?

I have objects which implement the interface `BroadcastInterface`, which represents a message that is to be broadcast to all users of a particular group. It has a setter and getter method for the `Subject` and `Body` properties, and an `addRecipientRole()` method, which takes a given role and finds the contact token (e.g., an email address) for each user in the role and stores it. It then has a `getContactTokens()` method. `BroadcastInterface` objects are passed to an object that implements `BroadcasterInterface`. These objects are responsible for broadcasting a passed `BroadcastInterface` object. For example, an `EmailBroadcaster` implementation of the `BroadcasterInterface` will take `EmailBroadcast` objects and use the mailer services to email them out. Now, depending on what `BroadcasterInterface` implementation is used to broadcast, a different implementation of `BroadcastInterface` is used by client code. The Single Responsibility Principle seems to suggest that I should have a separate `BroadcastFactory` object, for creating `BroadcastInterface` objects, depending on what `BroadcasterInterface` implementation is used, as creating the `BroadcastInterface` object is a different responsibility to broadcasting them. _But_ the class used for creating `BroadcastInterface` objects depends on what implementation of `BroadcasterInterface` is used to broadcast them. I think, because the knowledge of what method is used to send the broadcasts should only be configured once, the `BroadcasterInterface` object should be responsible for providing new `BroadcastInterface` objects. **Does the responsibility of “creating and broadcasting objects that implement the`BroadcastInterface` interface” violate the Single Responsibility Principle?** (Because the contact token for sending the broadcast out to the users will differ depending on the way it is broadcasted, I need different broadcast classes—though client code will not be able to tell the difference.)


What is the difference between being an IT in investment bank and a professional IT company?

Suppose there are two positions:   1. IT in investment bank: developer for the infrastructure or the platform   2. a famous IT company: embedded developer, linux As far as I understand, since in the investment bank not everyone will have the chance to work for the core trading system, most people just do the same job as they do in a normal IT company. And some of the tasks can even be outsourced. But in a professional IT company, you will have more chance to practice your coding skill and enhance your professional knowledge. So there are many choices when you want to change your job while the IT in invest bank not. Is this correct?


What are the dangers of setting an unlimited database transaction life timeout?

We have a process that may last between a few seconds and a few minutes. As such, we may update just a few records or thousands of them. The process can be committed only when everything has been done correctly. Recently we have begun having problems when attempting to commit transaction as they were marked as "rollbackOnly". I've discovered that in fact the transaction had been marked "rollbackOnly" because it had timed out a bit earlier (not clear to see in the log files as our application server is Websphere and its transaction manager just gives a one-line warning), and as such it could not be committed. Of course it makes sense that you cannot commit a transaction that has timed out. The problem is in fact that we never set the transaction timeout in transaction definitions, and that in that case the value of the timeout is the one set at the application server level (see Websphere's transaction settings, the paragraph on "Total transaction lifetime timeout"). That value is 2 minutes and sometimes we exceed it. Now, that explains the setting (and in case somebody encounters a "rollbackOnly" transaction, I've provided here a possible explanation). I'm tempted to increase the timeout, but **I've also seen in the documentation that the timeout can be set to 0, meaning there is no timeout**. As such, my question is: **what are the dangers of setting an unlimited transaction life timeout** ? Note that I'm aware of programmatic/database solutions to my problem like for example working on temporary tables, and reversing data from temporary tables to the real tables when we know everything has been done right (using PL/SQL for example). I'm just curious about the transaction timeout thing.


Naming a class that does Importing and exporting of data

I've been thinking about creating a class that handles importing and exporting of data, and I feel that naming it FooImporterExporter might look too long, I wan't to see if there's a name convention that I could use to name it. These are some of the names I think would be appropriate:   * `FooProcessor`   * `FooPorter` / `FooPort` \- ( as Import/Export comes from trading goods in a Port )   * `FooTrader`


Meaning of directories names

I was looking for a _dictionary_ where are described the meanings and purposes of each directory name used in softwares file trees.   I can't find anything except for the Linux FHS, but that is restricted to GNU/Linux OS. So I would like to ask you something to understand the meaning of the following folders:               /controllers     /models     /vendor     /src         This is what I've understood so far:   * **`/controllers`** ~~is where I should put the files that have the purpose of _control_ other files. For example in controllers I could have a PHP file that load a file to call MySQL queries, then one that parse the queries to structure an array, and then one that calls the template manager.~~   * **`/models`** I've no idea of what is intended for...   * **`/vendor`** is where are located external dependencies needed by the software.   * **`/src`** is where the source files are located.    My doubts are:   1. What is the **`/models`** folder?    2. If for example I include in my project, Mustache.php, I will have Mustache located in **`/src/Mustache`**.   But it also adds some dependencies in the **`/vendor`** folder.   The problem is, in my project, even **Mustache** is a "vendor" thing (I guess), so shouldn't it moved to **`/vendor`**?   3. If I'm writing in PHP, HTML, JS and CSS. Every file I use for the production will be also the source file, so why shouldn't I put everything in the **`/src`** folder and keep out maybe only the minified `.js`, `.css` and `.html`?


Puzzle solving: Minimum number of steps to achieve a goal

I have been doing some programming contest problems, and I have noticed that many of them involve something along the lines of "get the minimum number of steps necessary to achieve a certain goal". Examples:   * Given the position of a knight and certain pawns in a chessboard, what is the minimum number of jumps the knight has to do to kill all the pawns?   * Given a parking lot with disordered cars labeled alphabetically, a "move" is the process of taking a car and inserting it elsewhere. What is the minimum number of moves to get this parking lot ordered? So, many puzzles seem to share this structure: given a scenario, some rules, and a set of "operations", determine the least amount of operations to achieve a specific goal. There's a twist in some of these puzzles though - sometimes, the puzzles will also ask if it is impossible to achieve. I have discovered that I am particularly terrible with this kind of puzzles. In fact, I don't think I have ever solved them in an elegant way ever. I'm not sure how to "test all cases", "pick the shortest one" or "determine it is impossible". Can you advice me here? For the sake of the question, we can base ourselves on the chess puzzle: # Example Problem We got a chessboard. Each square is labeled with a number (which represents the position), from 1 to 64. **(Possible) Input**               2 8 31 13      This means "two pawns, on positions 8 and 31. The knight is on position 13." **Output**               2      Two steps. From position `13`, the knight can jump to `8`, and from `8`, it can jump to `31`. * * * # The Question How can I approach this kind of problem? I solved the chess one by generating a list of all possible steps and then I picked the shortest one. But that was very slow.


Developer productivity Cobol versus C#

We are doing a cost benefit analysis on a migration project. It would be nice to be able to say that future changes will be x percent cheaper due to the migration. Does anyone have any experience or know of any study that shows what benefit we could expect?


Bucketing model by time

I have a model which has timestamped entities. Now I want to do bucketing - "buckets" of entities which can be reasoned about a single entity. Also I want to be able to access related entities from a bucket and get a bucket of those entities. My main concerns are an implementation of bucketing itself and architecture of code behind this.   1. Should I create a separate model for bucketed data, or should I implement tools to work with the existing model?   2. As I already have a metamodel with all the subclasses and relations I'd like to be able to easily add bucketing on top. I have been thinking about subclassing all the entity classes to create a bucket-entity class which would extend their common bucket functionality with traits.


Is storing pointer (of new'd object) in static collection from object constructor a common idiom in C++

In code I am reviewing a common approach I see to storing objects (eg a socket client object), is use a static container to hold the objects. The objects are created by some helper function, eg like this:               create_client(params) {       ...       client* cl = new client(...);       return cl;     }      The thing that confused me at first was function called like this:               if (!create_client (...))        //generate error message      ie a copy of the pointer just seems to be thrown away. But on investigation I see this in the client constructor:               client::client(...) {         ...         coll[id] = this;     }      Where coll is a map of id to a pointer to the object. But anyway, just a collection. coll is static (not sure if that is relevant). Is there a name for this idiom? Is it good practice?


First dedicated IDE?

What was the first program that was created as a dedicated IDE? That is, purpose built for coding, rather than simply allowing integration as part of its expansion options. This is opposed to a text editor that has generic plugin/add-in/shell features that are were not dedicated to development work. The features I am thinking about that would qualify an editor as an IDE:   * Code highlighting   * Integrated compiler invocation (with error reporting)   * Code navigation features   * (optionally) integrated debugger Sub question - what was the first Visual IDE? (by which I mean with an integrated GUI designer).


How To Handle Previously Uploaded Files

I'm new to PHP and MySQL and I've only seen posts related to this on Zend and ASP so I'm looking for some advice to point me in the right direction for a LAMP project. I'm putting together a webform for a project of mine that logged in users will access to upload a submission. Each user will reuse previously uploaded files for each submission. At the bottom of the form the user can upload multiple files. Images, spreadsheets, and pdf's, etc. but I would like to give them access to files they have uploaded before rather than having to resubmit all new files for each submission. My question is what is your advice on accomplishing this? I figure I could have each user create a library of files that they could access from the form in some way. Maybe a list of files with checkboxes to select previously uploaded files? I haven't found much here or on Google so I'm not sure if there is a standard way to handle something like this. Note that the users will only be reusing only their own images, not those of the community. If it makes a difference I'm storing the images in MySQL as BLOB's. Thanks for any advice and information.


Best practice for creating views in spring and hibernate web application

Hi I am currently developing a web application in Spring and Hibernate where i have several different tables. The Delivery table for example is mapped many- to-one with the Customer table and the Product table. I am wondering what the best practice is for creating a view function where I display all the columns related to each delivery but exclude the different IDs. I can think of two ways of doing this:   1. Create a DTO (data transfer object) with all the columns I wish to display and then in the controller I create a new instance of it and set the different values with setters and services in a for-loop for each Delivery ID. this is the method used in this example. Here is part of the controller code from it:              @RequestMapping(value = "/list", method = RequestMethod.GET)     public String getRecords(Model model) {      logger.debug("Received request to show records page");           // Retrieve all persons      List<Person> persons = personService.getAll();           // Prepare model object      List<PersonDTO> personsDTO = new ArrayList<PersonDTO>();           for (Person person: persons) {       // Create new data transfer object       PersonDTO dto = new PersonDTO();             dto.setId(person.getId());        dto.setFirstName(person.getFirstName());        dto.setLastName(person.getLastName());        dto.setMoney(person.getMoney());        dto.setCreditCards(creditCardService.getAll(person.getId()));            // Add to model list         personsDTO.add(dto);         }           // Add to model      model.addAttribute("persons", personsDTO);           // This will resolve to /WEB-INF/jsp/records.jsp      return "records";      }           1. the second way I am considering is to create an HQL query that Joins the relevant tables and then displaying that. I'm not sure exactly how to do this yet.  So which of the alternatives is the better way to go? Are there any others that I haven't thought about? Thank you for the advice, D


Licensing doubts

I am quite new to programming and I am now creating my own program as part of my Master Thesis. My program is done in Java and uses several third-party libraries. These libraries come with different licenses, mainly:   * LGPL 2.1   * GPL 2 + GPL Linking exception   * Apache version 2   * BSD I have actually not touched the source code of these libraries, but use them in my program and in some cases create classes that extend classes in those libraries. If I decide to make my program publicly available (probably for free) what kind of licence could I use? I have read much about license compatibility (Apache vs GPL vs whatever), derivative works discussions and I am very confused. Comments and explanations would be very helpful.


Is it viable to make a port from a C++ application to Java through LLVM

how viable is it to port a C++ application to Java bytecode using LLVM (I guess LLJVM)? The thing is that we currently have a process written in C++ but a new client has made mandatory to been able to run the program in a multiplatform way, **using** the Java Virtual Machine with obviously no native code (no JNI). The idea is to be able to take the generated jar and copy then to different systems (Linux, Win, 32 bits - 64 bits) and it should just work. Looking around looks like it is possible to compile C++ to LLVM IR code and then that code to java bytecode. There is no need of the generated code to be readable. I have test a bit with similar things using emscripten, this takes C++ code and compile it to JavaScript. The result is valid JS but totally unreadable (looks like assambler).   * Does anybody done a port of an application from C++ to Java bytecode using this tecnique?   * What problems could we face?   * Is a valid approach for production code? To make more clear my point after some comments, maybe port is not well used, I do not expect readable source code as a result, just java bytecode, so it is not a 'port' which will be developed for anymore, just that the target plattform must be the java JVM not the native assamblear. Note: I am aware that currently we have some non standard C++ and close source libraries, we are looking to removing this non standard code and all close source libraries and use Free Libre Open Source Software, so lets suppose all code is standard C++ code with all code available at compile time. Note2: It is not an option to write portable C++ code and then compile it to the desired target platform, the compiled program must be multiplatform, thus the use of JVM . Note3: Right now we are not looking into similar solutions applied to Python or other language base, but i would also like to heard about it. With this I mean that our target executable must be java bytecode but if there are options to compile C++ to valid python compiled code I would also like to hear about them.


Implementing a DAO for entity framework

Could anybody help me to find a good tutorial about how can I implement DAO pattern and also tools that help me to create this classes in automated way.


"Bad apple" algorithm, or process crashes shared sandbox

I'm looking for an algorithm to handle the following problem, which I'm (for now) calling the "bad apple" algorithm. ### The problem   * I've got N processes running in M sandboxes, where N >> M.   * It's impractical to give each process its own sandbox.   * At least one of those processes is badly-behaved, and is bringing down the entire sandbox, thus killing all of the other processes in the same sandbox. If it was a single badly-behaved process, then I could use a simple bisection to put half of the processes in one sandbox, and half in another sandbox, until I found the miscreant. ### The question If _more than one_ process is badly-behaved -- including the possibility that they're _all_ badly-behaved -- does this naive algorithm "work"? Is it guaranteed to work within some sensible bounds? ### Simplifications For the sake of argument, let's assume that a bad process brings down its sandbox instantaneously, and a good process never does.


How do you keep released binaries under version control? This allows to track which stuffs are changed between each release. I mean to separate the released binaries from source repository. The released binaries are either built from Continuous Integration software or manually compiled.


What does it mean to do a "null check" in C or C++?

I have been learning C++ and I am having a hard time understanding null. In particular, the tutorials I have read mention doing a "null check", but I am not sure what that means or why it's necessary.   * What exactly is null?   * What does it mean to "check for null"?   * Do I always need to check for null? Any code examples would be much appreciated.


Does continuous integration involve automatic merging between branches?

When setting up a continous integration environment, does it always entail having the build server pull code and merge between branches? Or is it something you NEVER want to do because you are depending on an automatic merge would usually ends up having issues (and requires manual intervention).


Shoring up deficiencies in a "home grown" programmer?

I started out by teaching myself BASIC on a Vic 20, and in college (mid 80's) I had Fortran, Pascal, limited C, machine and assembler (With a smattering of COBOL) as part of a computer science minor in college. I didn't touch programming from approx 1989 to 1999. At that point, I was lucky enough to get hired as a Clipper programmer. Took me about 6 months to learn most of it, and by now (13 yrs) I'm pretty expert in it. I have also picked up Cold Fusion, some C#, some ASP, SQL, etc. I know programming structures, but in most modern languages I'm missing the esoterics, and I know my code could be much tighter. The problem is that I've learned what I needed to, to get the job done. This results in a lot of gaps in practical knowledge. I am also missing out on a TON of theory. Things like SRP, Refactoring, etc are alien terms. (Although I grok the intent after a short read). In addition, I am in the position now of teaching junior programmers the company and our software, and I don't want to pass on the knowledge gaps. I know this is somewhat of a subjective question and may be closed, but how do you go back and pick up what you've missed?


How to optimise an sentiment analysis algorithm for larger data sets?

I am a noob to sentiment analysis and found a good resource for Bayesian Opinion Mining and a way to make it self improving. I was wondering though, if the optimum analysis is dependent upon the supplied data set and since self improvement would mean adding known patterns to the data set (my understanding), wouldn't the application become too overloaded with huge data set over due course of time with more and more patterns getting added to the data set every day ? What should be the proper approach to make the application scalable (if I am using the right term at the right place) ?


GPL: terms of license

I'd like to use the VLC's DLL in one of my programs. VLC is under the GPL license. Do I have to redistribute all the sources under GPL or can I redistribute only the modified sources of VLC under these terms while redistributing the rest of my program in the license I want? Thank you, Sébastien **Edit** : And what if I only use the DLL of VLC in case they are installed on the user's computer ?


DDD identifying aggregate root

I am designing the a web application using domain driven design.I have following scenario: Each applicationGroup can have one Application and each application can have multiple configuration.I am trying figuring out which one will be aggregate object... which one will be aggregate roots and why?


Emotional attachment to code

As an employee of a company, when you write code do you feel like you have an attachment to it? Do you feel that you have some ownership of the code? Or do you write it completely detached from it without any concern about what happens to it after you've moved onto something else? EDIT: I'm not talking about writing bad code and then running...


Clarification needed for various architect terms and their roles

After going through many SO questions and answers on "Architects" , I am now basically confused with the various terms and their roles. Could any one please explain the terms clearly and their roles               A) Technical Architect          B) Solution Architect          C) Domain Architect          D) Enterprise Architect           E) Project Architect          F) Systems Architect          G) Software Architect          H) Design Architect      Thanks


How do you keep logins organized between multiple developers?

I've worked at several places with 2-10 developers and each place has struggled in the area of tracking if the company has an account on a given web site or service. We're always left wondering...   * What's the username   * What's the password (Obviously you don't want to store this, I'm not looking for something that does)   * What's the account number   * Who created this   * When was it created   * What email is our account registered under **What do you guys use to track this kind of thing between multiple developers?** I've setup at least a dozen accounts for the company I currently work for and I don't have any documentation to show the next guy what's been done. Ideally I'm looking for a web solution that will be locked down within our VPN.


Protocol for closing a socket connection

I'm rolling my own application protocol on top of TCP. I'm using Linux and C. I'm wondering whether there is an advisable sequence to closing a socket connection. The client will always initiate the close by sending a specially-formed string; say, "CLOSE". I'd like to receive some kind of acknowledgement from the server that it has seen my CLOSE request, so perhaps it needs to send back a special string like "CLOSE_OK". I've also seen both the close() and shutdown() system calls, but am not sure how to use them. For instance, should the client, after receiving "CLOSE_OK", do a shutdown(OUTPUT) and then wait to receive a zero-length string? And should the server, after sending "CLOSE_OK", issue close() and then consider the socket to be dead? I'm hoping there's a "best practice" on this subject that I haven't found yet... Thanks, Chap


Why does Scheme r5rs have no module system

With all the controversy surrounding scheme r6rs, I stuck with r5rs and I am wondering why the designers decided to not implement a module system. How does one organize code in this?


Mongodb array vs object

New with Mongodb, and I'm not sure what implications or benefits there are between the use of an array vs an object. So..   1. As above what are the implications and benefits between the use of arrays and objects?   2. For example my case. The idea is to store a document with a "capture" time, and a 2000 slots of "packet" counters. I used object to store to packets see this , but apparently it seems better off to use arrays. What kind of considerations should one make to determine whether an array or object is more suitable (with example)?


General way for getting graphics for open source project

I'm in process of making an open source application for Windows. In the end I would require an icons for my app and its gui. I'm huge fan of Tango styled icons, but its pack doesn't provide all icons I need. Gnome project seems to provide ones for more mature projects that run on linux. What is the general way, procedure for getting help in graphic assets for open source project?


random unique pair numbers from two range

I want to write a function that return random unique pair numbers every time call it from a range until resetting it. Something like this:               function randomUniquePairs($ranges, $reset = false){        if ($reset === false){           // some code for reseting        }        /*          some code for creating random unique pair numbers        */        return $result;       }           randomUniquePairs(range(1,10), range(1,20));     /*       this function returns for example:        array(2,9)     */     randomUniquePairs(range(1,10), range(1,20));     /*       this function returns for example:        array(5,19)     */          randomUniquePairs(range(1,10), range(1,20));     /*       this function returns for example:        array(5,9)     */      //this function returns random unique pairs until we pass reset paramer true      I tried two approaches: **Approach 1**   My first attempt was to make an array of all of possible pairs then select from them randomly, but it is very inefficient, because if ranges are so wide, it consumes a lot of memory. the code:                 class a {         private $asqar;              function __construct() ($range) {                  // cycle for ranges             foreach ($range[0] as  $v1) {                 foreach ($range[1] as $v2) {                     $asqar[] =  array(                         $v1,                         $v2,                     );                 }             }         }              function randomUniquePairs($reset = false){                  if ($reset === true){                $this->asgar = array();             }                  $rndKey = array_rand($this->asgar);             $result = $this->asqar[$rndkey];             unset($this->asqar[$rndkey]);             return $result;         }     }          $c = new a(range(1,10), range(1,20));     $c->randomUniquePairs();      **Approach 2**   My second attempt was to write a function that produce a pair from these ranges, then store it in a variable, every time that function calls after producing a pair , it checks if this pair produced before call function recursively, it continues until it produce a unique pair. Here's the code:               class a{               private $__uniqueVariables = array();              public function randomUniquePairs($range, $reset = false) {                  if ($reset === true){            $this->__uniqueVariables = array();         }              // cycle for each value         foreach ($range as $value) {                  // shuffle             shuffle($value);                  // selected id             $selectedId[] = $value[0];         }              // check for selected variable         if (in_array($rndUnqNum, $this->__uniqueVariables)) {                  // return for try again             return $this->uniqueVariable($range);         }              // added to current unique variables         $this->__uniqueVariables[] = $rndUnqNum;              // return         return $rndUnqNum;     }          }      but this second approach has an issue that sometimes throw `Fatal error: Maximum function nesting level of '100' reached`. I'm looking for a better approach to my algorithm.


Web programming, standard way to deal with a response that takes time to complete

With normal form submission I use the pattern Post / Redirect / Get, when processing the forms. I have a database application built with Django. I want to allow the users to select a number of items from the database, then launch a computationally intensive task based on those items. I expect the task to take between 10 minutes and 2 hours to complete. Is there a standard approach to dealing with requests like this (i.e. that don't return immediately)? Ideally there would be some way to display the progress.


Empty interface to combine multiple interfaces

Suppose you have two interfaces:               interface Readable {         public void read();     }          interface Writable {         public void write();     }      In some cases the implementing objects can only support one of these but in a lot of cases the implementations will support both interfaces. The people who use the interfaces will have to do something like:               // can't write to it without explicit casting     Readable myObject = new MyObject();          // can't read from it without explicit casting     Writable myObject = new MyObject();          // tight coupling to actual implementation     MyObject myObject = new MyObject();      None of these options is terribly convenient, even more so when considering that you want this as a method parameter. One solution would be to declare a wrapping interface:               interface TheWholeShabam extends Readable, Writable {}      But this has one specific problem: all implementations that support both Readable and Writable **have** to implement TheWholeShabam if they want to be compatible with people using the interface. Even though it offers nothing apart from the guaranteed presence of both interfaces. Is there a clean solution to this problem or should I go for the wrapper interface? **UPDATE** It is in fact often necessary to have an object that is both readable and writable so simply seperating the concerns in the arguments is not always a clean solution. **UPDATE2** (extracted as answer so it's easier to comment on) **UPDATE3** Please beware that the primary usecase for this is **not** streams (although they too must be supported). Streams make a very specific distinction between input and output and there is a clear separation of responsibilities. Rather, think of something like a bytebuffer where you need one object you can write to and read from, one object that has a very specific state attached to it. These objects exist because they are very useful for some things like asynchronous I/O, encodings,... **UPDATE4** One of the first things I tried was the same as the suggestion given below (check the accepted answer) but it proved to be too fragile. Suppose you have a class that has to return the type:               public <RW extends Readable & Writable> RW getItAll();      If you call this method, the generic RW is determined by the variable receiving the object, so you need a way to describe this var.               MyObject myObject = someInstance.getItAll();      This would work but once again ties it to an implementation and may actually throw classcastexceptions at runtime (depending on what is returned). Additionally if you want a class variable of the type RW, you need to define the generic at the class level.


Tool for programmers team

I'm looking for a tool for team of programmers. Generally we are split in two groups, we are building two applications on the same framework and in the same moment we are building the framework. I'm looking for a tool, which can make better our communication. The problem to solve is, one team solved a problem in first application and give some code to framework, but the other team doesn't know about this and invents a wheel. The documentation doesn't solve the problem. I'm thinking about a blog on Wordpress -- you solved a problem, so you should give a post: add some tags, description, file names etc.


Can code be the documentation in open source developer tools? How frequently is it?

It's understandable that after a big development effort, some OSS authors deem reasonable that the project users should make an effort too in order to get started. Can the source code effectively be the project's documentation? Does it need to be structured in a particular way in order to achieve this? And how often is this approach taken? Of course this only would be feasible if the project is aimed to developers, and written in the same targeted language of the application (e.g. you can't understand the V8 engine only knowing JavaScript).


What made object oriented programming successful?

What is that feature according to you that has made object oriented programming so much successful ?   1. Message Passing   2. Inheritance   3. Polymorphism   4. Encapsulation Or some other feature that you may like to introduce. Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?


Customer Requirements Contains Equations that Cancel to Nothing

I have a project where the customer requirement specifies a report and contains mathematical equations for the contents of some of the columns on that report. One of the columns on this report is a running total which starts at a opening value, and which 'should' remain at that opening value all the way down the report because the other stuff balances out. I.e. if something had gone missing, the value would change and the customer would see that there is a problem. The reason I quoted the 'should' in that last paragraph is because the spec defines an equation for this column, and I can mathematically prove that it cancels out to 'the value from the previous row'. In other words, the value will never ever change from the opening value. So my options are:   * Implement the equation as spec'd, I suspect the interpreter will not resolve the equation so there will be a performance hit   * Do some cancelling out, and implement the column value as 'value from the previous row'   * Send the question back up the chain to the customer and risk missing the deadline because of several days lost to bureaucracy and impromptu math 101 lessons to explain the difference between "yeah, it'll never change, it's there just in case" and "it. will. never. change."  I've pretty much decided what I'm going to do, but I thought it was an interesting question. What do you think is the professional thing to do?


Are By-Design "Bugs" a Bad Sign?

Is it a bad sign if users submit bug reports for things that are by design? Does it typically mean that the application is confusing or unclear, or should I just chalk it up to a one-off user mistake unless specifically stated? (I don't actually have any such reports. This is a purely hypothetical question about whether or not the existence of by-design "bugs" is a bad thing.)


Angularjs Business Logic mixing

## Scenario Last night I asked this question on StackOverflow. Although now I have a solution and I can move forward with the development, it feels partially answered because I have more questions now than before. The proposed solution creates an ugly effect. Now '$scope.item' wraps the $resource in '$scope.item.item' So i should change every bindings path in the document. ### From                     ### To                     This is not aceptable to me, feels bad practice. then I thought of this solution ### Item constructor               var Item = function Item(item) {         // mixing         angular.extend(this, item);     };      This solved the last problem but generated new one. Now `$scope.item` not contain the `$resource` methods. (eg `$scope.item.update()`) due `__proto__` chaged from `Resourse` to `Item` ### Item constructor v2               var Item = function Item(item) {         this.api = item; // Resource         // mixing         angular.extend(this, item);     };      Now to invoke the old '$scope.item.update()' needs to be changed to '$scope.item.api.update()'. This feels bad practice too. At this point I fear it is a XY problem. ## The Goal > Join the business logic to the data in angulay way. ## The Question Is "The Goal" itself an "Angular Way"? 'Angular Way' remains obscure to me. Maybe I should think of a different design.


Testing thread safety

Say you have a function `f` that is or contains a critical section. How would you unit test that only one thread can run it at once, that it doesn't have race conditions, and that it doesn't cause a deadlock, etc...?


How does a "Variables introduce state"?

I was reading the "C++ Coding Standards" and this line was there: > Variables introduce state, and you should have to deal with as little state > as possible, with lifetimes as short as possible. Doesn't anything that mutates eventually manipulate state? What does "you should have to deal with little state as possible" mean? In an impure language such as C++, isn't state management really what you are doing? And what are other ways to "deal with as little state as possible" other than limiting variable lifetime?


graphs with multiple series in javascript

I'm looking for a graphing tool that allows you to plot multiple series with 2 vertical axis, and with different graph types (at least that is how I would describe it in excel). I've never looked at graphing before, though have a reasonable knowledge of javascript. Where is a good place to start? Here is an example of the type of graph that I'm hoping to produce. ![enter image description here](http://i.stack.imgur.com/IUCmR.png)


Is there a more modern program than lex or yacc, which does not require JVM?

Is there a "modern" bison and flex equivalent which does not require the JVM or .NET or similar "heavy" runtimes? Thanks for comments, edit: By modern, I mean for example Antlr and another one in Java I saw but forgot the name of. (I know that for instance Antlr has a C target, but I am toying with the idea of embedding the compiler generator _inside my own program_ and Java would be very impractical for me.)


Mapping a legacy database to ORM using wrapper classes

I want to use an ORM with a legacy database, but I don't want to expose some of the underlying data types. For example, some of the columns are nullable doubles or floats and I want my domain model to use non nullable decimals. It seems to be impossible to have Entity Framework automagically cast between these types, and maybe for good reasons. I also want to be able to use enums and so far I have not found any method that don't look like ugly hacks to make this possible. My idea is simply to use wrappers, where I have table-like classes mapped to the database but wrap them in "real" domain classes for use in code. My question is simply if you have any thoughts about this approach or if you have any tips. I have no experience in mapping a legacy database to an ORM so any comments or suggestions are appreciated. Note: I've only looked at Entity Framework so I have no knowledge about the capabilities of other ORMs, such as NHibernate.


How many questions are on the 70-511 exam?

I'm preparing to take the Windows Applications Development with Microsoft .NET Framework 4 exam, but I'm not sure how many questions are on it. I know the exam should only take 90 minutes or so, but how many questions would I have to answer? 50? 100? More?


FromXYZ vs Overloaded Method

I'm trying to think of the cleanest way to implement a couple of methods that open a file. Consider the following method signatures:               public static DomainObject Load(Uri urlToFile)     {         /* downloads file and calls Load(savedToFilename) */     }          public static DomainObject Load(string filename)      {          /* creates filestream and calls Load(stream) */     }          public static DomainObject Load(Stream stream)      {          /* does actual loading */      }      I'm trying to implement some concepts from Clean Code, specifically: > When constructors are overloaded, use static factory methods with names that > describe the arguments. For example, > > _Complex fulcrumPoint = Complex.FromRealNumber(23.0);_ > > is generally better than > > _Complex fulcrumPoint = new Complex(23.0);_ Now, I know I do not have overloaded constructors, per se (I refactored away from that), but I think the principle is the same. So that implies that my Load methods be refactored to something like:               public static DomainObject FromURI(Uri urlToFile);     public static DomainObject FromFile(string filename);     public static DomainObject FromStream(Stream stream);      But, tbh, I think it's more intuitive to use what I've already got. From a consumer's perspective it feels like Open will take whatever source I happen to have whereas the other method requires me to think first about what my source is and then wonder if there is a specific method for that. So I ask, from your more experienced viewpoint, which is better and why?


Handling Coding Standards at Work (I'm not the boss)

I work on a small team, around 10 devs. We have no coding standards at all. There are certain things that have become the norm but some ways of doing things are completely disparate. My big one is indentation. Some use tabs, some use spaces, some use a different number of spaces, which creates a huge problem. I often end up with conflicts when I merge because someone used their IDE to auto format and they use a different character to indent than I do. I don't care which we use I just want us all to use the same one. Or else I'll open a file and some lines have curly brackets on the same line as the condition while others have them on the next line. Again, I don't mind which one so long as they are all the same. I've brought up the issue of standards to my direct manager, one on one and in group meetings, and he is not overly concerned about it (there are several others who share the same view as myself). I brought up my specific concern about indentation characters and he thought a better solution would be to, "create some kind of script that could convert all that when we push/pull from the repo." I suspect that he doesn't want to change and this solution seems overly complicated and prone to maintenance issues down the road (also, this addresses only one manifestation of a larger issue). Have any of you run into a similar situation at work? If so, how did you handle it? What would be some good points to help sell my boss on standards? Would starting a grass roots movement to create coding standards, among those of us who are interested, be a good idea? Am I being too particular, should I just let it go? Thank you all for your time. **Note:** Thanks everyone for the great feedback so far! To be clear, I don't want to dictate One Style To Rule Them All. I'm willing to concede my preferred way of doing something in favor of what suits everyone the best. I want consistency and I want this to be a democracy. I want it to be a group decision that everyone agrees on. True, not everyone will get their way, but I'm hoping that everyone will be mature enough to compromise for the betterment of the group. **Note 2:** Some people are getting caught up in the two examples I gave above. I'm more after the heart of the matter. It manifests itself with many examples: naming conventions, huge functions that should be broken up, should something go in a util or service, should something be a constant or injected, should we all use different versions of a dependency or the same, should an interface be used for this case, how should unit tests be set up, what should be unit tested, (Java specific) should we use annotations or external config. I could go on.


Fastest way to document software architecture and design

We are a small team of 5 developers and I'm looking for some great advices about how to document the software architecture and design. I'm going for the sweet spot, where the time invested pays off. I don't want to use more time documenting than necessary. I'll quickly give you my thoughts. What are the diagrams I should made? I'm thinking an overall diagram showing the various applications and services. And then some sequence diagrams showing the most important or complicated processes. About the code it self, I really don't see much value in describing or making diagrams for the code outside the .cs files them self. About text documents, I'm a bit uncertain about when to put down on paper. Most developers don't like to either write or read long documents.


Using absolute paths for build dependencies

Currently we are using Source Safe and have started migration to Subversion. All of our external SDK's(> 500 MB) are held in Source Safe right now, and I am looking for ways to move them from VSS to a repository. We have C++ (mostly), C# (many), Java (few) projects. Hundreds of projects, all running on Windows. I looked at a couple of dependency managers but I'm not satisfied:   * NuGet - good for .Net but painful for C++   * Ivy - not look in depth, but doesn't seem acceptable for C++ **First question: what else should I check? It should be easy to use for a front-end developer. Best case is a simple build within the IDE.** * * * Currently I am inclined to this solution: Allocate some rarely used drive, like S: and declare it as 'DEV HOME'. Then place externals here:               S:\SDK\boost\1.30\...     S:\SDK\boost\1.45\...     S:\SDK\oracle\agile_9.0.0.0\...     S:\SDK\IBM\lotus_8.0\...     S:\SDK\IBM\lotus_9.0\...     S:\Tools\NuGet\nuget.exe     S:\Tools\clr\gacutil.exe      Autobuild machine will hold mastercopy of this 'DEV HOME'. Every developer should copy necessary SDKs from autobuild machine to local and create a 'fake' disk with **subst**. I can't find any big problems with this solution:   * Branches. Projects in different branches contain references to different versions of SDK (boost for example)   * Version of external component will not change too frequently, so there will not be hundreds of, say, boost versions.   * Easy for developers to setup.    * Absolute paths supported by any tool. Minor problems:   * Personally for me it is not beautiful solution.   * Disk (S:) can be busy   * Can't be done in Linux (but currently we're not interested in it)  **Second question: what problems can you see with this solution?**


Parallel teams and scrum/agile

My company has grown seriously over the last years. Until a few years ago we could work with 1 agile team and everything went quite smooth. Now we have multiple teams, all working agile and things go less smoothly as we would hoped. One of the main [psychological] problems is how to organize the working methods in the teams.   * If every team has its own way of working (its own type of Excel sheets where the progress is kept, its own way of calculating capacity, ...) the teams seem to drift apart and seem to compete rather than cooperate on things (developing similar code in parallel)   * If all teams use the same methodologies and work flow procedures, then again we have two alternatives:      * 'Forcing' the methodologies by management seems incorrect since management does not clearly know how agile/scrum methodologies should work (only the actual teams know this)     * Letting teams making suggestions for improvements and them 'forcing' this onto other teams might improve the competition rather than the cooperation (teams will refuse to use the methodology because it comes from another team).  Does anyone have any experience with multiple teams working together in an agile/scrum way? How do promote the teams working together without making them 'blaming eachother' for things that don't work?


What other languages, beside Transact SQL, state that 22/7 is equal to 3?

I was using Microsoft SQL Query Analyzer the other day and wrote a very simple select statement:               SELECT 22/7 as [PI Equiv]      I was suprized that the result was 3, when I was expecting to see 3.1428571. Even if you declare the output to be `Numeric(18,7)`, you still get 3.0000000.               DECLARE @Answer Numeric(18,7)     SET @Answer = 22/7     SELECT @Answer as [PI Equiv]          RESULT = 3.0000000      What other languages return integer values when the dividend and divisor are both integers?


Strategy/algorithm to divide fair teams based on history

We are a group of people playing floorball together on a regular basis. Every session starts with the daunting task of dividing teams... So what would be better than an application to pick teams automatically? So, given a history of team-combinations and results, and a list of people showing up for this particular session, what would be a good strategy to find the optimal teams? By optimal, I mean teams as equal as possible. Any ideas? Edit: To make it clear, the data that I have to base the picking on, would be something like this:               [{ team1: ["playerA", "playerB", "playerC"],        team2: ["playerD", "playerE", "playerF"],        goals_team1: 10,        goals_team2:  8       },      { team1: ["playerD", "playerB", "playerC"],        team2: ["playerA", "playerE", "playerG"],        goals_team1:  2,        goals_team2:  5      },      { team1: ["playerD", "playerB", "playerF"],        team2: ["playerA", "playerE", "playerC"],        goals_team1:  4,        goals_team2:  2      }]