Are there legitimate reasons for returning exception objects instead of throwing them?

_This question is intended to apply to any OO programming language that supports exception handling; I am using C# for illustrative purposes only._ Exceptions are usually intended to be raised when an problem arises that the code cannot immediately handle, and then to be caught in a `catch` clause in a different location (usually an outer stack frame). **Q:** Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects? This question came up for me because .NET 4's `System.IObserver<T>.OnError` method suggests just that: exceptions being passed around as error objects. Let's look at another scenario, validation. Let's say I am following conventional wisdom, and that I am therefore distinguishing between an error object type `IValidationError` and a separate exception type `ValidationException` that is used to report unexpected errors:               partial interface IValidationError { }          abstract partial class ValidationException : System.Exception     {         public abstract IValidationError[] ValidationErrors { get; }     }      (The `System.Component.DataAnnotations` namespace does something quite similar.) These types could be employed as follows:               partial interface IFoo { }  // an immutable type          partial interface IFooBuilder  // mutable counterpart to prepare instances of above type     {         bool IsValid(out IValidationError[] validationErrors);  // true if no validation error occurs         IFoo Build();  // throws ValidationException if !IsValid(…)     }      Now I am wondering, could I not simplify the above to this:               partial class ValidationError : System.Exception { }  // = IValidationError + ValidationException          partial interface IFoo { }  // (unchanged)          partial interface IFooBuilder     {         bool IsValid(out ValidationError[] validationErrors);         IFoo Build();  // may throw ValidationError or sth. like AggregateException<ValidationError>     }      **Q:** What are the advantages and disadvantages of these two differing approaches?


Agile in a multidisciplinary environment

I work for an engineering consultancy who do a combination of industrial design, mechanics, electronics and software. By their nature - or perhaps simply by history - the overall development philosophy has been waterfall. But when I joined I was surprised that Agile, which I would now say is an industry standard, had barely been heard of. For me, whilst I remain skeptical of Agile, I recognize its benefits for both developers and clients, and have been keen to promote its use. It seems clear to me that you can't build hardware in an Agile fashion. It's just too time-consuming and expensive to "refactor" a physical thing. This means we are moving towards being software-Agile and hardware-Waterfall, and the Project Manager is struggling to make the two work together. Worse, it becomes difficult when we are faced with providing clients with a definitive cost for a project. Agile doesn't do uber-plans, and velocity projections require a project to be up, running and a few sprints to have passed to be meaningful. This means we tend to over-estimate as contingency, driving up our prices and our competitiveness goes down. Seems to me then that either We sell Agile explicitly to the client, and get their buy-in to receiving new software iterations per sprint, being able to add to the backlog and prioritize the next tranche of work. We persuade them that this is a no- bullshit way of working, and that waterfall is unrealistic and results in overspend. The Product Owner is from the client in this model. How then do we approach contracts, saying how much we charge for the software? How do we avoid the impression that this is an open-ended revenue stream in which it is in our interests to take as long as we like? We adopt Agile internally only. The Product Owner is one of our guys / girls. The client just gets an alpha/beta/release version of the software as in waterfall. If we're over time, do we then fudge the slippage in the final phases? Is this even Agile? In short, having a contract between us and a client seems a very un-Agile way of doing things. And yet waterfall is doomed to fail in an environment where we see every day that not only do we not understand the problem domain on day 1 of a project, neither does the client. And how do we do Agile for software and waterfall for hardware - is there software that can handle both under one umbrella? How do we marry these worlds?


How to migrate an XML serialization framework in Java in a tightly coupled system?

I work for a company that uses XML for storing a bunch of serialized Java classes. The framework we use is Apache Betwixt (abandonded in 2008) and it's kind of pain to maintain and extend (it seemed like a good choice back in the day). **Crash course in Betwixt along with the detailed problem:**   * Only supports public getters and setters, both getter and setter have to be present   * Does not support JAXB-style type adapters   * The XML evolves with the Java objects, resulting in redundant methods in our classes Our list of xml serializable classes is well over 150, and the codebase can get very messy when changes to definitions are made. Since the XML is bound to Java getters and setters, we can only migrate XML by keeping old properties in the class definitions. NowTake a look at this change:               public class ThingWithText {              private String text;            public String getText() {          return text;       }            public void setText(String text) {          this.text = text;       }     }      The resulting XML looks something like:               <thingWithText>         <text>Whatever</text>     </thingWithText>      Now consider a change in the model to add multiple locales to the `ThingWithText`:               public class ThingWithText {        private List<TextWithLanguage> texts = new LinkedList<TextWithLanguage>();             // Getter must be here so the framework recognizes the property.         public String getText() {           return null;        }             // Has to be here so it can be serialized        public void setText(String text) {           this.texts.add(new TextWithLanguage(text));        }             public List<TextWithLanguage> getTexts() {           return texts;        }             public void addText(TextWithLanguage text) {           texts.add(text);        }     }          public class TextWithLanguage {        private Locale locale = // omitted;        private String text;             public TextWithLanguage(String text) {           this.text = text;        }             // Getter and setter omitted     }      The XML now looks like:               <thingWithText>         <texts>             <text locale="en">Whatever</text>         </texts>     </thingWithText>      Now the XML isn't bad looking or anything, but it still leaves the `ThingWithText` class with several problems:   * A setter for a non-existing field   * A getter that always returns null, may cause exceptions because stuff still compiles **My questions go:** We have made the decision to do something about this, and it seems like a problem other people would have.   1. How does one handle migration between an old framework like Betwixt to a newer (JAXB, Xstream, whatever)?   2. If we were to keep our framework: How can we manage the considerable code complexity added by null methods and fake setters?


How do I recreate this Access Control/Group/ whatever methodology in OO/MVC

I am looking at trying to rewrite an application that is mostly procedural to an MVC/OO approach in order to teach myself a deeper understanding of both. BUT, I am having some conceptual issues with the current group/access control that is used. We have Groups (Businesses) that have role based users (Manager, salespersons, customers). They can have customers either assigned to a salesperson, or not. The manager sees everything, the salesperson only those customers assigned to him.               Business       |       ---Manager            |            ---Salespersons                 |                 ---Customers       |       ---Customers      The table structure for this currently is something like this:               users (userID [demographic info])     business (businessID, userID, et al [demographic info])     salespeople (salesID, businessID, userID [just foreign keys])     customers (customerID, businessID, userID, et al [demographic info])     salesAssignments (salesID, customerID [just foreign keys])      The Manager can affect everyone within that businesses group (everyone has a `businessID` that links them to that business and no other). The customers can login and make minor changes to their profiles or interact via messaging to their salesperson or the businesses manager. Added Spice to the mix: (comment on any of these if they apply to your insights to the above question) Is there a better way to have similar user access and control? I want to rebuild the site with an API that can be used by both the web app and mobile apps. **EDIT** My main conceptual hangup at the moment relates to how to recreate this structure in a user object for the OO part of the application. Now everything is accessible via session variables, or queried from the DB via procedural functions. Again my understanding of OO is limited, and this is an attempt to figure it out.


Need help - brainstorming php scheduler class

I've never written a php class before from scratch. But I guess you have to start somewhere right? I've got an idea, but need help with logic. Please tell me what you think. Below is shorthand obviously. In the planning stages.               Class -       -> type (recurring, single, day)      -> Recurring days (4,2,3,4,1,2....etc. for odd schedules- need even pairs)      -> Shift Type (onshift, vacation, medical, etc...)      -> Emp Id      -> Start      -> End      -> Location Id      -> Hours per day      -> Day start time           get schedule ( by account/location/company/unit/crew/individual )           select single entries           separate array into days (1 day) increments           if single entries have linking day entries, replace array with day entry information           return mysql array of days for the time period;           set schedule ( dates, emp id)           if recurring               if already exisits || conflicts with existing                   error               create recurring template in db table               create single db entries using recurring days for 1 year           if single               if date is between dates already in db || more than 1 year out                   error               else                   insert into db           if day               if no existing single range                  error               else                  insert into db under day table, with id linking to id of existing single.           remove recurringOnly(emp id)           delete all entries with recurring id           remove all entries( from this date forward, emp id )           delete entries with start date > date           cronUpdate( cron start / end dates)           if cron start / end dates                delete anything with dates bigger than nextUpdate (to make sure no errors)                select recurring db entries with nextUpdate between cron start/ end                insert into db the next set of "recurring days" for the employee                update nextUpdate date for employee           else - error


Scope of work contents in freelance development

One of my clients demanded to append screen shots of UI in the SOW. Also, I was asked to give a workflow diagram for the same. The project I am about to take is relatively small and my question is,   * Should we always provide UI snap shots before project begins? (at least basic). Personally I feel this is not possible as UI keeps changing until agreed upon by client, which is waste of time before development.   * Is it necessary to provide both Data Flow Diagram (DFD) and UI screen shot before development begins?


Entity-relationship model diagrams in Visio

I would love to create some database diagrams like this one with Visio but I can't find any templates at all for that kind of notation. The example I linked to was apparently made in Photoshop, which sounds like a terrible way to make ERDs. Are there any good Visio templates for this sort of thing? (I have Visio 2010 Pro, by the way.)


