I can't really create anything, what can I do about it?

I'm a C# programmer, and I don't really think I can create a software, for example: if I have a task to take a WAV and play it, I'll just use the .NET SoundPlayer class. if I need to present a picture I'll just use a picturebox. I'm not even sure how .NET handles the tasks, does it over treat it and takes a lot of memory? what do I do in cases .NET doesn't support? for example, if I want to play a WAV as mentioned, that's great. but if I want to play mp3 file, the only thing comes to my mind is look for a different library on the internet that supports it. I see a lot of programs out there and just don't understand how they do it. even if it's a simple task like having a folder's thumbnail like it's showed in Windows Explorer (as shown here: http://public.bay.livefilestore.com/y1p_RvwMDp6PkWP- X_nOZbscmJTL1y32Vzd8pG0QCJbo3Wn-38GlzzclueXc- jT7-mbIX1B-d3ySoRWlzRk1aPWxw/HiloMediaPane.jpg?psid=1) I have no idea how it can be done. Also, when given a complicated task, say make a path-finder algorithm or anything that isn't a basic task, I'm blank and have no idea what to do. I feel like I'm missing something, and I'm sure a lot of people out there feel exactly like I do, what advice could you give them?


Passing data between concrete states?

I have a state ~~machine~~ pattern implementation that's pretty straightforward, but I've got a design problem I don't know an elegant solution to. Here's some partly pseudo code to illustrate.               class MainRoomState:State              public override void HandleJoinSuccess(string gameName, List<LobbyPlayer> players)         {                  Context.CurrentState = new LobbyState(Context);             //the players list needs to be in the LobbyState             //that data is specific to the LobbyState         }      Basically, the event triggering the state change also is providing data that belongs in the new state, and I don't know if there's a nice way to do it besides a shared class in the parent Context object, or by mangling the constructor for this special case. **Edit** \- in more detail I have my states setup to encapsulate state specific data as well as logic, which includes, in this case, a GUI screen belonging to the current state. This seems to be a more elegant way of handling not only separation of logic, but also state specific data. Here's what my abstract state looks like,               public abstract class GameState     {              public GameState(Game context)         {             Context = context;             Net = context.Net;         }              //Incoming events         public abstract void HandleConnected();         public abstract void HandleDisconnected(string reason);         public abstract void HandleNetworkNotification(string msg);         public abstract void HandleGameStarting();         //there's about 20 more methods not shown here       Here's my Game class, mainly functioning as a data holder, but it also controls the game loop timer, firing main events, etc.               public class Game     {         public Game()         {            //...bunch of init code here            CurrentState = new DisconnectedState(this);         }         public GameState CurrentState         {             get;             set;         }              //more methods, etc     }      You'll see that I opted for composite containment of the CurrentState rather than implementing pass-through methods. That was mostly because I disliked the messiness of passing through the calls when I really didn't need to. Also, the whole state stores a reference to Context, rather than passing it per method. I've got two questions/problems with the pattern.   1. Every concrete state MUST implement in some fashion, EVERY method in the abstract State. This is ridiculous overkill, and currently most of my states only use 20-40% of the methods, leaving me with a couple pages of this: > public override void HandleGameStarting() { //not handled in this state }   1. My second issue is that each state has it's own data that only needs to exist while in that state. I don't want to store a huge conglomeration of data in the Context object when a far more encapsulated way of handling it would be putting it in the state. Looking over your example, I suppose one answer to my original question is that I could properly pass through the methods to the Current State, and just do a kind of hack with the data, class Game               public override void HandleJoinSuccess(string gameName, List<LobbyPlayer> players)     {              CurrentState = new LobbyState(this);         CurrentState.HandleData(gameName,players);         //the players list needs to be in the LobbyState         //that data is specific to the LobbyState     }


Neural network input preprocessing

It's clear that the effectiveness of a neural network depends strongly on the format you give it to work with. You want to preprocess it into the most convenient form you can algorithmically get to, so that the neural network doesn't have to account for that itself. I'm working on a little project that (surprise!) is going to be using neural networks. My future goal is to eventually use NEAT, which I'm really excited about. Anyway, one of my ideas involves moving entities in continuous 2D space, from a top-down perspective (this would be a really cool game AI). Of course, unless these guys are blind, they're going to be able to see the world around them. There's a lot of different ways this information could be fed into the network. One interesting but expensive way is to simply render a top-down "view" of things, with the entities as dots on the picture, and feed that in. I was hoping for something much simpler to use (at least at first), such as a list of the x (maybe 7 or so) nearest entities and their position in relative polar coordinates, orientation, health, etc., but I'm trying to think of the best way to do it. My first instinct was to order them by distance, which would inherently also train the neural network to consider those more "important". However, I was thinking- what if there's two entities that are nearly the same distance away? They could easily alternate indexes in that list, confusing the network. My question is, **is there a better way of representing this?** Essentially, the issue is the network needs a good way of keeping track of who's who, while knowing (by being inputted) relevant information about the list of entities it can see. Thanks!


How frequently do you switch mode?

I tried VIM and liked it but something stopped from using it: I had to type ESC to often, very often, something like each 5 seconds, and it was highly uncomfortable, so I stopped using it as a primary text editor (now I use emacs, nice for programmer as I am). After my sad experience with VIM, I could get why some much intensive users love vim. But now I suppose that maybe, after a bigger training, the frequency of mode switching could decrease dramatically. So, to verify this hypothesis, I am asking to you, old vim users, how frequently do you switch the mode?


Beginner need help on learning Qt programming

Thought of learning Qt. Need help from experienced ones out here. How should I begin. Some good books to refer. Some good tutorials to learn... Edit: Also which is the good IDE available out there for Qt programming. One that gives inline help, auto completion,indentation... I am using Debian Lenny


Forward declaration vs include

`Reduce the number of #include files in header files. It will reduce build times. Instead, put include files in source code files and use forward declarations in header files.` I read this in here. http://www.yolinux.com/TUTORIALS/LinuxTutorialC++CodingStyle.html. So it says if a class (class A) in header file does not need to use the actual definition of some class (class B). At that time we can use the forward declaration instead of including the particular (class B) header file. Question: If the class (class A) in the header if doesn't use actual definition of a particular class (class B), Then how forward declaration helps to reduce the compile time?


What are creative ways to unblock a development team?

The setting: Multiple development teams, lots of dependencies and constraints. If one team is blocked on developing some code, getting service calls, or moving to a QA environment, what are ways for teams to creatively look for work-arounds to their issues?


Open Source, Copyright and Trivial Bugfixes

Say a developer has developed a library for their closed-sourced commercial application. Since they want to give back to the open source community, they publish this library under, say, the GPL, but continue to use it in their own application. Since they hold the copyright, that's fine. Now, a user of the GPL version finds a bug, fixes it and submits a patch to the original developer. As I understand it, to use this bugfix in their closed-source application, the developer needs to have permission from the submitter. If the submitter refuses, the developer has to find another way to fix the bug in the closed-source version. But what if the bugfix itself is really trivial? Like properly initializing a variable or checking for a null pointer? Something that any half-competent programmer can find and fix in a matter of minutes, given an error description? Is the patch for this still protected by copyright? Or can the original developer implement the identical fix in their closed-source application without consent of the submitter? _Note: This really is a hypothetical scenario, not one of those "my 'friend' has this problem" questions_


Front end written in languages used for back end!

From my experice in web development, I know that languages like PHP,Java,Python..etc is used for backend development stuff (software that running on server), and for front end stuff languages like JS/HTML/CSS is used. But i see many companies say that they use for example PHP for front-end development and say python for the backend. Does that mean PHP is front-end for calling other services written in other languages via REST,RPC ..etc?


Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?

The `new` keyword in languages like Java, Javascript, and C# creates a new instance of a class. This syntax seems to have been inherited from C++, where `new` is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance. In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using `new` \- and in fact, this way of constructing objects is much more common in C++. So, coming from a C++ background, the `new` keyword in languages like Java, Javascript, and C# seemed natural and obvious to me. Then I started to learn Python, which doesn't have the `new` keyword. In Python, an instance is constructed simply by calling the constructor, like:               f = Foo()      At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have `new`, because everything is an object so there's no need to disambiguate between various constructor syntaxes. But then I thought - what's really the point of `new` in Java? Why should we say `Object o = new Object();`? Why not just `Object o = Object();`? In C++ there's definitely a need for `new`, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the `new` keyword? The same question could be asked for Javascript. In C#, which I'm much less familiar with, I think `new` may have some purpose in terms of distinguishing between object types and value types, but I'm not sure. Regardless, it seems to me that many languages which came after C++ simply "inherited" the `new` keyword - without really needing it. It's almost like a _vestigial keyword_. We don't seem to need it for any reason, and yet it's there. **Question:** Am I correct about this? Or is there some compelling reason that `new` needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?


Simple questions to test understanding of Dependency Inversion Principle

I am preparing a short (1-2 hour) presentation about DIP to several (~5) junior developers (1-3 yr xp) in the office. At the end of the presentation I want to know whether they understood what I was presenting, what are some possible questions that I ask in order to figure out their understanding? Maybe something that can be answered and explained by them in 3 minutes or less?


Do you think that storing a variable length encoding in std::string or std::wstring is OK and do you do it?

I'm kind of horrified that people actually suggest using UTF-8 inside a `std::string` and are OK with UTF-16 `std::wstring`. Do you actually do this? Do you think that it is OK?


Open Grid Engine or Akka/Something more fault tolerant?

My use case is that I have a pipeline of independent, stand alone programs, that I want to execute in a certain order on specific pieces of data that are output from previous pipeline stages. The pipeline is entirely linear and doesn't do anything in terms of alternate paths through the pipe. I'm currently using SGE to do this and it works OK, however occasionally a job will overstep it's memory bounds, fail, and all jobs that require that output data will fail. The pipe needs to be restarted in that case, and it seems that whatever is providing the fault tolerance in akka might solve that for me?


Customer relations in agile development

My management just asked an unprecedented question in my (admittedly brief) history with the organization: "What can we do to help you?" Simultaneously, we're working several big projects for a fairly new client whose ability to push requirements around mid-project is legend. Developing for these guys is like tap dancing on quicksand. Seems like a prime opportunity to propose a shift to a more agile approach. The thing I know I'm going to get asked, and that I don't have any idea about, is how to quote/bid/bill for that sort of project. Do you go hourly? Do you bid a range of prices? Do you charge by the sprint? More generally, the aspect of the Agile Manifesto that reads "We value customer collaboration over contract negotiation" is GOING to scare my management. How do you value that in the real world of customers who want a lot for a little?


Getting started on Large Projects

I just graduated from my College with a B.S. in Comp. Science. Although it was a good school, we're the only accredited CS department in our state. I feel like im a decent programmer, not amazing, but not terrible. I got my first job about 2 weeks ago, it's a pretty entry level job: firmware development/tester. There isn't a whole lot of coding to be had right now (mostly simple stuff) but soon I will have the option of helping out with development (which is what I want to do). Thing is I have never worked on a huge project. In school we had "group" projects but nothing really big. So I'm not familiar with huge classes and such (main language was C++). Is this something I'll just get used to with time? Some fellow students were used to that with internships and such.but I never got that chance. My job was mostly a "one man job" kinda thing. Mostly little things. Plus in class we never did huge projects anyways. How do you guys "plan" out these things? Do you use a whiteboard and plan out classes and such or what? Another worry of mine is that I have to use google a lot for examples of code, because sometimes I just don't get how something works. Is this normal? I mean "technically" I've had 4-5 years coding experience but it really only feels like I had 2 years of actual experience.


Is Adobe Flash still viable for developing CBT (Computer Based Training) software?

From everything I have read about Adobe Flash over the past couple of years, it seems like the platform has received a lot of stigma in the web space. Regardless of that, is it still viable as a platform for building local applications such as CBT (Computer Based Training) courses?


What is the history of the use of "foo" and "bar" in source code examples?

Why do many code examples, especially tutorials, use the names "Foo" and "Bar" so often? It is almost a standard. For example:               void foo(char* bar) {       printf("%s", bar);     }


What's the origin of foo and bar?

> **Possible Duplicate:**   >  Using "Foo" and "Bar" in examples I know AT&T labs used them in their Unix days, but do they have even deeper histories?


Picking an image from a set of images that is most likely to be compelling to a typical viewer

Given a set of images on a webpage, what's a good way to pick a compelling image that is also representative of the webpage? The use case is displaying an image along with a description of a URL to a page, after a user includes it in a status update. I've found some techniques to find the most interesting part of a single image. Example: http://berk.es/smartcropper/ So maybe I can use this notion of entropy to compare images in a set? I am programming in ruby, so a pure ruby solution is preferable, but am open to others.


How Lua handles both integer and float numbers?

As far as I remember myself programming I was taught not to compare floating point numbers for equality. Now, while reading Programming in Lua about Lua `number` type, I found following: > The number type represents real (double-precision floating-point) numbers. > Lua has no integer type, as it does not need it. There is a widespread > misconception about floating-point arithmetic errors and some people fear > that even a simple increment can go weird with floating-point numbers. The > fact is that, when you use a double to represent an integer, there is no > rounding error at all (unless the number is greater than > 100,000,000,000,000). Specifically, a Lua number can represent any long > integer without rounding problems. Moreover, most modern CPUs do floating- > point arithmetic as fast as (or even faster than) integer arithmetic. Is that true for all languages? Basically if we don't go beyond floating point in doubles, we are safe in integer arithmetic? Or, to be more in line with question title, is there anything special that Lua does with its `number` type so it's working fine as both integer and float-point type?


The Relative Cost Efficiency of (Acceptance) Test Driven Development

I would like to know what the overall impact of resource planning on a software project is, where the requirements and design of the project are driven by automated acceptance tests and unit tests, in contrast to a more "traditional" approach to software development. ![enter image description here](http://i.stack.imgur.com/3vNIF.jpg) What, in your experience, is the overall effect on resource requirements for completing a software project under TDD, as opposed to more "traditional" development methodologies? It seems self-evident to me that quality would increase, and the amount of uncertainty decreases because testing is done earlier, but requiring tests up front seems like it would require more developer hours to accomplish. How much does the development effort increase, or does it actually decrease due to the up-front elimination of bugs? How much more effort is required from the customer? Do they have to change the way they relate to the project, especially if they are used to big design up front? Does the number of hours required of the customer overall increase, or does it actually decrease? I would imagine that time estimates would be very vague in an iterative TDD process at the beginning of a TDD project (since there is no Software Development Plan). Is there a point, say, 20% into a project, where confidence increases enough that a more or less stable time and money estimate can eventually be provided to the customer? Note: I'm not looking for subjective opinions or theories here, so please don't speculate. I'm looking more for real-world experience in TDD.


Is there any theory or science for building complex visualization GUI's?

Most "Canvas" widgets in common GUI toolkits offer low level operations like drawing basic shapes of different colors/line-width/etc, or displaying sprites and images. Some seem to have slightly more advanced features like the ability to treat primitives drawn on the canvas as "actors" so they can be moved and manipulated independently after drawing. How do you go from such low-level operations to highly complex and interactive visualizations, for example the Integrative Genomics Viewer (screenshot 1, screenshot 2, screenshot 3)? This tool lets you navigate various annotations and features located on a genome in a variety of ways, at the single- nucleotide level (ie, very low detail) to the whole-genome level (very high level overviews), handles very large data sets (100's of gb) and incorporates many different plot types many of which are unique to the application or at least bioinformatics. Beyond MVC, is there underlying theory or model as to how you should structure such an application?


Why write tests for code that I will refactor?

I am refactoring a huge legacy code class. Refactoring (I presume) advocates this:   1. write tests for the legacy class   2. refactor the heck out of the class Problem: once I refactor the class, my tests in step 1 will need to be changed. For example, what once was in a legacy method, now may be a separate class instead. What was one method may be now several methods. The entire landscape of the legacy class may be obliterated into something new, and so the tests I write in step 1 will almost be null and void. In essence I will be adding _Step 3. rewrite my tests profusely_ What is the purpose then to write tests before refactor? It sounds more like an academic exercise of creating more work for myself. I am writing tests for the method now and I am learning more about how to test things and how the legacy method works. One can learn this by just reading the legacy code itself, but writing tests is almost like rubbing my nose in it, and also documenting this temporary knowledge in separate tests. So this way I almost have no choice but to learn what the code is doing. I said temporary here, because I will refactor the heck out of the code and all my documentation and tests will be null and void for a significant part, except my knowledge will stay and allow me to be fresher on the refactoring. Is that the real reason to write tests before refactor - to help me understand the code better? There's got to be another reason! Please explain! **Note:** There is this post: Does it make sense to write tests for legacy code when there is no time for a complete refactoring? but it say "write tests before refactor", but doesn't say "why", or what to do if "writing tests" seems like "busy work that will be destroyed soon"


Increase application performance

I'm writing a program for a company that will generate a daily report for them. All of the data that they use for this report is stored in a local SQLite database. For this report, the utilize pretty much every bit of the information in the database. So currently, when I query the datbase, I retrieve everything, and store the information in lists. Here's what I've got:               using (var dataReader = _connection.Select(query))     {         if (dataReader.HasRows)         {             while (dataReader.Read())             {                 _date.Add(Convert.ToDateTime(dataReader["date"]));                 _measured.Add(Convert.ToDouble(dataReader["measured_dist"]));                 _bit.Add(Convert.ToDouble(dataReader["bit_loc"]));                 _psi.Add(Convert.ToDouble(dataReader["pump_press"]));                 _time.Add(Convert.ToDateTime(dataReader["timestamp"]));                 _fob.Add(Convert.ToDouble(dataReader["force_on_bit"]));                 _torque.Add(Convert.ToDouble(dataReader["torque"]));                 _rpm.Add(Convert.ToDouble(dataReader["rpm"]));                 _pumpOneSpm.Add(Convert.ToDouble(dataReader["pump_1_strokes_pm"]));                 _pumpTwoSpm.Add(Convert.ToDouble(dataReader["pump_2_strokes_pm"]));                 _pullForce.Add(Convert.ToDouble(dataReader["pull_force"]));                 _gpm.Add(Convert.ToDouble(dataReader["flow"]));             }         }     }      I then utilize these lists for the calculations. Obviously, the more information that is in this database, the longer the initial query will take. I'm curious if there is a way to increase the performance of the query at all? Thanks for any and all help. **EDIT** One of the report rows is called Daily Drilling Hours. For this calculation, I use this method:               // Retrieves the timestamps where measured depth == bit depth and PSI >= 50     public double CalculateDailyProjectDrillingHours(DateTime date)     {         var dailyTimeStamps = _time.Where((t, i) => _date[i].Equals(date) &&                                             _measured[i].Equals(_bit[i]) &&                                             _psi[i] >= 50).ToList();             return                 _dailyDrillingHours =                 Convert.ToDouble(Math.Round(TimeCalculations(dailyTimeStamps).TotalHours, 2, MidpointRounding.AwayFromZero));     }          // Checks that the interval is less than 10, then adds the interval to the total time     private static TimeSpan TimeCalculations(IList<DateTime> timeStamps)     {         var interval = new TimeSpan(0, 0, 10);         var totalTime = new TimeSpan();         TimeSpan timeDifference;              for (var j = 0; j < timeStamps.Count - 1; j++)         {             if (timeStamps[j + 1].Subtract(timeStamps[j]) <= interval)             {                 timeDifference = timeStamps[j + 1].Subtract(timeStamps[j]);                 totalTime = totalTime.Add(timeDifference);             }         }              return totalTime;     }


I've been trying to write an algorithm that will print separately the digits from an integer. I have to write it in Pseudocode. I know how to write an algorithm that reverse the digits.               digi(n):        while n != 0:         x = n % 10          n = n // 10          print (x)      But I don't know how to write an algorithm to print the digits in the correct order. For example, the input is integer `123467` and the output is: `1 2 3 4 6 7`. The numbers will be input from the user, and we cannot convert them to a string. I need help getting started on writing algorithms.


How to write descriptive conditionals for ifs?

I've gotten into the habit of using excessively descriptive names. In addition, I've also gotten into the habit of creating the conditions for ifs like so:               bool user_is_female  = user.get_gender() == GENDER_FEMALE;     bool user_is_warrior = user.get_unit_class() == CLASS_WARRIOR;     bool user_can_wear_battle_skirt = user_is_female && user_is_warrior;          if (user_can_wear_battle_skirt) {         user.equip(EQUIPMENT_BATTLE_SKIRT);     }      So, yeah, I dropped the "== true" or "true ==" that I've been taught was good practice. It seems to need less comments too. It is quite wordy/lengthy though. I was going for making the code more readable. So should I continue using this method? Any alternatives?               if (user.can_wear(battle_skirt)) {         user.equip(battle_skirt);     }      Was a suggestion that I had to delete because I posted in the wrong place.


LINQ vs Data Access Layer

I've taught myself always to handle any data access code in a completely separate 'layer' to my business logic and UI code. This has always been a very good architecture for me and any 'rules' or best practices I see, still manage to fit into this style of coding, especially Single Responsibility Principle. For most of my home projects, I'd use my own ORM I created, which I always intended to make open-source. However since then, LINQ became available, which was very similar to the way my ORM worked (but.. better). There's nothing that I could previously do with my own ORM that I can't now do with LINQ (except bits of the REST integration). So my question is; **is LINQ my new Data Access Layer?** Do I need this layer at all anymore? Should my BLL just talk directly to LINQ? Or is this bad practice still? **Edit:** The original question was referring to LINQ to Entities, but there are many interesting answers regarding LINQ to SQL. What are peoples thoughts on both of them? I gather than LINQ to SQL can't really replace a DAL, but could the Entity Framework?


Is there a way to determine if a database has been altered, then to push new data to the Application

All our (my company) currently applications pull information from that database, is their a way to get the following types of databses to either push data or push an event to allow the application to pull data.   * Access   * SQL   * Oracle   * File systems (Files and folders) The issue today is that most of our application spend a large amount of time constantly looking at databases and file system checking to see if data has changed . It would be better for the database to inform the application when data has changed. Are there tools within Visual studio to allow this or are there tools within the database / filesystem to do this? All ready asked this on stack overflow but go no answer. I've been doing some more research but I cant seem to get any further. My manager has asked to investigate it as it would mean our applications are much quicker and efficient.


Checking timeouts made more readable

I have several situations where I need to control timeouts in a technical application. Either in a loop or as a simple check. Of course – handling this is _really easy_ , but none of these is looking cute. To clarify, here is some C# (Pseudo) code:               private DateTime girlWentIntoBathroom;     girlWentIntoBathroom = DateTime.Now;          do     {       // do something     } while (girlWentIntoBathroom.AddSeconds(10) > DateTime.Now);      or               if (girlWentIntoBathroom.AddSeconds(10) > DateTime.Now)       MessageBox.Show("Wait a little longer");     else       MessageBox.Show("Knock louder");      Now I was inspired by something a saw in Ruby on StackOverflow: Now I’m wondering if this construct can be made more readable using extension methods. My goal is something that can be read like > “If girlWentIntoBathroom is more than 10 seconds ago” **1st attempt**               if (girlWentIntoBathroom > (10).Seconds().Ago())       MessageBox.Show("Wait a little longer");     else       MessageBox.Show("Knock louder");      So I wrote an extension for integer that converts the integer into a TimeSpan               public static TimeSpan Seconds(this int amount)     {       return new TimeSpan(0, 0, amount);     }      After that, I wrote an extension for TimeSpan like this:               public static DateTime Ago(this TimeSpan diff)     {       return DateTime.Now.Add(-diff);     }      This works fine so far, but has a great disadvantage. **The logic is inverted!** Since girlWentIntoBathroom is a timestamp in the past, the right side of the equation needs to count backwards: impossible. Just inverting the equation is no solution, because it will invert the read sentence as well. **2nd attempt**   So I tried something new:               if (girlWentIntoBathroom.IsMoreThan(10).SecondsAgo())       MessageBox.Show("Knock louder");     else       MessageBox.Show("Wait a little longer");      IsMoreThan() needs to transport the past timestamp as well as the span for the extension SecondsAgo(). It could be:               public static DateWithIntegerSpan IsMoreThan(this DateTime baseTime, int span)     {       return new DateWithIntegerSpan() { Date = baseTime, Span = span };     }      Where DateWithIntegerSpan is simply:               public class DateWithIntegerSpan     {       public DateTime Date {get; set;}       public int Span { get; set; }     }      And SecondsAgo() is               public static bool SecondsAgo(this DateWithIntegerSpan dateAndSpan)     {       return dateAndSpan.Date.Add(new TimeSpan(0, 0, dateAndSpan.Span)) < DateTime.Now;     }      Using this approach, the English sentence matches the expected behavior. But the disadvantage is, that I need a helping class (DateWithIntegerSpan). Has anyone an idea to make checking timeouts look more cute and closer to a readable sentence? Am I a little too insane thinking about something minor like this?


Can a strategy be implemented as a nested member class?

Is it okay to have a strategy implemented as a non-static inner class or is it considered a bad practice?               public class SomeClass{            private final Strategy strategy;            public void someMethod(){        this.strategy = new Strategy();        //call some strategy method to run an algorithm         strategy.doSomeWork();       }            private class Strategy(){         private doWork(){};       }     }      **P.S** : `Strategy` does need access to the state of the `SomeClass`. So can't make it static.Another option is to have `Strategy` as an _interface_ and then inject a concrete `Strategy` inside the `SomeClass` constructor but at the moment I do not see this particular `Strategy` interface being used by another class. So thought of the first approach. However,if I do take the first approach how would I have my class work seamlessly with multiple strategies?


Should methods always be closed for modification?

Say I have a method called 'functionA' that is called by a service and carries out a single piece of functionality, it is easy to unit test as it is does one thing only. If a few months later an new requirement comes in that requires another method 'functionB' to be called directly after 'functionA' has executed. What is the better approach to add functionB to my code. to call 'functionB' at the end of the 'functionA' method:               functionA() {         //do something..              functionB();     }          functionB() {         //do somehting...     }      Problem with this is that when I unit test functionA it will call functionB that will also be part of the test (so now it is more of an integration test). Or refactor the code with a new method 'functionX' that calls 'functionA' and then 'functionB'?               functionX() {         functionA();         functionB();     }          functionA() {         //do something..        }          functionB() {         //do somehting...     }      I can unit test both methods individually but now I have changed the API. I see the first approach so much in legacy code, is it best practice to always make methods closed for modification or are there examples when it is OK to use the first approach?


Tracking scientific error when working with floating-point numbers

**Background** I hate the way .Net/IEEE-754 handles equality of floating-point numbers (FPNs) (i.e. double, float). It requires the programmer to be prescient with respect to the yet-to-be-determined history of the number, as the programmer must choose a 'reasonable' value of epsilon where frequently no such value can be determined (as the programmer cannot determine ahead of time how many operations, hence roundings, the number will be subject to). I would like to create a 'better' FPN within .Net. At creation, one would set its initial scientific error (or accept a default; the default being the minimum). When one performed operations on the FPN, those operations would update the scientific error (to account for the effect of rounding). When testing the equality of two FPNs, one could determine if their ranges overlapped (and even the probability that they are the same number). **Question** The code itself is simple, my questions are:   * How do operations (+ - * / to start with) affect the scientific error of a FPN? Are there formulae for determining this scientific error?   * I understand that an added complication is the uneven distribution of FPNs. This can obviously be accounted for by scaling the error in proportion to the inherent scientific error of the result; but is there a formula for determining the inherent scientific error present in a given FPN?


What's the difference between simulation and emulation

I frequently see _Simulation_ and _Emulation_ in computer science. These two terms seem synonymous. Is there any difference between _Simulation_ and _Emulation_?


How to fix a project with basically no structure?

I've been working on a software project mostly solo for over 5 years. It was a mess to begin with (I am the third or fourth developer to be working on it), and although it's less of a mess now it is still incredibly disorganized. The rate of progress in getting it under control is glacial and I'm starting to feel despondent over the state that it's in. How do I really start fixing it? Project specifics: It is a sales program written almost entirely in Visual Basic Classic (VB6) with a MySQL back end and a reporting engine written in C#. The C# reporting module is a joy to work on, it was only just written in the past couple years and before that all reports were done in Crystal Reports 9 (yes, we still have some reports that rely on it). The actual program itself, however, is a complete disaster. There are not quite 90k LOC total, and about 10k lines of comments (mostly not documentation, but old code that's been commented out). 158 form files, and 80 module files. I have no idea how many of those are actually used, because some features of the program are simply deprecated and (uh, sometimes) noted as such without having the associated code removed from the program. I would guess that only 50% of the code is in actual productive use. I am afraid of touching a lot of the code just because I am not sure if I'm breaking something that one obscure client relies on, it's happened on more occasions than I can count. It's like there are landmines strewn throughout the code. There is not really any structure to the project. It is not object oriented except in the few places I have had the patience to reform so far. If you need to get data on a form, you instantiate a database object, declare your query right there in the function, execute it and do what you will with the dataset. When I began working on the project there was no source control in use. I tried to encourage the other people I was working on to use it, but I was the new guy and my attempts to get people to use subversion all but failed. The company's lead developer finally caught a mercurial bug in the last couple years and he's made sure that all developers do use source control on all projects now, so at least that's some progress. I think if I was able to work on reforming the project full time I would be able to make decent progress and maybe even have an estimate for how long it would take me to fully makeover the project, but it is in active use and I am constantly being asked to put out fires, fix bugs, add features, etc. etc. So how do I start to really fix this project? Try to tool VB6 with another language? Try and rewrite the program in my spare time? Or is this completely hopeless? **Update** After this post I went back to the project with renewed zeal, but fell back into hopelessness within a few months after seeing such a slow rate of progress. I then repeated this cycle 2 or 3 more times over the next year or so. I have since moved on to a different job. Although after so many years of vb6, and only peripheral experience with other technologies the search was difficult and I faced many rejections along the way (around a dozen interviews over the course of a year). My advice to others in this situation is to consider leaving for this factor alone. Consider the damage you can do to your career by staying in a dead end position such as this.


Is it bad etiquette to ask a potential employer how they score on the Joel Test?

Developer interviews are different than most other places, because not only do you worry about the people you work with, benefits, job description, etc., you also have EXTRA to worry about after getting the job. Writing two application with exact requirements can be vastly different if you're working in a loud vs quiet environment, using VS2003/.NET 2.0 vs VS210/.NET 4.0., using SVN vs VSS. Is it ok to give the potential employer the straight-up Joel Test? I try to ask as many questions to get the type of environment I will be working in, which is extremely important from my perspective, but what's the best way to cut to the chase and just ask the tough questions (like they ask you during the same interview). NOTE: By the "Joel Test" I mean a specific list of things that are deal breakers that are important to you (not necessarily Joel), but you may not have time to get out using the traditional casual "conversational" way of asking them, so you decide to either email or schedule another meeting, or ask other people, etc.


Long vs short scripts? Big vs small scripts?

As a programmer, I have always wondered whether it is preferable to write **(a)** short modular functions that are each stored in their own script (i.e., file) or **(b)** long comprehensive scripts that contain all of their relevant functions. For example, if I code a data analysis stream that includes a variety of operations performed on the same data (e.g., data cleaning, feature selection, clustering, supervised learning, etc.), should I write a single file even if it runs for hundreds of lines? I have heard many opinions on the matter and I wonder what this community thinks. I understand that the answer may depend on the type of project, but, if this is the case, then it would be great to hear your thoughts on what factors one should consider in deciding between options **(a)** and **(b)**. I am currently coding in Python and I've wondered whether Python programmers have a preference to multiple functions in the same file or one file per function, but I imagine that this question is broader and applies to all programming languages.


Is there a canonical book on Agile?

As a solo developer, I think I'm using an Agile-like process, but I'd like to compare what I'm doing to real Agile and see if I can improve my own process. Is there a book out there that's the de-facto standard for describing best practices, methodologies, and other helpful information on Agile? What about that book makes it special?


Learning Agile & Scrum

> **Possible Duplicate:**   >  Is there a canonical book on Agile? I'm looking for a good book on learning Agile and Scrum for web application development. Can anyone suggest a good resource that guides one from the group up? We want to start implementing this into our business and web application development cycles.


Is there a book I can read to get up to speed with Agile development?

> **Possible Duplicate:**   >  Is there a canonical book on Agile? I’ve read the Manifesto for Agile Software Development, and the twelve principles behind it. What else can I read to get a reasonably comprehensive overview of what people (and by people, I mean people writing job adverts) specifically mean when they talk about Agile Software Development? I get the sense that there are a few people using the term pretty loosely, so I’d like to have some more concrete ideas in my head to aid discussion (and, ultimately, actually help make software).


What is the recommended way to separate current development from maintenance development in version control software?

I have some software application managed using Git. I just released a new version 2.x which I plan to maintain on the long term (bug fixes mostly). In the meantime, I would like to start working on version 3.x. What is the recommended way to manage this? Should I create a branch for version 2.x and have the 3.x development on the master? or the other way?


Using vim: Is there a way to automatically un-tab everything in your source file by using a command?

And then to automatically re-indent after that? (I tried copying code from one terminal screen to the other, but the tabulation got all messed up) I didn't know what to call this functionality, so it was hard for me to find it on google (which generally returned things related to how to set tab size, which wasn't what I was looking for unfortunately.) Thanks


Is there a general rule for when you should use 'make clean' instead of just 'make'?

I am writing a multiple-filed program right now, and apparently running only 'make' (as one would intuitively think needs to be done in most situations) for some reason causes my program to fail. I guess I can provide more detail of the problem, but the important thing is that it does run when using 'make clean'. So I was wondering if anyone knew the general rule of thumb for running 'make clean' instead of just 'make'


Count a row VS Save the Row count after each update

I want to know whether saving row count in a table is better than counting it each time of the proccess. Quick Example : A visitor goes to Group Clan, the page displays clan information and Members who have joined the group,Should the page look for all the users who joined the clan and count them, or just display the number of members already saved in table ? I think the first one is not possible to get manipulated with but IT MIGHT cost performance Your Ideas ?


Graphics Library

I would like to know about high end graphics library in C and Fortran. I have heard about OpenGl and Direct X. But I find that OpenGL is practically low end library. Is Direct X is in C too? I really need to have a very high end graphical library in C. Thanks in advance. Regards, hena


How long would it take for someone completely new to programming to get enough knowledge to make it to the job market as a junior programmer?(C#)

I just want to know how long would it take me to become proficient enough (in let's say C#) in order to be able to get into the job market as a junior/entry level programmer. I have read all those articles and discussions about "how long would it take" but the answers always seem to be like "...it will take you two weeks to know the syntax, but it will take you 10 years to become a good programmer..." or "...the same time that it would take you to learn German...". Nevertheless, there is a continuum between the two extremes. I know that I'm not going to produce great code in a few months, I just want to know how long would it take me to write code "good enough" to be considered "hirable". I know that the answer depends on many factors, so I will be as specific as possible describing my situation: -I'm in my late 20's. -Haven't made it in programming beyond creating objects in C#. -Have some friends (5) who studied CS and are working as programmers. A couple of them are able to help me through my learning process though no full time. -Very underdeveloped mathematics skills. Never made it beyond very basic algebra, not because I didn't understand it, but rather because I studied something unrelated to mathematics. -Fast learner. I made it through a Basic Algebra book in less than two weeks and scored A in a test after more than 7 years without even opening an arithmetic book. I don't know the multiplication table, but I get by because I know in principle what multiplication is. If you ask me how much is 8*8 my brain goes like: it is 80-(2*8)... yeah, I'm at that level... -My IQ is consistently over 135 in standard tests.(to maple_shaft: yes, standardized tests, like the ones to complete for MENSA; anyway I'm not that proud about it at all since EQ is where the real deal is. I just brought it up because I know that in the field of programming it is a good trait to have.) -Very high capacity of abstraction and generalization. -I won't be able to study full time. I could study for an average of 1.5hrs on work days and 6hrs on days off. If you read this far maybe you would also be so kind to respond as concisely as possible to these two questions: A. Is it realistic for someone with no college education to make it to high levels in the industry? B. How would you describe the relation between the daily work of an **_application developer in an average project of an average company_** and **_mathematics_** (mainly: calculus, trigonometry, etc)? Physics <\---> Mathematics (Strong Correlation. All great physicists are great mathematicians... there is no way around it). Architecture <\---> Civil Engineering (Somehow Correlated, but you can earn your bread with only some general concepts of it). General Mechanic <\---> Engineering (I'm just going to use the tools that you created to fix what you created, but how I do it is another thing). Thank you very much in advance for your replies. Please, please, no offensive or repetitive answers; I would appreciate serious answers. Thank you for your time.


What are some current opinions on WPF?

We are trying to make a decision about if we should create a program in WPF w/ a WCF server, and I was wondering what the current opinions are of WPF. I was looking around online but most of the arguments I saw for/against WPF were dated a year or two ago, and about WPF3.5. I was wondering if those opinions have changed in the past year or two with the release of WPF4.0. Some notes.... The program we are making is for use by a single-company in a controlled enviornment. With the exception of one or two Vista laptops, most users are on Terminal Servers or WindowsXP. It is not media-heavy and doesn't need a pretty UI (although it won't hurt). It needs to be extensible and allow for easy additions later on. Security and Performance are our key concerns. **EDIT** Primary concern about WPF is Support (MS and community), memory/cpu usage on terminal servers, and finding people to work on the project now and maintain it in the future. Some smaller things of concern are lack of library controls, development time, and learning curve. The primary alternative we were considering is ASP.Net/jQuery.


Is it possible to adopt agile methodologies for outsourced projects?

I've had experience as a developer or team lead on several projects that have been outsourced and have seen less than stellar results in all cases. Most of these projects have employed a waterfall philosophy, with large kickoff meetings, months-long requirements gathering phases, plenty of conference calls, and innumerable emails. One thing that's always frustrated me is an absence of early access to the code. The contracts are setup in a way where the offshore team is responsible for meeting functional requirements, which is what the executives are concerned with. This means, however, that architecture decisions, implementation details, pattern usage, and things that concern other developers are so deeply settled by the time the product is delivered that we're unable to offer feedback or request any real changes. Has anybody here managed an offshore project that hasn't experienced these problems? Specifically, I'm wondering if there's any way to structure the contracts to compel offshore teams to work in shorter cycles and re-factor or re-design based on feedback from on-shore developers. I haven't had too much experience with agile methodologies (I agree with the general principles, but work in a conservative shop that has it's entrenched methodologies), but wonder whether these could somehow be adapted to help manage offshore development. Overall, I'm looking to minimize the surprises and maintenance nightmares that inevitably arise when a development team is left to work in isolation for months at a time.


Open Source Project: Company to register copyright

I'm releasing an open source project. I want to make it as inclusive as possible for any community that might embrace it. Specifically, I don't want the code copyrighted in my name when an entire community might work on it; that approach seems self-centred and alienating. My immediate thought to avoid this issue is to assign the copyright to a company rather than myself. How do I do this? Do I have to register a corporation? Can I just give the name of a group and call that a company? What legal hurdles are there? I honestly have no idea when it comes to this sort of thing. (I'm in Canada and want to use the GPL, if that helps.)


C++ track or Java track in college?

I'm starting some CS classes at a community college and they have two tracks. Either you take three courses in C++ or three courses in Java. Both cover the same fundamental material e.g. data structures, algorithms etc. Which would you recommend considering that I know python and may be consider doing a masters in CS some time down the road....my undergrad degree is in something else. And advice would be appreciated.


Where can I find inspiration for a good user interface?

I've got a mental block as far as desigining the main screen interface for a desktop application that I'm currently upgrading. When I first developed this program the screen resolution was 640 X 480. Today there are multiple screen resolutions out there. Where can I find ideas for a good main screen layout for a desktop application?


What are functional-programming ways of implementing Conway's Game of Life

I recently implemented for fun Conway's Game of Life in Javascript (actually coffeescript but same thing). Since javascript can be used as a functional language I was trying to stay to that end of the spectrum. I was not happy with my results. I am a fairly good OO programmer and my solution smacked of same-old-same-old. So long question short: what is the (pseudocode) functional style of doing it? Here is Pseudocode for my attempt:               class Node       update: (board) ->         get number_of_alive_neighbors from board         get this_is_alive from board         if this_is_alive and number_of_alive_neighbors < 2 then die         if this_is_alive and number_of_alive_neighbors > 3 then die         if not this_is_alive and number_of_alive_neighbors == 3 then alive          class NodeLocations       at: (x, y) -> return node value at x,y       of: (node) -> return x,y of node          class Board       getNeighbors: (node) ->         use node_locations to check 8 neighbors         around node and return count          nodes = for 1..100 new Node     state = new NodeState(nodes)     locations = new NodeLocations(nodes)     board = new Board(locations, state)          executeRound:       state = clone state       accumulated_changes = for n in nodes n.update(board)       apply accumulated_changes to state       board = new Board(locations, state)


Showing real time data using WCF call (silverlight)

Currently I have a WCF method which brings back all the data from the db and binds it to a grid, but I would like to call this method regularly to get the updated data back each time, to show the user real time data, what is the best way to go about this? Thanks in advance.


What are some good, simple examples for queues?

I'm teaching **CS2** (`Java and data structures`), and am having some difficulty coming up with good examples to use when teaching queues. The two major applications I use them for are `multithreaded` message passing (but MT programming is out of scope for the course), and `BFS-style algorithms` (and I won't be covering graphs until later in the term). I also want to avoid contrived examples. Most things that I think of, if I were actually going to solve them in a single-threaded fashion I would just use a list rather than a queue. I tend to only use queues when processing and discovery are interleaved (e.g. search), or in other special cases like length-limited buffers (e.g. maintaining last _N_ items). To the extent practical, I am trying to teach my students good ways to actually do things in real programs, not just toys to show off a feature. Any suggestions of good, simple algorithms or applications of queues that I can use as examples but that require a minimum of other prior knowledge?


is it Ok to have a time for familialization of technology and tools once a project starts

I have been in several software projects but not as a leader. In all the projects we all knew the tools and languages etc. before the project started. I am wondering if it is ok or is it a good practice to have a time for developers to familiarize themselves with tools and technologies after project kicks off (eg. After requirements specification)?


Is there a way to 'package' up my Visual Studio installation so I can easily deploy it on other machines?

I have a number of machines running VS, and each has a slightly different config - display styles, installed plugins, source control extensions, project templates, service packs and so on. Not only is this annoying when moving from machine to machine but also I have no real way of wiping an install and starting again. I know I _could_ use a virtual machine but I really don't like the added overhead of VMs. What I'm looking for is a way of rolling up a Visual Studio install, with all the extra plugins into an installable package so I can just define it once and deploy it everywhere. Is this possible?


Should the provider of an interface also provide a mock implementation for testing?

We wasted a lot of time on our last integration test on a bug that I think should have been found in unit testing. The problem was that an interface / service we called behaved different than we expected and the unit test didn't find this problem because we mocked that interface for the unit test and our mock was of course based on our mistaken interpretation of what the interface would do. Now I could be a bit angry at our dear coworker who provided the interface, because their description / specification of it (a terse JavaDoc comment) was ambiguous and contributed to our misunderstanding. On the other hand, I thought that the problem could have been avoided if those same coworkers had provided a mock implementation of their interface which we could call in our unit testing. Then the bug would have shown up much earlier and a lot of cursing could have been avoided. Now, what's the best practice in organizing the creation of mock objects among teams who provide and use shared interfaces? What are your experiences?


Move from JSON to Protobuf. Is it worth it?

We have REST webservices that can serve XML or JSON (WCF). I'm toying with idea of implementing Protobufs. Why? PROS   1. Less load on servers.   2. Smaller message size - less traffic.   3. It is easier to switch now than later. CONS   1. Need to be implemented   2. Going to be harder to troubleshoot/sniff messages for debugging.    3. I can enable GZip on server and JSON will consume as much traffic What is your suggestion and/or experience on this?


Effective Code Review Process for software maintenance

I have been working with a code being maintained for years. We're using clear- case as version control. To submit the code for review and get the code count (for project metrics) are usually painful. What's the best way to conduct code review for maintenance software? How effective we can share the code for peer review (I understand it's tightly coupled with the version controls we're using). Any known standards or best practices? How can I get metrics like code count etc.?


How to restrict viral file sharing

So I have a website I would like to make that would essentially be selling files. For the sake of discussion let's say that these files are like the raw text of a book. If somebody buys a file from my site, there really isn't anything preventing them from sharing that unlimited amounts of times with their neighbor or whatever. I know that the music industry has suffered from this type of thing for years, so there may not be an easy solution, but what could I do to try and limit the use of that text file to just one person? Is there any type of encryption or password verification that would help me solve this problem? Or do I just have to cope with the fact that it's 2010 and nobody will pay for anything they can find for free on the web?


I need an approach to the problem of preventing inserting duplicate records into the database

A webservice that I call returns a list of data. The data from the webservice is updated periodically, so a call to the webservice done in one hour could return the same data as a call done in an hour. Also, the data is returned based on a start and end date. We have multiple users that can run the webservice search, and duplicate data is most likely to be returned (especially for historical data). However I don't want to insert this duplicate data in the database. I've created a db table in which the data is stored (most important columns are)               Id int autoincrement PK       Date date not null        --The date to which the data set belongs.       LastUpdate date not null  --The date the data set was last updated.       UserName varchar(50)      --The name of the user doing the search.      I use sql server 2008 express with c# 4.0 and visual studio 2010. Entity Framework is used as the ORM. If stored procedures could be avoided in the proposed solution, then that will be a plus. Another way of looking interpreting what I'm asking a solution for is as follows: I have a million unique records in my table. A user does a new search. The search results from the user contains around 300k records of the data that is already in the db. An efficient solution to finding and inserting only the unique records is needed. A combination of the `Date`, `LastUpdate` and `UserName` makes a record unique.


Java Developers Coding CSS/HTML/JQuery?

Are Java Developers better equipped to write front end stuff? Should Java Developers be coding HTML, CSS & JavaScript? What do people follow in your companies? What are some suggestions if they have too?


Peer review for UI Development

I am the only front-end developer in a team composed for 3 .Net devs, 1 QA and 1 PM. Although we have another team from another office halfway around the world, to whom would i do code review with?   * me + front end developer from another office.   * me + one of the .net developers in local office.   * other choices/course of action to take? this in assumption that:   * .net developers have minimal experience in css and table-based layouts and as well as javascript;   * me and the ui dev's time difference is that im 8 hours ahead of him.   * sometimes most front-end and backend's mind doesnt jive.


Mercurial branch or rebase?

After using mercurial daily for over a year, we are about to find a better workflow for our DVCS. Inspired by a successful Git branching model we are about to move away from our "push daily work into master repo and fork off release branches at regular intervals" workflow into "work on separate feature branches and merge finished features back into master". Anyway, the problem I have had with branching and mergeing in mercurial (branch using clone) is the actual merge process. I have no problem with merges generating additional changesets, the problem I have is that it usually generates huge changesets that contains more changes than the original changeset+merges, The merge changeset also contains changesets from other heads as well. So I have recently realised that when we do pull from master repo,then update/merge and finally push, we create these unnecesary large changesets. What we should do is rebase instead of pull, update/merge. Now rebase was originally an extension to mercurial, it is still an extension but is nowadays shipped together with the mercurial distribution. When following other threads, especially those comparing git with mercurial, it seems like one of the largest difference between the two is the fact that git does not support branches, but has native support for rebase. Mercurial has no native suppport for rebase but support branches. So my question then, if we should adopt to a more flexible workflow using feature branches, we must have a solid branch/merge workflow that does not cause havoc in the master branch. The master branch should be **peach** containing only changesets containing a single feature without any extra changesets for any merge operations carried out. Now can that be done in mercurial without rebase support? As a separate issue, I would like some input on how to aggregate multiple changesets in a feature branch into one single changeset when pushing into the main branch. I have read A Guide to Branching in Mercurial but it never mentions the pros or cons regarding ease of mergeing, or more specifically, how the results of the merge is commited into the master branch.


Why decouple view and controller (web)?

Why can't we put them in the same page, like each action paired up with its view? Not using code island, but controller code at top then view code at bottom? What are the problems with this approach? By MVC, I am referring to frameworks such as ASP.NET MVC and Ruby on Rails, and I am under the impression that the V and C are actually the UI layer.


How can I improve my error checking and handling?

Lately I have been struggling to understand what the right amount of checking is and what the proper methods are. I have a few questions regarding this: What is the proper way to check for errors (bad input, bad states, etc)? Is it better to explicitly check for errors, or use functions like asserts which can be optimized out of your final code? I feel like explicitly checking clutters a program with a lot of extra code which shouldn't be executed in most situations anyway-- and not to mention most errors end up with an abort/exit failure. Why clutter a function with explicit checks just to abort? I have looked for asserts versus explicit checking of errors and found little to truly explain when to do either. Most say 'use asserts to check for logic errors and use explicit checks to check for other failures.' This doesn't seem to get us very far though. Would we say this is feasible:               Malloc returning null, check explictly     API user inserting odd input for functions, use asserts      Would this make me any better at error checking? What else can I do? I really want to improve and write better, 'professional' code.


iOS Resources/Luminaries?

In the .NET world, I was able to find several industry figures or luminaries' blogs to read or to follow on twitter to learn about features and trends. Moving into the iOS realm, I'm kind of surprised how difficult it has been to find analogous resources. What resources should I be reading/following/osmosing to get better integrated into the iOS community?


Implementing Asynchronous Insert / Update for a web application

I am in the process of implementing a small web application using memcached for caching objects and sql server for database persistence. In all the projects I have done before I have done inserts/updates in the web thread itself. In this project I want to implement asynchronous inserts and updates. I will use memcached http://en.wikipedia.org/wiki/Memcached to capture changes and an external service (windows service) to persist the changes in db. I understand premature performance tuning is evil but this is just a test project to learn memcached. Has anybody done this before. What are the disadvantages of using this ?


Do you start writing GUI class first or reverse?

I want to write my first Java program, for example Phonebook, and I wonder what to do first. My question is should I write GUI classes first or util classes first? I am database developer and want to know best practice in building program.


Does Java have automatic memory management?

I have started learning about C# and I come to what is called 'Automatic memory management' or 'Garbage collectors' and I'm wondering if Java contains something like this as well? and if it does, does it do that as effective as C# when it comes to windows desktop application and web applications?


Char and unsigned char

Where is unsigned char used in C ( please tell about some real-world examples )? Why would we need both char and unsigned char? Char ranges from -127 to 128 ( 8-bit integer ) Unsigned Char ranges from 0 to 255 ( 8-bit integer ) If the purpose is to store ASCII, why would we need both? Another question. Consider this:               char a = 127;     unsigned char b = 255;      When I print it using std::cout. It gives me different characters. Can you explain why? ( I'm using Microsoft vs11 compiler )


For a web-application, should I programmatically create the database tables or provide a schema file and instructions?

The few LAMP web applications I have installed require me to create the necessary database tables myself, with a schema file, instead of doing it automatically with a script or setup page. Is this a normal and accepted practice? In my own hobby projects I find it much easier and hassle free to just create the tables in code. As the programmer I can make sure it's done correctly, and as the user I don't care - just make it work! However, I have very limited knowledge and experience in the world of web applications and database management, so I don't know the pros and cons of either approach. If I were to make my LAMP web applications available for download and installation by others, should I continue to do table creation in code or follow the example of the other applications I have installed, and just provide a schema file with installation instructions?


Custom graph comparison?

I'm trying to compare two graphs using hash value ( i.e, at the time of comparison, try to avoid traversing the graph ) Is there a way to make a function such that the hash values compared can also lead to determining at which height the graphs differ? The comparisons between two graphs are to be made by comparing children at a certain level. One way to compare the graphs is have a final hash value for the root node and compare them, but that wouldn't directly reflect at which level the graphs differ, since their immediate children might be the same ( or any other case ).


How do I become a real expert?

Being a freelancer, I don't have a luxury of corporate training and a circle of professional employees. Even though I have been programming for the last few years and developed professional projects, but at times I find myself in a place where there is no help. Not even StackOverflow and other related sites can help. Take for instance, Crystal Reports. I am using it for the last few years in my projects. I learned it all by myself, but still I struggle with many issues. I am still not able to improve the performance of reports, not able to design fast and still I am able to use only 30% of the Crystal Report's power. I reside in a city where I can't find freelancers like New York or San Francisco, to hire them for learning. A handful of experts available online are not in my budget. I face the same problem with C# and other technologies. At StackOverflow, you can't keep an expert engaged. After two-or-three comments, he will loose focus of your question and jump to a new question out there. Few people suggested me to look into code written by others to learn fast. But again, how to get my queries answered. There are some aspects where you just can't write it down. You need personal assistance. I think freelancers in US have better choices and flexibility as compared to other countries.


Is a merging strategy like Git Flow really an anti-pattern?

My company is using Git, and is using a peculiar branching scheme - work is done in master, and branches are reserved for releases. This works fine, so long as all of the work done in an iteration makes it into the branch, but if a critical production issue comes up, we have to ensure that the work somehow makes it into both branches. Lately, we've been having some "fun" with those branches. It's been an administrative headache, ensuring that all of the work makes it into every branch, and some bugs which have been fixed on one branch don't make it into master until someone points it out, which is concerning. I came across Git Flow a while back, and I feel that it would be a solution to our problem - code not percolating all the way to the release, or all the way back down. The only catch is that my lead stated that this sort of development was an anti-pattern - developing furiously for two weeks, then spending three to resolve the merge conflicts. I'm not entirely sure I agree, and since I brought it up, work has resumed like normal. Only recently have we had some major pain points with this. I'd like to know - why would this sort of development scheme be seen as an anti-pattern? _Is_ it really an anti-pattern?


TekPub Feedback

Following on from a previous thread that had a link to TekPub, I have just had a quick look and I think it looks pretty impressive. Are any of you guys subscribers and if so would you recommend it? I am mainly interested in general software design and, as a language, C# and it's features. Is there much content posted on a regular basis along these lines to warrant the outlay? Thanks.


Does "don't reinvent the wheel" ignore the limits of human memory?

One thing working in Haskell and F# has taught me is that someone in a university smarter than me has probably already found an abstraction for what I'm doing. Likewise in C# and object-oriented programming, there's probably a library for "it", whatever it is that I'm doing. There's such an emphasis on reusing abstractions in programming that I often feel a dilemma between: 1) just coding something short and dirty myself or 2) spending the same time to find someone else's more robust library/solution and just using that. Like recently one of the coders here wrote up a (de)serializer for CSV files, and I couldn't help but think that something like that is probably very easy to find online, if it doesn't already come with the .NET standard APIs. I don't blame him though, several times working in .NET I've patched together a solution based on what I know, only to realize that there was some method call or object or something _,often in the same library,_ that did what I wanted and I just didn't know about it. Is this just a sign of inexperience, or is there always an element of trade- off between writing new and reusing old? What I hate the most is when I run across a solution that I already knew about and forgot. I feel like one person just isn't capable of digesting the sheer quantities of code that comes prepackaged with most languages these days.


What should I do with too much interfaces needed for a dialog

Let me start by doing a small summary of the changes we did in our code in the last year. We have a software (VERY big) that is used to visualize multiples underground networks, enter data in the entities in the network and create simulation in this network. In the 20 years of development of this application (in MFC C++), multiple people have worked on it, lots of patch have been done and it's in constant developpement. Over the year, a monster class has been created. The class is called "CNetwork" and each network is a subclass of it. To illustrate this moment in the code history, the prototype of a typical dialog was this:               public SuperNiceDialog(int nID, CNetwork* pNetwork);      After a course on unit testing, it was obvious for me that we needed to create interface to make everything more testable. Since most of our "functionnality" were in the network,CNetwork was implementing a lot of them and now when we need to call the same dialog, it looks like this:               public SuperNiceDialog(int nID, ITranslateNetwork* pTranslate,                             IUnitManager* pUnitManager,                             ICommonVectorProviderAQ* pCommonVectorProviderAQ,                             INetworkInfo* pNetworkInfo,                             IDatabaseManager* pDatabaseManager,                             ISimulation* pSimulation,                             INetworkAutonumerotation* pNetworkAutonumerotation,                             ISpreadsheetInfoProvider* pChiffrierInfoProvider,                             IPolygonManager* pPolygonManager,                             ISetterValidation* pSetterValidation)      I will not unit test a dialog but a lot of class called inside this dialog could be tested but for most of them, I must passe a lot of interface to get the work done. And I can't juste pass the network because some of the interface are removed from CNetwork to slowly remove functionnality from a single class. So we think about it and one of the ideas that we had was to create a "package" object which could be a simple structure containing pointers to interfaces and getter to get access to these pointers (Like a Facade object). For example My dialog would be called like this               public SuperNiceDialog(int nID, CDialogInterfacePackage* pPackage)      And in the code, I would use it like that               m_pPackage->GetITranslation()->Translate(123456);      Since most of the Dialog needs the same interface, we could put 10 interfaces in it and just pass this to the dialog. We could create "interface package" for various module for example for simulation, spreadsheet, etc.. One part of me think it's a good idea but another part is telling me that I will be slowly creating a new "CNetwork" in some kind of way... Any idea about this problem of having too much interfaces? Is this a good approach? Thanks


Is there a setting to enable anti forgery globally in ASP.NET MVC, and if not, why?

The tutorials I've read tell you to use [ValidateAntiForgeryToken] attributes and `<%= Html.AntiForgeryToken() %>` in your code. I was wondering why this isn't a built-in automatic setting or at least a global toggle in the web.config. Perhaps it is, and I haven't realised, but I am doing it by hand and I can't help but wonder if there is a good reason for not handling it automatically behind the scenes. Any ideas?


Representational Equality versus Value Equality

I am coding a system where I have objects which represent a set of resources. These resources are identifiable (they have an ID). There can only be one resource with the same ID, and so multiple objects with the same ID really should have the same values.   My problem is with the **equality** concept in this case. Should it be based on the ID or on the values alone? Is object A = object B because they have the same ID **OR** should object A == object B because their fields are the same. One possibility I was thinking of was to have the ID-based comparison be "equals" and the field-based comparison be "equivalent". Alternatively I could have it so the field-based comparison was "equals" and the ID based comparison was "representSameObject" (or something). Just a pseudo-code example:               class A {        String uuid;        int field1;        double field2;        List<String> listField;             @Override        public boolean equals(Object other) {            return uuid.equals(other.uuid);        }             public boolean equivalent( other ) {            if (this == other) {                return true;            }            if (null == other) {                return false;            }            if (other.getClass() != this.getClass()) {                return false;            }                 A rhs = (A) other;            return new EqualsBuilder().append(field1, rhs.field1).append(field2, rhs.field2).append(listField, other.listField).isEquals();        }     }      In the end this may come down to a personal preference coupled with system requirements, but I am very interested to learn how others have approached this concept. It has been annoying the heck our of me since I started on this project! If it makes a difference I am programming at the minute in Java. I don't mind where the answer comes from though as this is obviously a conceptual issue.


PHP4 constructor does not work with namespaces

Here's a scenario: whenever accessing class using namespaces in php, it doesn't launch the standard constructor, but only the 'magic' method. What's wrong here and what can be fixed? **hierarchy**                test.php      a      +-foo.php      **test.php**               <?php          spl_autoload_register();     spl_autoload_extensions(".php");          new a\Foo();      **foo.php**               namespace a;          class Foo{      /* //if this ges added the __construct() is called         public function __construct(){             echo "called magic constructor";         }       */              public function Foo(){              echo "called standard constructor";          }     }      Launching test.php doesn't lounches the Foo constructor method, but only the __construct method if present.


Data Structure for Small Number of Agents in a Relatively Big 2D World

I'm working on a project where we will implement a kind of world simulation where there is a square 2D world. Agents live on this world and make decisions like moving or replicating themselves based on their neighbor cells(world=grid) and some extra parameters(which are not based on the state of the world). I'm looking for a data structure to implement such a project. My concerns are : I will implement this 3 times: sequential, using OpenMP, using MPI. So if I can use the same structure that will be quite good. The first thing comes up is keeping a 2D array for the world and storing agent references in it. And simulate the world for each time slice by checking every cell in each iteration and further processing if an agents is found in the cell. The downside is what if I have 1000x1000 world and only 5 agents in it. It will be an overkill for both sequential and parallel versions to check each cell and look for possible agents in them. I can use quadtree and store agents in it, but then how can I get the information about neighbor cells then? Please let me know if I should elaborate more.


Use of Service Bus in a Pub-Sub Engine

In one of our projects, we've built a Publisher - Subscriber Engine on Oracle Service Bus. The functionality being a series of events are published and subscribers (JMS queues) receive these whenever a new event is published. We are facing some technical issues now, performance-wise and hence an architectural review is underway. Now for my questions: Architecturally the ESB has to publish events into a DB and read from the DB which users wish to be notified, then push the event onto their respective queues. There is a high amount of DB interaction and the question is **whether ESB should be having such high amount of interaction with the DB in the first place**? Or should there have been some alternate component responsible for doing this. Alternately **is there any non-DB approach in which we can store the events and subscribers**? Where else can this application data be held within the ESB context?


Can dyslexics be good at programming?

I am a big picture thinker (visual spatial) and enjoy abstract maths. However I struggle with sequential tasks and am struggling with programming. My bad working memory isn't helping either. I heard that good picture thinkers are good at programming in general. I just cannot figure out how to start writing a code etc. I am extremely frustrated. Have you seen any visual spatial person who are bad at programming? Or is it just me? I feel very devastated and feel like I don't fit in anywhere. Any tips on how I can improve? Or does my brain just not work in a logical way? My brain is always jumbled up. If you are a programmer and are dyslexic: What are your weaknesses caused by dyslexia? Are you good at sequential tasks?


What is a proper term to describe a server running source control, bug tracking and CI tools?

I'm looking for a 'term' that describes holistically the set of various software development tools/services that most developers use on a day to day basis. While each tool by itself has a specific purpose and can be described, is there a plural term when they are grouped together and running as a holistic service. If a person said a server was a production test box, I'd expect it to be running the application that company are writing. If a person said box A is the office ware server, I'd know to expect email/communication related services.


C++11 includes std::stoi, why not std::itos?

I noticed to my glee that C++11 has a std stoX family of functions for easily unpacking ints/floats/longs whatever from strings. I'm surprised however, that the opposite isn't implemented. Why didn't the standards committee include a std::itos family of functions for going from ints/floats/whatever to strings?


Rich domain model and container services

I have a long experience in programming Java EE projects, but as I noticed most of the job I have done was with `Transaction Script` (anti)pattern. So I want to learn using a rich domain model, but then there is a question, shall Domain Object be depended on container/system services (such a persistence, mail, ...)? I have read this article and I don't agree with it at all!   * How services are initialized and injected into domain entities?   * What about single responsibility paradigm?   * And isn't it against reusablity? I also read Applying UML and Patterns fantastic book, but I don't know why didn't author describe the how shall responsibilities be assigned to entities after defining data access layer (in chapter 38). So what is the best practice about having rich domain model, and do not having dependency on container/system services! * * * An example, consider following scenario in a software:   * There are agents (which work with the system)   * Our agents' business is selling insurance policies.   * Each insurance policy type has a special type of pre-printed card which is given to agents, and agents give them to insureds.   * We need to track each agent's number of available cards.   * So there is a use case, which records how many cards of each type is given to each agent.   * There is a use case, for recording agent's number of damaged unused cards of each type.   * And the cards are used as the agent sells insurance policies. I believe Rich Domain Model suggests that I shall have a method as following in agent class:               class Agent {         int computeRemainigCards(CardType cardType) {}     }      But then Agent shall depend on 3 DAO classes for just one responsibility:   * One for calculating SUM of count of each card type given to an agent.   * One for calculating count of used cards (by selling insurance policies).   * One for calculating SUM of damaged unsold cards. I believe that will make domain entities a mess. So what is the good practice?


Is there a purely SQL alternate to looping?

Historically, I probably would have written a script (php or something) to loop through all spreadsheet rows and perform some calculations. I'm looking for a pure SQL solution on the presumption that SQL has better options than loops. How should I approach this problem while using a pure SQL approach? * * * **DATA OVERVIEW:**   We have a list (currently in a spreadsheet) of items for which we want to check trending.   Let's pretend that that spreadsheet contains these three items; 111111, 222222, and 888888. In the DB, we have a table of vendors' inventory snapshots. Here's a simplified example:   (see the fiddle here).               CREATE TABLE inventory_snapshots         ([id] int, [vendor_id] int, [item] int, [brand] varchar(1), [inventory_version] int, [quantity] int);          INSERT INTO inventory_snapshots         ([id], [vendor_id], [item], [brand], [inventory_version], [quantity])     VALUES         (1, 111, 111111, 'A', 5, 45),         (2, 111, 111111, 'B', 5, 43),         (3, 111, 222222, 'X', 5, 12),         (4, 222, 111111, 'B', 4, 5),         (5, 222, 888888, 'C', 4, 50),         (6, 222, 111111, 'D', 5, 10),         (7, 222, 888888, 'C', 5, 100),         (8, 111, 111111, 'A', 6, 40),         (9, 111, 222222, 'X', 6, 10);      Notice that a vendor can have multiple rows of an item in a given inventory version because of brand differences. **GOAL:**   Our goal is to see the trending over all vendors.   That means comparing a list (currently in spreadsheet form) of items against the DB to retrieve:   * item number   * starting qty (sum of qty's from the MIN version number for each   * vendor, items grouped by vendor_id,inventory_version) total increases (sum of each vendors version-over-version increases in qty) total   * increases (sum of each vendors version-over-version increases in qty)   * ending qty (sum of qty's from the MAX version number for each vendor, items grouped by vendor_id,inventory_version) For another example, see the comment in the fiddle. **SUMMARY:** It sounds like SQL Server _can_ do some looping, but that it's impractical. What's a better way to approach this?


UML class diagram notations: Differences between Association, Aggregation and Composition

I'm confused about some of the notations of UML class diagrams. ![enter image description here](http://i.stack.imgur.com/bfBSY.png) Pretty sure I know what **Association** means. Any relationship between instances of two classes, where an instance of one class needs to know about an instance of the second class in order to perform it's work - is an Association relationship. An Association often means class A has a reference (field) to an instance of class B. However, I'm having trouble understanding what the **Aggregation** and **Composition** arrows mean. Part of my confusion was caused by encountering different definitions of these notations. Two definitions of the **Aggregation** notation: **Definition 1:** An Aggregation notation between two classes is suitable whenever an instance of class A **holds a collection** of instances of class B (e.g. a List, Array, whatever). **Definition 2:** An Aggregation link between two classes is suitable if an instance of class A holds a reference to an instance of class B, **and the B instance is dependent on the lifecycle of the A instance.** Meaning: When the instance of class A get's deleted, so will the instance of class B. The instance of class B is **entirely contained** by the instance of class A, as opposed to the instance of class A simply owning a reference to the instance of class B (which is regular Association). Regarding what the Composition notation means and how it differs from the Aggregation notation, I'm not sure. Please clarify the definitions and help me understand. Concrete examples would be welcome.


Should I use the new C++11 'auto' feature, especially in loops?

What are the pros/cons to using the auto keyword, especially in for loops?               for(std::vector<T>::iterator it = x.begin(); it != x.end(); i++)     {        it->something();     }          for(std::map<T>::iterator it = x.begin(); it != x.end(); i++)     {        it->second->something();     }          for(auto it = x.begin(); it != x.end(); i++)     {        it->??     }      Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use `first` or `second` or just directly access properties of the object, no? This reminds me of the C# debate on whether to use the keyword `var`. The impression I'm getting so far is that in the C++ world people are ready to adopt the `auto` keyword with less of a fight than `var` in the C# world. For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.


how to design a stack without using java library or using list

I have a question how to design a stack without using list or array? This is one question that I want to think about as I want to better understand stack.


Why are parser generators used?

I saw some projects require BISON to generate C++ code. What is the advantage of having BISON/Yacc etc. generate C/C++ code instead of writing it yourself?


Avoiding coupling

> It is also true that a system may become so coupled, where each class is > dependent on other classes that depend on other classes, that it is no > longer possible to make a change in one place without having a ripple effect > and having to make subsequent changes in many places.[1] This is why using > an interface or an abstract class can be valuable in any object-oriented > software project. _Quote from Wikipedia_ ### Starting from scratch I'm starting from scratch with a project that I recently finished because I found the code to be too tightly coupled and hard to refactor, even when using MVC. I will be using MVC on my new project aswell but want to try and avoid the pitfalls this time, hopefully with your help. ### Project summary My issue is that I really wish to keep the Controller as clean as possible, but it seems like I can't do this. The basic idea of the program is that the user picks wordlists which is sent to the game engine. It will pick random words from the lists until there are none left. ### Problem at hand My main problem is that the game will have 'modes', and need to check the input in different ways through a method called `checkWord()`, but exactly where to put this and how to abstract it properly is a challenge to me. I'm new to design patterns, so not sure whether there exist any might fit my problem. ### My own attempt at abstraction Here is what I've gotten so far after hours of 'refactoring' the design plans, and I know it's long, but it's the best I could do to try and give you an overview (Note: As this is the sketch, _anything_ is subject to change, all help and advice is very welcome. Also note the marked coupling points): ### Wordlist               class Wordlist {         // Basic CRUD etc. here!         // Other sample methods:         public function wordlistCount($user_id) {} // Returns count of how many wordlists a user has         public function getAll($user_id) {} // Returns all wordlists of a user     }      ### Word               class Word {         // Basic CRUD etc. here!         // Other sample methods:         public function wordCount($wordlist_id) {} // Returns count of words in a wordlist         public function getAll($wordlist_id) {} // Returns all words from a wordlist         public function getWordInfo($word_id) {} // Returns information about a word     }      # Wordpicker               class Wordpicker {              // The class needs to know which words and wordlists to exclude         protected $_used_words = array();         protected $_used_wordlists = array();              // Wordlists to pick words from         protected $_wordlists = array();              /* Public Methods */         public function setWordlists($wordlists = array()) {}         public function setUsedWords($used_words = array()) {}         public function setUsedWordlists($used_wordlists = array()) {}              public function getRandomWord() {} // COUPLING POINT! Will most likely need to communicate with both the Wordlist and Word classes              /* Protected Methods */         protected function _checkAvailableWordlists() {} // COUPLING POINT! Might need to check if wordlists are deleted etc.         protected function _checkAvailableWords() {} // COUPLING POINT! Method needs to get all words in a wordlist from the Word class          }      ### Game               class Game {              protected $_session_id; // The ID of a game session which gets stored in the database along with game details         protected $_game_info = array();              // Game instantiation         public function __construct($user_id) {             if (! $this->_session_id = $this->_gameExists($user_id)) {                 // New game             } else {                 // Resume game             }         }              // This is the method I tried to make flexible by using abstract classes etc.         // Does it even belong in this class at all?         public function checkWord($answer, $native_word, $translation) {} // This method checks the answer against the native word / translation word, depending on game mode              public function getGameInfo() {} // Returns information about a game session, or creates it if it does not exist         public function deleteSession($session_id) {} // Deletes a game session from the database              // Methods dealing with game session information         protected function _gameExists($user_id) {}         protected function _getProgress($session_id) {}         protected function _updateProgress($game_info = array()) {}          }      ### The Game               /* CONTROLLER */     /* "Guess the word" page */          // User input     $game_type = $_POST['game_type']; // Chosen with radio buttons etc.     $wordlists = $_POST['wordlists']; // Chosen with checkboxes etc.          // Starts a new game or resumes one from the database     $game = new Game($_SESSION['user_id']);     $game_info = $game->getGameInfo();          // Instantiates a new Wordpicker     $wordpicker = new Wordpicker();          $wordpicker->setWordlists((isset($game_info['wordlists'])) ? $game_info['wordlists'] : $wordlists);     $wordpicker->setUsedWordlists((isset($game_info['used_wordlists'])) ? $game_info['used_wordlists'] : NULL);     $wordpicker->setUsedWords((isset($game_info['used_words'])) ? $game_info['used_words'] : NULL);          // Fetches an available word     if (! $word_id = $wordpicker->getRandomWord()) {              // No more words left - game over!         $game->deleteSession($game_info['id']);         redirect();          } else {              // Presents word details to the user         $word = new Word();         $word_info = $word->getWordInfo($word_id);          }      ### The Bit to Finish               /* CONTROLLER */     /* "Check the answer" page */          // ??????????????????      ( http://pastebin.com/cc6MtLTR ) Make sure you toggle the _'Layout Width'_ to the right for a better view. Thanks in advance. ### Questions   1. To which extent should objects be loosely coupled? If object A needs info from object B, how is it supposed to get this without losing too much cohesion?   2. As suggested in the comments, models should hold all business logic. However, as objects should be independent, where to glue them together? Should the model contain some sort of "index" or "client" area which connects the dots? _Edit:_ So basically what I should do for a start is to make a new model which I can more easily call with oneliners such as `$model->doAction(); // Lots of code in here which uses classes!` How about the method for checking words? Should it be it's own object? I'm not sure where I should put it as it's pretty much part of the 'game'. But on another hand, I could just leave out the 'abstraction and OOPness' and make it a method of the 'client model' which will be encapsulated from the controller anyway. Very unsure about this.