US Software Patents

Hypothetical: I’m based in the UK. I’ve developed an application only to discover after it has gone live, that someone else has filed a US Patent application for similar software. I don’t know if the patent will actually be granted, since the software-functionality has probably already existed long before now. Definitely the business process has been done for many decades albeit manually or semi-manually. What are my options? I’m thinking   * Assume the patent will fail and just carry on. But be prepared to stop shipping if and when they are granted the patent.   * Assume it will be granted (because that what they normally do by default) and stop selling the application now; and offer refunds to those already purchased.   * Open the source. Make my source code open-source and free to amend etc. But copyrighted. Then I could at least continue and get cred for giving the software away free and revenue for improving or customising the application for individuals.


What it the best programming/developer productivity tool ... you have coded youself?

Well, the question is in the subject, but I would repeat - what is the best programming/developer productivity tool you have coded yourself. A small console application or a script you hacked in a day or two, and then wondering why have you waited for so long and haven't coded it earlier. Something that automated the (now only a 10 seconds long) process which was a mundane 20 minute manual task before. Something that not only made you a day, but continued to do so for another month or even longer. A pinnacle of a DRY principle, even though it was just comparing a two xml files which could not be **easily** compared with a Beyond Compare. A small living piece of software that makes proud of. So, what it was for you?


State design pattern: best implementation for my case?

Me and a mate have a discussion about what would be the best way to implement the pattern state for managing several screens for an application we are developing. We have a ScreenManager (I guess the Context class according some books) which looks like this (some irrelevant code has been removed to ease understanding) :               public class ScreenManager : DrawableGameComponent     {              #region Fields              List<GameScreen> screens = new List<GameScreen> ();         List<GameScreen> screensToUpdate = new List<GameScreen> ();              InputState input = new InputState ();              #endregion              /// <summary>         /// Constructs a new screen manager component.         /// </summary>         public ScreenManager (Game game)             : base(game)         {             content = new ContentManager (game.Services, "Content");                  graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService (                                                         typeof(IGraphicsDeviceService));                  if (graphicsDeviceService == null)                 throw new InvalidOperationException ("No graphics device service.");         }              public override void Update (GameTime gameTime)         {             // Read the keyboard and mouse.             input.Update ();                  // Make a copy of the master screen list, to avoid confusion if             // the process of updating one screen adds or removes others             // (or it happens on another thread)             screensToUpdate.Clear ();                  foreach (GameScreen screen in screens)                 screensToUpdate.Add (screen);                  while (screensToUpdate.Count > 0) {                 // Pop the topmost screen off the waiting list.                 GameScreen screen = screensToUpdate [screensToUpdate.Count - 1];                      screensToUpdate.RemoveAt (screensToUpdate.Count - 1);                      // Update the screen.                 screen.Update (gameTime);                 screen.HandleInput (input);             }         }              public void AddScreen (GameScreen screen)         {             screen.ScreenManager = this;                  if ((graphicsDeviceService != null) &&                 (graphicsDeviceService.GraphicsDevice != null)) {                 screen.LoadContent ();             }                  screens.Add (screen);         }              public void RemoveScreen (GameScreen screen)         {             screens.Remove (screen);             screensToUpdate.Remove (screen);         }     }      As you can see, the screenmanager has a list of GameScreens which are updated every time the Update method is called. Then here we have a couple of screens + base Screen class. At the base class, we create a coupling between GameScreen and ScreenManager, while there also exist a coupling between ScreenManager and GameScreen:               public abstract class GameScreen     {         ScreenManager screenManager;              public ScreenManager ScreenManager {             get { return screenManager; }             internal set { screenManager = value; }         }              public virtual void HandleInput (InputState input)         {         }              public virtual void LoadContent ()         {         }              public virtual void UnloadContent ()         {         }              public virtual void Update (GameTime gameTime)         {         }     }          public class TitleScreen : GameScreen     {         public Texture2D titleScreen;              public TitleScreen ()         {         }              public override void HandleInput (InputState input)         {             if (input.MenuSelect) {                 ScreenManager.AddScreen (new PlayingScreen ());         }          }               public class PlayingScreen : GameScreen     {     //...... Irrelevant implementation details for my question     }      As you can see there, TitleScreen knows about PlayingScreen, creates it and adds it to ScreenManager (creating a dependency between TitleScreen and PlayingScreen). Although this kind of implementation has been seen in books (as far as I've read), my companion proposes me another kind of implementation: He proposes to create an Observer approach, replacing in TitleScreen the whole PlayingScreen management with an event, which would then be suscribed by the ScreenManager, and then the ScreenManager would orchestrate all the management of screens. With this approach, he says TitleScreen could be reused in other applications and decouple screens among them, but create a big ScreenManager class who would be coupled with everyone. I'm not sure whether the State approach or the Observer approach is better for my specific case. Which would be the best implementation? Thank you


Should I put newlines before or after binary operators?

When you're in Python or Javascript, you should always put binary operators at the _end_ of the previous line, in order to prevent newlines from terminating your code prematurely; it helps you catch errors. But in C or C++, this isn't an issue, so I'm wondering: Is there any reason for me to prefer the second version to the first?               return lots_of_text            + 1;      versus               return lots_of_text +            1;      (For example, does one of them help prevent other kinds of errors? Or is one of them considered more readable?)


I have 6 years of programming experience, mostly following the object oriented paradigm, and I'm interested in learning functional programming. My main goal is to become a functional paradigm programmer and not a programmer who is using a functional language but still writes in imperative style. When I'm practising in functional programming I still follow an object oriented way of thinking, like loops, mutable variables and so on. I picked F# as a basic functional language and because it's very tightly integrated with other .Net languages, like C#. F# allows usual object oriented statements, therefore you can use F# syntax but not actually produce functional code. What statements and approaches should I avoid when learning functional programming?


What are the open source options for a Bug tracker on IIS 7 & SQL Server 2008? Currently we're running a Windows Server 2008 with IIS 7, Coldfusion 8 & SQL Server 2008. What are the best options for an easy to install & use Bug Tracker?


What is TCL, and is it a marketable skill?

I've gotten pretty far in some interviews for a company which seems to use several technologies I've frankly never heard of. The big one which I'd be working with if I got the job is TCL. What is TCL, and more importantly, how marketable is it as a skill? Would working in a job using for TCL for a few years be like getting a case of the MUMPS?


Book on Access and SQL

My little brother is a CPA but in his new job he is required to use access to pull his own data. He has grown frustrated with the limitations of the canned reports that he has access to. However he does have read access to the data cubes and can write his own queries. I am looking for a book that would be easy for him to understand. Any suggestions?


Designing object oriented programming

Basically, I want to make api calls using an SDK I am writing. I have the following classes:   * Car   * CarData (stores input values needed to create a car like model, make, etc)  Basically to create a car I do the following:               [Car carWithData: cardata onSuccess: successHandler onError: errorHandler]       that basically is a factory method that creates instance of Car after making an API call request and populating the new Car class with the response and passes that instance to the successHandler. So "Car" has the above static method to create that car, but also has non- static methods to edit, delete cars (which would make edit, delete API calls to the server) So when the Car create static method passes a new car to the successHandler by doing the following:               successHandler([[Car alloc] initWithDictionary: dictionary)      The success handler can go ahead and use that new car to do the following:               [car update: cardata]     [car delete]      considering the new car object now has an ID for each car that it can pass to the update and delete API calls. My questions:   * Do I need a cardata object to store user inputs or can I store them in the car object that would also later store the response from all of the api calls?   * How can I improve this model? With regards to CarData, note that there might be different inputs for the different API calls. So create function might need to know model, make, etc, but find function might need to know the number of items to find, the limit, the start id, etc.


What are good projects to create to show your future employers?

I'm finishing my last year of school while working full time and currently, I have a job that's completely unrelated to programming (student job to pay the bills...). I'm trying to find a job as a programmer (or website developer) or in a related field to get some experience. So far, I've seen companies that hire students part-time and I tried going there, but they always ask me for a portfolio of some kind to show my work and what I can do. The problem is most of my projects so far have been for school work, so they're not really impressive. The other projects are for my current job to help my fellow coworkers accomplish some tasks more easily or so they can be able to accomplish my current tasks when I'm gone. This would be a great project to show, but it's not done yet since I'm always adding new functionalities and I don't really feel like it's a good idea to show something that's not polished enough as a project I'm proud of. So I end up with nothing to show future employers and they don't call back for an interview or anything. I'd like to know what kind of projects are good to add to a portfolio to show future employers. I know it depends on where I'm applying and what that corporation does, but I'd like to have multiple different projects to show I can learn quickly and that I'm versatile. I know Python, Java, C++, Javascript, PHP, Oracle and MySQL the most, but I can pick up other languages and be functionnal with them very quickly. I'm asking because I don't want to end up spending a lot of time on projects that will end up not being a good way to show what I can do. I'm trying to plan my future the best I can.


In C++, are acquire-release memory order semantics transitive?

According to cppreference, we can use release-acquire semantics to ensure write-read precedence between two threads as follows:               // Thread A     1. Write to X     2. Atomic store to Y with std::memory_order_release     // Thread B     3. Atomic load at Y with std::memory_order_acquire     4. Read at X      Supposing that `2` is ordered before `3` (take it as a given that this occurs according to Y), we are guaranteed that `A`'s write to `X` is visible to `B` since we can establish a total order on the events (as conveniently described by my enumeration above) because `1 sequenced-before 2 synchronizes-with 3 sequenced-before 4` and because release-acquire ensure that all of `A`'s writes are visible to `B` after `3`. _However_ , the link above explicitly states that in this situation "all memory writes (non-atomic and relaxed atomic) [by A become] visible side- effects in thread B." My question is then: **are "visible side-effects" considered writes made`B` to threads previously unaware of `A`'s writes?** In other words, suppose I had a third thread `C` and another atomic:               // Thread A     1. Write to X     2. Atomic store to Y with std::memory_order_release     // Thread B     3. Atomic load at Y with std::memory_order_acquire     4. Read at X     5. Atomic store to Z with std::memory_order_release     // Thread C     6. Atomic load at Z with std::memory_order_acquire     7. Read at X      (Assume similarly that `5 happens-before 6`). Would `C` read `A`'s write to `X`? Or is `B`'s "visible side-effect" on `X` not considered a write?


What does a programmer do at a consulting firm type of organization?

I'm a senior in college and am getting close to graduation. I love programming, and I certainly want my first job to involve programming (I'm also looking at fit, culture, location, etc. etc.). I've noticed that some major consulting firms are recruiting from my school's engineering department and are looking for computer science majors. I'm considering going out to a few info sessions to get a feel for the work, but in general, what does a programmer do at a company like this? If the company is looking to fill a position called "Business Analyst" with a computer science major, will the job likely even involve any programming? If it does, how might this work vary from a typical programming job at a software company? Here is an example of the type of company I see recruiting.


In Knuth's MMIX, how can x be an octabyte (64 bits) and M[x] be a byte (8 bits)?

In Knuth's Fascicle 1 on MMIX, the "Memory and Registers" section on page 4 states: "thus if _x_ is any octabyte, M[ _x_ ] is a byte of memory." and "thus if _x_ is any byte, $ _x_ is an octabyte." How can _x_ be an octabyte (64 bits) and M[ _x_ ] be a byte (8 bits)? Conversely, how can _x_ be a byte and $ _x_ be an octabyte?


Building a route creator

Ok, already up front, I'm going to tell you, that this is a bonus task for Data structure course I'm taking. That should take care of all the questions whether or not this is for a homework. **Route creator** I have a task, where a company has to create a route for a given data set. The data set can be input for every operation and in the end, it should print out the optimum route. The conditions are like this:   * Streets can only be directed North-South or East-West, effectively making every angle between 2 streets in 90 degrees.    * The data set includes streets, junctions and places to pick client and where to drop him off, as well as the starting place for the car. My problem is, that I'm having trouble thinking of the correct data structure way to do this. What came up first from the top of my head was a directional graph. In theory, it should fit perfectly   * Streets are input up front with numeric identificators   * A node represents junction and is represented by the id's of the streets   * An edge between 2 nodes represents a piece of street and has length   * Places of interest are effectively a sub-class of Junction nodes therefore they have distance from the one node to another. Best route would then be calculated by finding the shortest path from the starting place of the car to the starting place of the client + shortest path from the starting place of the client to the ending place of the client + shortest path from the ending place of the client to the starting place of the car. Is my thinking in this matter even remotely correct? I am finding this quite difficult to image with any other data structure than a directed graph, but maybe I'm just limiting my options with this thinking.


research papers vs books

For studying advanced topics, what's the better and nearer to complete approach? Can books cover what's in research papers, journals or those ACM transactions, or Springer's LNCS? Or reading research papers is indispensable for getting advanced? If we can't depend on books for information, how can a learner know of what he is missing in a specific topic, since research papers cover a specific (very specific) topic which cannot be found in a collected manner of the whole topic as books do. Is there a place (may be wikipedia) which could help finding the way through a topic? Rephrasing my question, do research papers offer new information which may not be found in books or are they clever applications of the information found in books?


May I give a single class multiple responsibilities if only one will ever be reusable?

To the extent that I understand the Single Responsibility Principle, a SINGLE class must only have one responsibility. We use this so that we can reuse other functionalities in other classes and not affect the whole class. My question is: what if the entity has only one purpose that really _interacts_ with the system, and that purpose won't change? Do you have to separate the implementations of your methods into another class and just instantiate those from your entity class? Or to put it another way... Is it ok to break the SRP if you know those functions will not be reusable in the future? Or is it better to assume that _we do not know_ if the functionalities of these methods will be reusable or not, and so just abstract them to other classes?


How do PGP and PEM differ?

Email messages are sent in plain text which means that the messages I send to Derpina are visible to anyone who somehow gets access to them while they are in transit. To overcome this, various encryption mechanisms were developed: PEM and PGP are two of them. PEM canonically converts, adds digital signature, encrypts, and sends; PGP does exactly the same. So how do they differ? Is it that PGP (being a program) is used to generate a PEM message?


Are there studies on what programming does to the brain?

Are there studies on what effects have programming languages on the brain or for that matter any other artificial languages in general, like mathematics ? Speaking from my personal experience I feel very different every time I speak Italian, I feel like a virtuoso on a quest but at the other end when I coded in machine code in debug.exe I felt like the main charcter in`π(Movie)`. Why do I bring this up because I am suspecting that languages affect your mind and popular legends back this up too often: are full of mathematicians that crossed the Rubicon.


Requesting feedback on my OO design

I'm working on an application that creates music by itself. I'm seeking feedback for my OO design so far. This question will focus on one part of the program. * * * The application produces `Tune` objects, that are the final musical products. `Tune` is an abstract class with an abstract method `play`. It has two subclasses: `SimpleTune` and `StructuredTune`. `SimpleTune` owns a `Melody` and a `Progression` (chord sequence). It's `play` implementation plays these two objects simultaneously. `StructuredTune` owns two `Tune` instances. It's own `play` plays the two `Tune`s one after the other according to a pattern (currently only `ABAB`). `Melody` is an abstract class with an abstract `play` method. It has two subclasses: `SimpleMelody` and `StructuredMelody`. `SimpleMelody` is composed of an array of notes. Invoking `play` on it plays these notes one after the other. `StructuredMelody` is composed of an array of `Melody` objects. Invoking `play` on it plays these `Melody`ies one after the other. I think you're starting to see the pattern. `Progression` is also an abstract class with a `play` method and two subclasses: `SimpleProgression` and `StructuredProgression`, each composed differently and played differently. `SimpleProgression` owns an array of chords and `play`s them sequentially. `StructuredProgression` owns an array of `Progression`s and it's `play` implementation plays them sequentially. ![enter image description here](http://i.stack.imgur.com/uzgkQ.png) * * * Every class has a corresponding `Generator` class. `Tune`, `Melody` and `Progression` are matched with corresponding abstract `TuneGenerator`, `MelodyGenerator` and `ProgressionGenerator` classes, each with an abstract `generate` method. For example `MelodyGenerator` defines an abstract `Melody generate` method. Each of the generators has two subclasses, `Simple` and `Structured`. So for example `MelodyGenerator` has a subclasses `SimpleMelodyGenerator`, with an implementation of `generate` that returns a `SimpleMelody`. (It's important to note that the `generate` methods encapsulate complex algorithms. They are more than mere factory method. For example `SimpleProgressionGenerator.generate()` implements an algorithm to compose a series of `Chord` objects, which are used to instantiate the returned `SimpleProgression`). Every `Structured` generator uses another generator internally. It is a `Simple` generator be default, but in special cases may be a `Structured` generator. ![enter image description here](http://i.stack.imgur.com/SuK5T.png) * * * Parts of this design are meant to allow the end-user through the GUI to choose what kind of music is to be created. For example the user can choose between a "simple tune" (`SimpleTuneGenerator`) and a "full tune" (`StructuredTuneGenerator`). Other parts of the system aren't subject to direct user-control. * * * My question regarding this design is rather specific: **When I look at my design, it looks like the design-equivalent of 'code duplication': _'class-duplication'_ or _'design-duplication'_.** You can clearly see what I'm referring to if you look at the above diagram. My question is split into two:   1. Is my intuition correct? Is this duplication, or reoccuring pattern in the design, a bad thing?   2. If it is, how can I design this differently and more efficiently?


Prevent product key from being used on multiple virtual machines

I have a software product. it will probably run on VMs that have no network connection at all. I want the user to pay for each VM the user runs. I thought to ask the user for some kind of hardware ID and provide him with serial that is unique for his machine. But user can just copy the VM image and than have two machines running? So I thought of having a security dongle. But how can I prevent user from running two VM's on the same machine both connected to the same dongle? This should be only basic defense so that actual hacking will be required to breach the license and not only spinning one more VM.


How best to construct our test subjects in unit tests?

Some of our business logic classes require quite a few dependencies (in our case 7-10). As such when we come to unit test these the creation become quite complex. In most tests these dependencies are often not required (only some dependencies are required for particular methods). As a result unit tests often require a significant number of lines of code to mock up these useless dependencies (which can't be null because of null checks). For example:               [Test]     public void TestMethodA()     {           var dependency5 = new Mock<IDependency1>();       dependency5.Setup(x => x. // some setup            var sut = new Sut(new Mock<IDependency1>().Object,         new Mock<IDependency2>().Object,         new Mock<IDependency3>().Object,         new Mock<IDependency4>().Object,         dependency5);            Assert.SomeAssert(sut.MethodA());         }      In this example almost half the test is taken up creating dependencies which aren't used. I've investigated an approach where I have a helper method.               [Test]     public void TestMethodA()     {           var dependency5 = new Mock<IDependency1>();       dependency5.Setup(x => x. // some setup           var sut = CreateSut(null, null, null, null, dependency5);            Assert.SomeAssert(sut.MethodA());         }          private Sut CreateSut(IDependency1 d1, IDependency2 d2...)     {       return new Sut(d1 ?? new Mock<IDependency1>().Object,         d2 ?? new Mock<IDependency2>().Object,     }      But these often grow very complicated very quickly. What is the best way to create these BLL classes in test classes to reduce complexity and simplify tests?


MVP pattern and references

I am doing a Windows C# application. I asked this question and I was told that the viewer/presenter should never know anything about the model. Does this mean that I should not add a reference of my model to the GUI I am making and instead of, lets say `List<Car>` I should transport the information using only strings and ints e.g. `Dictionary<carID, carName>`? Because of the fact I am using EntityFramework, half of my domain model are basically in the `DAL` and rest are in the `BLL` and then I would need to add reference to both those layers. Is this the approach or am I doing it wrong?


Computers that operate exclusively on boolean algebra

I was wondering if there are any computers that operate exclusively on boolean operations. For example, no add, sub, mult, or div in the instruction set (although these could be emulated with the appropriate boolean code). Rather, the cpu would work by comparing 2 bits at a time, with instructions like and, or, xor. I realize that no modern computer would operate like this, but have any historical computers had an instruction set something like this?


How to avoid downcasting?

My question is about a special case of the super class Animal.   1. My Animal can moveForward() and eat().   2. Seal extends Animal.   3. Dog extends Animal.   4. And there's a special creature that also extends Animal called Human.   5. Human implements also a method speak() (not implemented by Animal). In an implementation of an abstract method which accepts Animals I would like to use the speak() method. That seems not possible without doing a downcast. Jeremy Miller wrote in his article that a downcast smells. What would be a solution to avoid downcasting in this situation?


DDD Bounded Contexts & Domains?

I've been working in a relatively complex application with 10's of database tables (Aggregates, Entities/Value Objects) and applying DDD. At this point it appears to be basically DDD-Lite meaning that there are Application/Domain Services, the Domain Model (Entities, Value Objects), and Repositories. I picked up a book Implementing DDD and the first thing he is mentioning is DDD-Lite and Bounded Contexts and Domain Events missing as first mistakes which are usual when beginning DDD. Currently I've tried organizing the Domain Model by Aggregate relationships, and using namespaces to demonstrate it. I'm failing to see the benefit/downfalls relating to separating the Domain Model project into separate Bounded contexts (yet). Perhaps it will become apparent later on but I'd like some real life feedback on Bounded Contexts (and possibly sub domains etc. if they tie into it).


Who should get a developer certificate from Apple if client want their company name to show up in App Store

I am about start my first project with client, However I will work as a consultant. So do I need to get developer certificate and post my client's app in app store? Or I should ask my client to get the license and then I help them deploying the app on their name? They don't want company name to be my organisation but they want their company name to show up in App Store. However the developer of app is my organisation not them. How to deal with this situation?


How to control messages to the same port from different emitters?

_Scene:_ A company has many factories X, each emits a message to the same receive port in a Biztalk server Y; if all messages are processed without much delay, each will trigger an outgoing message to another system Z. _Problem:_ Sometimes a factory loses its connection for a half-day or more and, when the connection is reestablished, thousands of messages get emitted. Now, the messages still get processed well by Y (Biztalk can easily handle the load) but system Z can't handle the flood and may lock up and severely delay the processing of all other messages from the other X. What is the solution? Creating multiple receive locations that permits us to pause one X or another would lose us information if the factory isn't smart enough to know whether the message was received or not. **What is the basic pattern to apply in Biztalk for this problem?** Would some throttling parameters help to limit the flow from any one X? Or are their techniques on the end part of Y which I should use instead ? I would prefer this last one since I can be confident that the message box will remember any failures, which could then be resumed.


Control flow testing in white box - static or dynamic?

Yesterday I asked a question that happened to have another meaning inside. I can see that Control/data flow is often mentioned to be static analysis (when tools is used) or dynamic analysis testing in terms of white box testing. Could it be that automatic analysis tools can just help by creating graphs or they do actually test it with inputs (then it would not be static IMHO).


I don't understand the arguments against operator overloading

I just read one of Joel's articles in which he says: > In general, I have to admit that **I’m a little bit scared of language > features that hide things**. When you see the code >   >   >     i = j * 5; >   > > … in C you know, at least, that j is being multiplied by five and the > results stored in i. > > But if you see that same snippet of code in C++, you don’t know anything. > Nothing. **The only way to know what’s really happening in C++ is to find > out what types i and j are, something which might be declared somewhere > altogether else. That’s because j might be of a type that has`operator*` > overloaded and it does something terribly witty when you try to multiply > it.** (Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as **abstraction** ) one of the key ideas of object-oriented programming? Everytime you call a method `a.foo(b)`, you don't have any idea what that might do. You have to find out what types `a` and `b` are, something which might be declared somewhere altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer? And how is `j * 5` any different from `j.multiply(5)`, which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of `j` and peek inside the `multiply` method, because lo and behold, `j` might be of a type that has a `multiply` method that does something terribly witty. "Muahaha, I'm an evil programmer that names a method `multiply`, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading! If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all. Please enlighten me.


how to layout good documentation

I need to write out a documentation for developers to be able to use some API web software how should i lay out a documentation? What should always be included? And does it need to be really long or keep it simple and easy as possible for anybody to understand?


Getting the relational table data into XML recursively

I have levels of tables (Level1, Level2, Level3, ...) For simplicity, we'll say I have 3 levels. The rows in the higher level tables are parents of lower level table rows. The relationship does not skip levels however. E.g. Row1Level1 is parent of Row3Level2, Row2Level2 is parent of Row4Level3. Level(n-1)'s parent is always be in Level(n). Given these tables with data, I need to come up with a recursive function that generates an XML file to represent the relationship and the data. E.g.               <data>       <level levelid = 1 rowid=1>         <level levelid = 2 rowid=3 />       </level>       <level levelid = 2 rowid=2>         <level levelid = 3 rowid=4 />       </level>     </data>        I would like help with coming up with a pseudo-code for this setup. This is what I have so far: Edited/Updated code:               XElement GetXML(ArrayList list, XElement xml)             {                 XElement xElement = xml;                 // Get the rows of the current list into xmlData format                 ArrayList childList = GetChildList(list);                      if (childList != null)                 {                     foreach (Row r in list)                     {                         // Convert the rows to xml                         xElement = new XElement(xml);                         xElement.AddFirst(new XElement("Row"));                         xElement.Add(new XAttribute("RowId", r.RowId));                              // Get the children as xml                         if (childList != null)                         {                             ArrayList childRows = GetChildRows(list);                             XElement childXml = GetXML(childRows, xElement);                             if (childXml != null)                             {                                 xElement.Add(childXml);                             }                         }                     }                 }                 return xElement;            }      This is the main function. I can add the rest of the test program if needed. Thank you.               static void Main(string[] args)             {                 Program p = new Program();                      // Initialize datasets                 p.InitializeLists();                      // Create xml map of the datasets                 XElement x = p.GetXML(p.level1, new XElement("Row"));                      Console.WriteLine(x.ToString());                 Console.ReadLine();             }


Separating Db from business with Inherited classes using multiple views

I have a software that has a car model that will be used in different views (listing, ads, detail page, carousel, up sell widget,etc).               class CarModel extends DbModel{          }      I look for a "nice way" (a combination of flexible, easy to maintain,etc) to have this used in views. I'm thinking at two different ways   1. Having object views for each context              CarViewBase{         var car;// of type CarModel         function constructor(args){             //will instantienta internal variable car based on args         }              function getThumb(){         }              function getTitle(){              }      }          CarListingView extends CarViewBase{         function getListing(){         }     }          CarAdsView extends CarViewBase{     //the busines rule changes for ads widget         function getThumb(){         }     }        2. Extending directly the CarModel The challenges comes when My Car Model might need an abstract factory. Let's say I have a field on my car object that states the type of the car : a truck, or a bike, or van. How would affect that my object view? Let's say that getTitle() rule would be different for each type of it. How would you do it?


How to get a database on my filesystem that I can use in my application

I'm making a .NET application where I'll have a lot of data entries. This will not go to any server though, but needs to be stored and updated, frequently on the local machine. I would like something like an SQL database, that simply exists in a file, in my application's folder (or in %appdata% or whatever). But how do I go about this? What can I use? I'm a big fan of Linq2Sql, so if it supports that, it would be awesome. I've tried to use MSSQL Compact, but I couldn't really get it to work very well. It basically required me to install MSSQL as well. What options do I have, other than MSSQL Compact?


Efficient mixing of sync and async methods within a single method?

Okay, it sounds odd, but the code is very simple and explains the situation well.               public virtual async Task RemoveFromRoleAsync(AzureTableUser user, string role)     {         AssertNotDisposed();         var roles = await GetRolesForUser(user);         roles.Roles = RemoveRoles(roles.Roles, role);         await Run(TableOperation.Replace(roles));     }      (I know I'm talking kind of in the abstract below, but the above is an actual method from what will be actual production code that is actually doing what I'm asking about here, and I'm actually interested in your actually reviewing it for correctness vis a vis the async/await pattern.) I'm encountering this pattern more and more often now that I'm using `async`/`await` more. The pattern consists of the following chain of events:   1. Await an initial call that gets me some information I need to work on   2. Work on that information synchronously   3. Await a final call that saves the updated work The above code block is typically how I go about handling these methods. I `await` the first call, which I have to because it is asynchronous. Next, I do the work that I need to do which isn't IO or resource bound, and so isn't async. Finally, I save my work which is also an `async` call, and out of cargo-cult I `await` it. But is this the most efficient/correct way to handle this pattern? It seems to me I could skip `await`ing the last call, but what if it fails? And should I use a `Task` method such as `ContinueWith` to chain my synchronous work with the original call? I'm just at a point right now where I'm not sure if I'm handling this correctly. **Given the code in the example** , is there a better way to handle this async/sync/async method call chain?


How to manage a growing team?

I'm the admin assistant of the CTO and our organization has recently experienced a lot of growth. Within six months, we have merged with another organization and our Dev team has grown from 8 to 16, with another 8 people in QA. What we're dealing with now is a highly technical individual, with little patience, managing a much larger team than he's accustomed to, 40% of which is junior as well as an increase in the number of projects. Needless to say, my boss is being pulled in too many directions at once. How can I help him manage his workload and his team so that the team feels they're getting enough help and support and remain effective? Also, where can I find additional resources on managing a growing team?


Phone Number based Login

I'm trying to implement a phone number based login and not sure if I should ask the users for full number, i.e country code + number or just the number. What I have in mind so far:   * Attempt optimistic login using whatever number user gives.   * Most likely, it'll come back with a single user match.   * In case there is a collision, throw an error (and show some helpful clue to the user asking them to enter full number) I guess this is a simplistic approach with minimum friction and complexity (as opposed to IP detection, geography based resolution etc.).


What is a good algorithm to distribute items with specific requirements?

I have to programmatically distribute a set of items to some entities, but there are rules both on the items and on the entities like so:               Item one: 100 units, only entities from Foo     Item two: 200 units, no restrictions     Item three: 100 units, only entities that have Bar          Entity one: Only items that have Baz     Entity one hundred: No items that have Fubar      I only need to be pointed in the right direction, I'll research and learn the suggested methods.


Are there any good tools to help implement or enforce the proper equals and hashcode patterns for c#?

A very common bug on my development team is forgetting to, or incorrectly overriding equals and hashcode. While the pattern is simple, there's a lot of boilerplate code that goes into doing this correctly. Implementing `IEquatable<T>`, `IEquatable`, `IComparable<T>`, and `IComparable`. While sometimes this needs to be done in a custom fashion, almost always this is simple a checking of types followed by a checking of an ordered set of fields. In the absence of compiler support (while I hope is coming), can a code generator/analysis tool help with this problem? What would be idea is to simply tag properties or fields with an attribute (say [EC_KEY] (for Equality/Comparison Key)). Then all the appropriate routines for checking those fields/properties (in lexical order) would be generated (using those field's type's corresponding equality or comparison operators and, of course, natural ordering for primitives) Ideally, the analysis tool would report as error objects where no tags (or explicit overloads) were found, but could have tags like [EQ_ALL] (to use all fields/properties) or [EQ_IGNORE] to explicitly ignore the class.


Complex Release Vehicle Management

I'm looking into improving our build and release system. We are a .Net/Windows shop, and I don't see any really good tools for Windows for generating the files that are to be dropped in patch or hotfix. We are currently using TFSBuild 2010 with Windows Workflows for our continuous integration builds as well as our daily full build which includes an Installshield package for deployment.   1. What is a good way of generating the list of files to be included in a "patch" style release, where one does not redistribute all the files, but only those necessary to accomplish the necessary changes? Are there any open source tools that work well for this, or do teams usually roll their own? I have considered using Beyond Compare but I would prefer something open source. The file "patch" creation must be 100% automatable.   2. Which release vehicles really ought to be patch style? And which releases should replace all system files related to our application? Assume we have a very large amount of resources necessary to maintain.   3. Is there any established material that is trusted within the industry for strategies about this? I realize it is different for "enterprise" rather than with typical websites. I am looking more for "enterprise" strategies due to our product distribution style. tl;dr > Looking for info on how to ship more reliable packages?


Do you know of a data-pump design pattern?

I frequently encounter a situation where I need to write a program which reads data-objects from a file or system, does a transformation on the data, convert the data to another datamodel and then push the data in another file, or system. Do you know of a object-model which facilitates these type of programs in such a way that it is pluggable and scalable?


Are Language Comparisons Meaningful?

Dr Bjarne Stroustrup in his book D&E says > Several reviewers asked me to compare C++ to other languages. This I have > decided against doing. Thereby, I have reaffirmed a long-standing and > strongly held view: "Language comparisons are rarely meaningful and even > less often fair" . A good comparison of major programming languages requires > more effort than most people are willing to spend, experience in a wide > range of application areas, a rigid maintenance of a detached and impartial > point of view, and a sense of fairness. I do not have the time, and as the > designer of C++, my impartiality would never be fully credible. > > -- The Design and Evolution of C++(Bjarne Stroustrup) Do you people agree with his this statement "`Language comparisons are rarely meaningful and even less often fair`"? Personally I think that comparing a language X with Y makes sense because it gives many more reasons to love/despise X/Y `:-P` What do you people think?


What are some reasonable arguments in favor of closed source software?

I like a technology (including programming language) but its platform is closed sourece and many times I meet people who ask me, "why do you use a closed source platform, why not use an open source alternative? If there is something wrong it should be with the closed source not with the open source, (as they say)". Actually I don't know how to answer their question. Could anyone tell me a good answer? Why do you use a closed source platform?


How Can I Make My Programming Class More Interesting?

I already found a similar question here on SO, but almost all of the answers were more philosophical, rather than practical. I'd like some PRACTICAL ideas about how to make my programming course more interesting. It doesn't matter how much effort it takes. I thought about asking my students to pick a topic in the beginning of the course and to work on it as some kind of a real, small, startup project that they could financially exploit once it's finished. But I'm afraid that most of them will not take the project to its completion, and that it could become very boring. Also I thought about involving them in Torcs, but I'm afraid most of them wouldn't be up to the task. Btw, Torcs is Car Racing Simulation, but there's an API for developers so they can develop their own AI for the driver, and then race their car against other programmers' AIs. I'm not asking here for problem examples, as I asked a separate question about that. I need ideas about making my lectures more interesting and fun.


Algorithm refresher. Why is heapsort an insort algorithm?

I can not see why the heapsort is considered an inplace **sorting** algorithm. I mean an **extra** data structure populated with the elements of the array to be sorted i.e. a heap, is used to assist in the extraction of the min value and the sorting process. So may be I am misunderstanding the definition of inplace here? But insertion sort for example it is obvious that it is inplace algorith, i.e. no extra memory needed for the elements. So why is it considered inplace?


How can I advocate unit testing on private code?

I'm trying to advocate unit testing in my workgroup, but an objection I often get is that it should be used only for externally exported API (which is only a minimal and non critical part of our system), and not on internal and private code (which now has only functional testing). While I think that unit test can and should be applied to all the code, how can I persuade my coworkers?


How much math do you learn in computer science?

How much do you need to know for computer science? When you get out of a PhD program in computer science at most schools how much math do you come out knowing? I'm guessing beyong the high school precalc stuff, you have to know what's called discrete math that there's usually one course for at most schools and it covers all the concepts required for compiuter science (combinatorics, probability & statistics, number theory, proofs, formal languages, etc.) And I'm guessing you need to know linear algebra, and calculus (both single and multivariable). I don't think you need to know differential equations, abstract algebra, higher analysis, non-euclidean geometry, and stuff like that - typically, a math major learns those.


I'm so jealous of middle-aged developers. Are we unlucky?

First of all, I couldn't decide the right words for title after reading How old is "too old"? question. I still can't decide with old, middle-aged, expert or professional. As you know, there are a lot of developers over 35-40 years old in StackExchange. They are helping to beginners and having less experience people. They are so valuable users. And mostly, their some answers are awesome becauase of good analyzing and adding their experience to answers. When I see this kind of users, they all started programming with kind of Lisp, Pascal, Cobol or Basic type programming language. These are the first modern programming languages. And I think these people are so lucky learning programming with them first because of they are close to machine language. Maybe they learn the basics of programming better. Now it looks they are working easly with object orianted programming. I'm graduated from computer engineering a year ago . First year, we superficial learned C programming language. Second year, there are C# and Java course. But when I try to learn this languages in colluage, I always feel like I missed something. Learning languages, structures, libraries.. if fine but teachers never teach us "How the codes working in machine?". They teach us the programming language which is popular in software market. So kind of they prepare us for companies. They think If we learn assembly or fortran, we can't easly find a job according to Java or C#. Unfortunately, at these days, this is kind of true. Could be better learning first Assembly, Fortran, Cobol instead of Java and C#? Are we unlucky?


How to prevent my executable being treated from AV like bad or virus?

I'm creating a piece of software, that will run on windows and will act like launcher for the game, to serve as an auto-updater and file verifier in client siede PC. One thing I don't understand, why my antivirus software (Avast) is considering my exe file as dangerous and won't start it without asking to put it into sandbox, for safe use. Is there any rules that my software should obey, to be treated as good, or should I pay hundreds of dollars for some sort of digital signing and other stuff? I'm using C# with MS Visual Studio 2010. VirusTotal report. No DLL injections, working as remote file downloader, using WebClient() class. It is not like it warns about virus, but it "suggests" to sandbox it. Look at screenshot:![enter image description here](http://i.stack.imgur.com/Cp85Z.png)


Application architecture for subscriber based system

I am planning on building a system where users "subscribe" to "records". Records are updated on a schedule, several times a day. When records are updated, the user should be notified that these records have been added/updated. I don't want each user to have their own copy of the records due to storage space and the overhead of inserting many records, one for each subscriber, each time the schedule runs. However, each user will need to add metadata against each record they are subscribed to. Such as notes and flags that the record has been read etc. Can anyone give me any advice or how to structure such a system or where I can learn more about this sort of application architecture? Is this the correct place to ask? At the moment, I'm not even sure what to Google for ;)


How to manage my private key for signing .NET assemblies?

I write open source .NET class libraries as a hobby and thought about signing them. I can get Visual Studio to generate me a password protected public/private key pair and save it as a .pfx file, but I don't think I should do this for _each and every_ project. One key pair should be enough, right? Obviously I'm not going to put my .pfx file with the source code in my online public repository: only the assemblies I release should be signed with my key pair. Other people can use their own keys if they want. So I'm left with some .pfx file that supposedly contains my public/private key pair.   * How do I manage my key pair effectively?   * Where do I store it?   * Do I have to import it somewhere?   * How can I use it on both my PC and my laptop?   * How do I prevent the key pair hell when switching from PC to laptop?


Is wikipedia a valuable resource for studying data structures? (can we call it complete?)

Can I depend on wikipedia to learn data structures fully using the list of data structures http://en.wikipedia.org/wiki/List_of_data_structures and the links they refer to? The same question for algorithms http://en.wikipedia.org/wiki/List_of_algorithm_general_topics ?... What's after learning algorithms and data structures? Specializing in a certain field of algorithms such as computer graohics, memory management...etc? or what could be the plan for mastering programming after knowing the language syntax and the background about program design and programming logic? I asked about wikipedia because i would like to find a complete resource or are least a resource which would be enough for the field of data structures instead of searching for separate articles in different places in other words an alternative to books which may even be more complete.


Semi-securely storing data in a remote key-value store, ensuring minimal data corruption/tampering

I'm bashing around a few ideas for storing usage data (similar to google analytics) for some Javascript products that we are working on. Unfortunately as yet we don't quite know 100% what data we want to store and only have a basic idea of the metrics we want to glean from it. My thinking is that basically we want to store a set of key-value pairs grouped by a unique instance_id (there may well be flaws in this logic:)). With that in mind I knocked up a (very) quick prototype in monkrb, the grand total of which is below:                 get "/store" do         key = params[:key]         value = params[:value]         instance_id = params[:instance_id]         Ohm.redis.hset instance_id, key, value       end      While this should work, I'm somewhat worried that an inquiring mind could easily pollute our data with random sets and key-values, doubled by the fact that this is all going to be called in Javascript so anything we do to secure or encrypt it is going to be pretty transparent to anyone who cares to view source. A lot of it should be easily filtered out, as come reporting time we'll have an idea which keys we are interested in (and know which ones we've created) so we can just junk any sets that contain keys which we know nothing about (though again there's the risk that additional keys have been added to an otherwise valid set..) Following down this path here are my questions:   1. What steps can I take to make it as hard as possible to add completely false data? (handshaking, obfuscation, signing, etc)    2. What can I do to try and detect any junk data? (bonus for a rough idea of how to implement too)   3. What sort of checks should I have in place to stop an existing instance_id being guessed and messed about with? (so any historical data can't get polluted) It should be noticed that this is mostly academic at the present stage, as I know 6 lines of ruby does not an application make, I'm just interested in the scenario and would like to hear others approaches and thoughts on where one could go with this.


Storing 'sensitive' data in settings file

I'm writing a small utility in AutoIt that connects to Twitter. I would like to store the username and password in the programs setting file, but I know that it needs to be encrypted obviously. Previously when I've done this for personal use I've just adopted an `ini`format - written to a temporary file and then encrypted it using a rediculously long password and 256 bit AES encryption, just calling the file "settings.eini". However, I'm going to be offering this utility to the public. I don't expect a large amount of people to use it or for it to become a target, but I thought that it's best not to take chances. I've been reading about creating custom file extensions and it seems like something I want to avoid for now, so is there a standard/acceptable way of doing this?


Why isn't the ‘format’ method more widely used in Python?

I'm probably missing something here, after searching I couldn't find an answer. I've explored quite a few Python projects and one thing I keep noticing is the fact that the majority of them continue to use the **`%`** operator for formatting strings rather than the newer, recommended **`.format()`** method. Is there a reason for this? it seems like a trivial change, unless I'm missing something entirely. For example:               # count how many times the % operator technique is used     find . -name "*.py" -exec grep -HE "\"[^\"]+\"\s\%\s\w+|'[^']+'\s\%\s\w+" {} \; | wc -l          # and the same for format()     find . -name "*.py" -exec grep -HE "\w+\.format\(" {} \; | wc -l          # Results:     #     #               % operator        format()     # iPython          670               63     # Django           977               8     # Tornado          91                0     # requests         25                1      No real reason for this question, just curious. Cheers guys!


What is the advantage of choosing ASCII encoding over UTF-8?

All characters in ASCII can be encoded using UTF-8 without an increase in storage (both requires a byte of storage). UTF-8 has the added benefit of character support beyond "ASCII-characters". If that's the case, why will we _ever_ choose ASCII encoding over UTF-8? Is there a use-case when we will choose ASCII instead of UTF-8?


What would be the optimal way to solve a problem like this?

I have a problem where I have to change all the Xs in a 2D array into 0s, and I have to calculate the minimum steps (where a single step consists of changing an entire row or column) required to do so. For example, in an array like-               [[X, X, X],          [X, 0, 0],          [X, 0, 0]]      The minimum number of steps required here is 2. I thought of a brute force approach (where I am checking row-wise once and column-wise thence and then comparing them to check which takes minimum number of steps) but that would give me an answer of 3, which is not the desired output. Any help, or clue, regarding how I should approach this problem would be appreciated, thanks!


History of vendor css prefix

When and how did this process of prefixing css with vendor specific prefix begin. Which browser/org start this and why was this started. I searched the web but found no details on this.


Whats the logic behind making ViewBag a dynamic object in ASP.NET MVC 3

Last time I checked C# was loved by many because it's a statically typed language but the introduction of ViewBag in ASP.NET MVC 3 brings the same problem that is there with strings: in a controller you type one thing and in the view you can by mistake type something else. What's the reason for making ViewBag dynamic? How is it better?


Searching integer sequences

I have a fairly complex search problem that I've managed to reduce to the following description. I've been googling but haven't been able to find an algorithm that seems to fit my problem cleanly. In particular the need to skip arbitrary integers. Maybe someone here can point me to something? Take a sequence of integers A, for example (1 2 3 4) Take various sequences of integers and test if any of them match A such that.   1. A contains all of the integers in the tested sequence    2. The ordering of the integers in the tested sequence are the same in A   3. We don't care about any integers in A that are not in the test sequence   4. We want all matching test sequences, not just the first. An example               A = (1 2 3 4)     B = (1 3)     C = (1 3 4)     D = (3 1)     E = (1 2 5)      B matches A C matches A D does not match A as the ordering is different E does not match A as it contains an integer not in A I hope that this explanation is clear enough. The best I've managed to do is to contruct a tree of the test sequences and iterate over A. The need to be able to skip integers leads to a lot of unsuccessful search paths. Thanks Reading some suggestions I feel that I have to clarify a couple of points that I left too vague.   1. Repeated numbers are allowed, in fact this is quite important as it allows a single test sequence to match A is multiple ways A = (1234356), B = (236), matches could be either -23---6 or -2--3-6   2. I expect there to be a very large number of test sequences, in the thousands at least and sequence A will tend to have a max length of maybe 20. Thus simply trying to match each test sequence one by one by iterating becomes extremely inefficient. Sorry if this wasn't clear.


How much should I pay to Microsoft when I am selling a desktop & Web base software built on VB.NET using MS SQL 2005 Express Edition?

Can I distribute the MS SQL 2005 Express edition along with my application to the customer?


Why are some files in programming projects named "commons"?

I have seen numerous projects have a file named `commons` for example:               commomns.go      I was wondering, why was this convention adopted and what did the meaning of naming a file or a package or something as commons?


How do I dissuade users from using the same password with similar systems?

I'm building a web application that connects to other web services (using strictly anonymous binding, so no user passwords are being used). However the web application maintains its own users itself, and is required to ask certain details such as e-mail addresses and public linking information to these other web services (for example, a username but not a password). I want to deter or prevent users from reusing passwords in my application that they have also used in the applications I'm linking to. For example, if I ask for their e-mail and provide me with their gmail address, I don't want them using their gmail password for my system. Another example would be reusing a password to a linked system in which they also gave me their username. One idea I had was to simply try using the information they gave me, along with the password they are trying to store and log in to these external web applications to test the password - then immediately unbind if I was successful and ask the user to use a different password. However I suspect there is a host of morale and legal issues there. The reason this is a big deal to me is accountability. My application is simply not funded enough to invest properly in security around user passwords. A salted, hashed password in a public SQL-like database is as secure as it gets. So if passwords and linked usernames or e-mails get out, I don't want my userbase compromised.


Writing/discussions about the aesthetics of code?

I'm looking for considerations of the questions "Can code be beautiful?" and "What makes code beautiful?" Examples would include:   * This academic paper: Obfuscation, Weird Languages, and Code Aesthetics   * This blog post: Hamon or the Skin Deep Beauty of Code Please note that I'm not trying to start a discussion here, or asking for opinions about what makes code beautiful, or for code you think is beautiful; I'm trying to find stuff that has already been published. Thanks for your help.


Does professionalism in job postings matter?

I came across this job posting: http://www.justin.tv/jobs/jobs. The page contains some bad language ("No bulls--t"). I personally find this vaguely offensive, and it would certainly put me off applying to work there: It made me wonder what kind/personality of people work at this company. At least where I'm from (EU), the language would be considered bad form, and it would be seen as badly representing the company. Some job postings seem to go to the other extreme, filled with vacuous people skill descriptions and irrelevant details. It's tempting to dream up pictures of each company based on their job posting. So, does professionalism in job postings matter? Are you inclined to see through bad language, irrelevant corporate speak and so on, or do these affect interest in a job?


Document Versioning

I have been tasked by my boss to look at a system where we create Python scripts and upload them to a server and store details in the DB. He also wants me to implement versioning, so that if any changes are made to a script then the updated version has an incremented version number. This is the area where I am not so sure about. How would you go about implementing a versioning tool? Is it simply a case of incrementing a field in the Database with the new version number? Or is it more complex than what it initially seems?


How to explain why multi-threading is difficult

I am a fairly good programmer, my boss is also a fairly good programmer. Though he seems to underestimate some tasks such as multi-threading and how difficult it can be (I find it very difficult for anything more than running a few threads, waiting for all to finish, then return results). The moment you start having to worry about deadlocks and race conditions, I find it very difficult, but the boss doesn't seem to appreciate this - I don't think he has ever come across this. Just slap a lock on it is pretty much the attitude. So how can I introduce him, or explain why he might be underestimating the complexities of concurrency, parallelism, and multi-threading? Or maybe I am wrong? Edit: Just a bit on what he has done - loop through a list, for each item in that list create a thread that executes a database update command based on the information in that item. I'm not sure how he controlled how many threads executed at once, I guess he must have added them to a queue if there were too many running (he wouldn't have used a semaphore).


Storing different algorithms and using them for demonstration

I have an app for creating simple graphs (the kind with vertices and edges) and then using different algorithms on them (BFS, DFS, topsort, Prim's etc) for demonstrating how they work. I'm now working on porting it into a Rails app and deploying so it can be used by my university (hopefully). Currently the graphs are stored in a SQLite db and I am planning to do some D3 magic on them. Then to the real problem, how should I implement and store the algorithms? I want to be able to "step" through the algorithm, showing step by step how it works on the graph. In my previous implementation, written in Java, I had an abstract Algorithm class with abstract methods like init, step and reset. But, now that we are out of the Java world and using wonderful Ruby, I have a feeling that there's a really clever and elegant way achieving the same. I am planning to pack it into a Rails engine, just for kicks. Here is the mentioned Java implementation: https://github.com/7SLEVIN/visualgraphalgs


Dataset with coordinates of borders of countries

I am creating an application that visually displays world regions, e.g. to place markers within an administrative region. Does a dataset exist with geometrical or geographical (long/lat) descriptions of the world's current country borders (and possibly other administrative divisions)? Ideally the dataset would be in a format that I could easily generate border images of the size that I require.


Is it possible to use the Intel C/C++ compiler on Linux to create object files to be linked on Windows?

**Why?** Depending on your source the Intel compiler is likely or most definitely the compiler generating the fastest executables for the x86 architecture (5 to 100 % execution time improvement). Intel offers its compilers for Linux under a non-commercial license for free (I think I read it is free somewhere on their page: Intel - Non-Commercial Software Development). There is also a free non-commercial license for students, but this license is not applicable although tools are offered for all three major operating systems (link dropped due to reputation restriction). **Goal** I (as a non-student) would like to be able to use the Intel compilers for possible execution speed improvements under the non-commercial license to compile object files that can be linked to create executables and dynamic link libraries for Windows (and possibly OS X) **More Details:** What I inferred from this document is that the Intel compilers create object files that are compatible to the dominant compilers of the platform. **Sub-questions:**   1. What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?   2. _Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?_   3. Am I right that the metadata in the generated object files is the main issue? ad 2:   mingw32-objcopy seems to be able to convert the Intel compiler output on Linux (presumably ELF) to Microsoft-compatible COFF (with the possible exception of relocateable object files). Could someone confirm that this actually works (for non-trivial applications), please?


What is the best way to build a static page web site from a JSON API?

I have a JSON API that includes some discusssions. I want to build a static html site on another server, pages that are built from data on that API. I am more comfortable using Rails than Node. The API is done in Node. The idea is that I periodically call the JSON api to get the data, and dynamically build the html pages on the Rails server. This way the web pages would be super fast, wouldn't have to call the JSON API. One technology that looks like it would do the job is http://middlemanapp.com/, but I haven't used it before. Anybody done this before and have any suggestions? My preference is to use Rails, and Heroku.


How does one become a big contributor to an opensource project?

I know that the default advice for open source projects, and getting started, is to start fixing bugs. But I have a feeling that its the path that one would want to take if they wanted to be a tester/fixer of bugs in the project. How does one become an active contributor of an opensource project? [I.e. on the level of architecture]


How does one write a book on a new framework?

How are authors able to write a book on a framework that is just released? A framework like spring is updated, and a book is released in the next day. Is this typically by people who are direct contributors? Are they basing it off of beta/alpha versions? I find this rather difficult to understand as that documentation is rarely up to snuff by the time the framework is updated.


Rails - Does using partials slow views rendering?

I'm having performance issues on a Rails `3.1.0` application, now I've done dome changes on my queries with AR and so but views still takes too many time to render, I've divided the views, loops and so, on many partials that are rendered dynamically inside views and inside other partials. So it's a bad practice to have a large number of partials? Should I reduce the number of partials to improve the views rendering time? Thanks


Is there something wrong with how we're doing version control?

I work with a team of programmers as the business analyst. We just released version 2.0 of our product and are working on the next version to be released in 3 months (it's an internal software product). Unfortunately version 2.0 has some issues that they have had to fix and we're going to deploy those fixes in a couple weeks. The problem is that we also don't want to deploy the changes that are still being worked on and are not slated to be released for another 3 months. The programmers decided that the way to manage this was that only the code for the defects will be checked in, and the code for the new enhancements will be kept on the developer's local machines until they are done. I will have to get local builds from their machines to test because if they check in the code and we have to push out another patch to fix defects we don't want to include those enhancements just yet. There is also the problem where the same code file contains both defect fixes and enhancements, so they have to copy the code file locally, then make a change to fix a bug and check that one in, then resume work on the enhancements by taking the local copy they made. It seems quite convoluted - is there a better way to handle this type of scenario? We're using Team Foundation Server and Visual Studio 2010.


Is there a technical reason why you can't develop iOS apps on a Linux computer?

I understand why you can't develop OS X apps on a Linux computer, but is there a good technical reason why you can't develop iPhone and iPad apps on Linux? Why isn't it possible to compile iOS source code into an iOS executable and run it in an iOS simulator on Linux or install it on a development iOS device? Is it just because the XCode IDE is a Cocoa application? You can develop Android apps on any kind of platform, it seems. I don't see why the same can't be true of iOS.


AGPL Question about Linking and Derivative Works

I'm thinking of selling a collection of Django apps I've written which provide the basic functionality of a Facebook game, but I'm also thinking of releasing it under a GNU Affero GPL. I read the Affero GPL, and the extra clause specified that modified versions of a covered work have to be distributed under the same license. What I'm wondering is, do derivative works have to be distributed under the GNU Affero License, even if they don't modify the original? The scenario is someone could use my project and add a few features of their own contained in separate Django apps; would those new apps they've written which depend on my software have to be released under an Affero license as well?


Is it a good idea to read compiler source code?

I'm a junior in college majoring in Computer Science. Apart from writing lots of code, I want to start reading source code written by others to improve my coding skills and learn better/different ways of doing stuff. I was thinking I should start reading some of the key parts of the code in C++ compilers. I think this would help me do two things:   * Learn elegant coding practices because compilers are hard and the code represents solutions to this hard problem.   * This would also help me learn about how my most used language is compiled, the details, how each error is generated, how code is parsed, and become really good with the specifications of the language. Do you think this is a good idea?


Do most programmers copy and paste code?

I learned very early on that cutting & pasting somebody else's code takes longer in the long run that writing it yourself. In my opinion unless you really understand it, cut & paste code will probably have issues which will be a nightmare to resolve. Don't get me wrong, I mean finding other peoples code and learning from it is essential, but we don't just paste it into our app. We _rewrite_ the _concepts_ into our app. But I'm constantly hearing about people who cut & paste, and they talk about it like it's common practice. I also see comments by others which indicate it's common practice. So, do most programmers cut & paste code?


How can I send data without POSTFIELDS in PHP curl?

I'm using a REST API through PHP and I'm a bit confused on the CURL_POSTFIELDS behavior, which implies that I must send a querystring or array, but what I'm seeking to do is just to send a string of JSON text. In the API I'm using there is no such thing as a field: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Edit+issues So, how can I just send data that doesn't get interpreted as a query string, and without having to use a file?


Lost Interest in Programming

I am a computer science student currently in my 2nd year of bachelors. My problem is pretty straight forward yet still so far has not been self- resolvable. It is simply is that I am tired of programming. I don't know why but it just happened. When I started my first course in c++ I was very excited. So excited that I finished two heavy c++ books within 2 months and was way ahead of my class and my own expectations. It was like I can easily develop algorithms and code them. I explored C++ a lot, > but for the past 2 semesters I am pretty much not into coding and I have > lost a great amount of interest or passion for it. I love programming as well my CS degree.But even with that i am not able to set things up. Kindly tell me what to do? I have started C# and XNA Game development on my own but still it's like I am pushing myself. Can anyone give give suggestions to wake up the coder inside of me?


Interviews: How far to go on DVCS experience?

I've been interviewing some potential interns for a project I'm working on. We use git, so I'm looking for someone familiar with DVCS (or SVN/CVS or a desire to learn). A response that threw me off was "I've worked with github" with no further information, so it forced me to consider what to expect from a programmer working with version control. I actually led a VCS conversion, so I got more intimately involved with Git/DVCS administration than I thought I ever would be, so I don't think it is fair to hold a student to that standard. My question is, what should a junior programmer be comfortable doing when working with a DVCS? Should it be simple adds, commits, merges, remotes, or would you expect something more? If you've been asked good questions in interviews, I'd appreciate them being shared. I don't really want to hire the developer that pushes a backwards merge! Edit: I really should have mentioned before this got rolling that our distribution model relies heavily on Git and our self-hosted repository (I'm a web developer), and that's why I feel it's important to know (at the very least) the consequences of serious actions like remote pushes; these actions triggers a few different processes in our environment. My fault! The answers have still been very helpful.


Why does Eclipse need to be restarted after installing a plugin?

As Eclipse uses OSGi to handle modules and bundles, and therefore should be able to hot-deploy them, why does it suggest to restart after installing a plugin "for changes to take effect"? Has Eclipse hit some OSGi limitation, or is its architecture such that even with hot-deploy, it cannot guarantee that deployments went smoothly and hence takes the safest route by offering a restart?


Isn't MVC anti OOP?

The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data. In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?


Backbone.js app pulling large data sets with fetch()

I'm currently making some improvements for a client on a backbone.js app. The app is a web store and inventory management system. One thing that bothers me about this app (and other backbone.js apps I've encountered) is that it loads the entire collection of inventory items into memory from the server on every initial page load. After about a year and a half in production, this data set (not including image assets) is around 2.7 MB. So for every visitor to the web site, the javascript front-end pulls 2.7 MB data over the wire on initial page load. Of course this results in serious lag (around 8-12 seconds to load over most consumer-class broadband connections in my area). To me this load time is unacceptable. Of course once the data is loaded, the rest of the website is super snappy and responsive. Is loading an entire collection really the best-practice way of developing backbone.js apps? I'm trying to figure it out because the books and tutorials I've come across seem to teach this. Is there another pattern to follow? Trying to keep it backbone.js specific --- but how does one manage large datasets in this framework?


Where is the best place to get off my feet in Python programming?

I have tried to learn C++ and Java before, but the syntax confused me. I definitely will be learning them after, but for now, where is the best place for a guy who has programmed before to learn python? Do you concur with me learning Python? Should I stick with Java or C++ before?


Service layer vs DAO -- Why both?

I have been working with SpringMVC, Hibernate, and some databases in a java web application example. There are a few different ones that do this, but this Spring 3 and hibernate integration tutorial with example has a model class, view (in jsp), and a service and dao classes for the controller. My question is, don't both the service and DAO classes do the same thing? Why would you need them both? EDIT: This was the tutorial I was actually using (not that it matters) http://fruzenshtein.com/spring-mvc-security-mysql-hibernate/


Tracking feature requests for small-scale components

I'm curious how other development teams (especially those that work in moderate to large development groups) track "future" features/wishlists for functionality for internally developed frameworks or components. I know the standard advice is that a development team should find one good tool for tracking bugs/features and use that for everything and I agree with that if the future requests are for the product itself. In my company we have an engineering department, which is broken up into multiple groups and within each there can be one to several agile teams. The bug tracking product we use has been "a leader since 1997" (their UI/usability seems to also be evaluated against that year even today) but my agile team or even group doesn't really control what is being used by the whole department. What we are looking to track is not necessarily product features but expansion/nice to have functionality for internal components that go into our product. So to name a few for example...   * framework/utility library on top of CppUnit which our developers share   * low-level IPC communications framework   * Common development SDK that myself and several other team leads started to help share some common code/tools at the department-wide level (this SDK is released as internal "product" to each of the groups). Is the standard practice to use the one bug tracking tool? Or would it make more sense to setup something more localized specifically for our needs and maintain it ourselves? It's also unclear how management will feel if developers start performing "IT" roles of maintaining software and servers. At the same time, right now, we use excel files, internal wiki and MS OneNote for this kind of stuff and that just doesn't feel right. (I'm afraid to ask for actual software recommendations, since that might make this question more localized or something. Also developers needs this way more than management, so it would be nice to find something either free or no more than the cost of a happy hour).


Learning the basics

I am a Linux server administrator first and foremost... Having said that, I have been asked by a former high school teacher of mine to teach students a bit about programming. Like any Linux administrator, I know my fair share of Python and Bash. The problem is that I know NOTHING about the lower level stuff like "machine code" and compilation. The main purpose of this series is to teach programming, not computer science, so I don't need a graduate degree's level of knowledge for this, they will be learning Python first and foremost. However, I would like to learn enough to at least broach the subject with them, any ideas where I can learn that kind of stuff relatively quickly?


What Technology can Render Medium Scale 3d Environments in a Web-Browser

I intend to make a web application that displays 3d environments that can be navigated by dragging(with a finger or mouse depending on the platform). The web app will render 3d environments of development sites including contours, water pipeline locations, buildings etc. I am trying to decide what technology/libraries to use that will create a web- app that will work on Android-Web-Browser, iOS-Safari, IE9, Safari, Firefox and Chrome. And also what technology will provide speed in development. I understand that this is _'asking for my cake and eating it too'/'asking for the moon'_ but I don't know all the technologies out there - so there may be advanced libraries that can render 3d environments across many web-browsers including the main smart phone ones and I dont know of them. The 3d rendering would not be highly detailed buildings or water with effects, but rather simple 3d representations of these objects. The environment would be navigable by dragging around and you could view the landscape in layers(view only contour lines, view only underground pipelines, view only sewerage pipes, etc.). **Are there any 3d libraries for web-browsers out there? Is there a way to run OpenGL(or OpenGL ES) through a webbrowser?** **What technology would you use if you were making this kind of app/web app that should work on desktop Windows, Android, iOS and WindowsPhone?** **Is there any technology I have failed to mention that would be good for this kind of project?** I am tending towards a Browser Driven Web App because I get that cross platform ability(where it even works on linux and MacOS by using compatible web-browsers). Also I know of CSS3 transforms that can create cubes that can rotate in 3d space(NOTE only works for WebKit browsers - so no IE :( ). _But I don't know if CSS3 is robust enough to render whole 3d environments? Do you think it could? Maybe I could use HTML5 canvas's for this? Can Google maps create custom 3d maps?_