In a WPF MVVM application, I exposed my model object into my viewModel by creating an instance of Model class (which cause dependency) into ViewModel. Instead of creating separate VM properties, I wrap the Model properties inside my ViewModel Property. My model is just an entity framework generated proxy class:               public partial class TblProduct     {         public TblProduct()         {             this.TblPurchaseDetails = new HashSet<TblPurchaseDetail>();             this.TblPurchaseOrderDetails = new HashSet<TblPurchaseOrderDetail>();             this.TblSalesInvoiceDetails = new HashSet<TblSalesInvoiceDetail>();             this.TblSalesOrderDetails = new HashSet<TblSalesOrderDetail>();         }              public int ProductId { get; set; }         public string ProductCode { get; set; }         public string ProductName { get; set; }         public int CategoryId { get; set; }         public string Color { get; set; }         public Nullable<decimal> PurchaseRate { get; set; }         public Nullable<decimal> SalesRate { get; set; }         public string ImagePath { get; set; }         public bool IsActive { get; set; }              public virtual TblCompany TblCompany { get; set; }         public virtual TblProductCategory TblProductCategory { get; set; }         public virtual TblUser TblUser { get; set; }         public virtual ICollection<TblPurchaseDetail> TblPurchaseDetails { get; set; }         public virtual ICollection<TblPurchaseOrderDetail> TblPurchaseOrderDetails { get; set; }         public virtual ICollection<TblSalesInvoiceDetail> TblSalesInvoiceDetails { get; set; }         public virtual ICollection<TblSalesOrderDetail> TblSalesOrderDetails { get; set; }     }      Here is my ViewModel:               public class ProductViewModel : WorkspaceViewModel     {         #region Constructor         public ProductViewModel()         {             StartApp();         }              #endregion //Constructor              #region Properties              private IProductDataService _dataService;         public IProductDataService DataService         {             get             {                 if (_dataService == null)                 {                     if (IsInDesignMode)                     {                         _dataService = new ProductDataServiceMock();                     }                     else                     {                         _dataService = new ProductDataService();                     }                 }                 return _dataService;             }              }              //Get and set Model object         private TblProduct _product;         public TblProduct Product         {             get             {                 return _product ?? (_product = new TblProduct());             }             set             {                 _product = value;             }         }              #region Public Properties              public int ProductId         {             get             {                 return Product.ProductId;             }             set             {                 if (Product.ProductId == value)                 {                     return;                 }                      Product.ProductId = value;                 RaisePropertyChanged("ProductId");             }         }              public string ProductName         {             get             {                 return Product.ProductName;             }             set             {                 if (Product.ProductName == value)                 {                     return;                 }                      Product.ProductName = value;                 RaisePropertyChanged(() => ProductName);             }         }              private ObservableCollection<TblProduct> _productRecords;         public ObservableCollection<TblProduct> ProductRecords         {             get { return _productRecords; }             set             {                 _productRecords = value;                 RaisePropertyChanged("ProductRecords");             }         }              //Selected Product         private TblProduct _selectedProduct;         public TblProduct SelectedProduct         {             get             {                 return _selectedProduct;             }             set             {                 _selectedProduct = value;                 if (_selectedProduct != null)                 {                     this.ProductId = _selectedProduct.ProductId;                     this.ProductCode = _selectedProduct.ProductCode;                 }                 RaisePropertyChanged("SelectedProduct");             }         }              #endregion  //Public Properties              #endregion  // Properties              #region Commands              private ICommand _newCommand;         public ICommand NewCommand         {             get             {                 if (_newCommand == null)                 {                     _newCommand = new RelayCommand(() => ResetAll());                 }                 return _newCommand;             }         }              private ICommand _saveCommand;         public ICommand SaveCommand         {             get             {                 if (_saveCommand == null)                 {                     _saveCommand = new RelayCommand(() => Save());                 }                 return _saveCommand;             }         }              private ICommand _deleteCommand;         public ICommand DeleteCommand         {             get             {                 if (_deleteCommand == null)                 {                     _deleteCommand = new RelayCommand(() => Delete());                 }                 return _deleteCommand;             }         }              #endregion //Commands              #region Methods              private void StartApp()         {             LoadProductCollection();         }              private void LoadProductCollection()         {             var q = DataService.GetAllProducts();             this.ProductRecords = new ObservableCollection<TblProduct>(q);         }                   private void Save()         {             if (SelectedOperateMode == OperateModeEnum.OperateMode.New)             {                   //Pass the Model object into Dataservice for save                   DataService.SaveProduct(this.Product);             }             else if (SelectedOperateMode == OperateModeEnum.OperateMode.Edit)             {                  //Pass the Model object into Dataservice for Update                   DataService.UpdateProduct(this.Product);             }             ResetAll();             LoadProductCollection();         }                   #endregion  //Methods     }      Here is my Service class:               class ProductDataService:IProductDataService     {         /// <summary>         /// Context object of Entity Framework model         /// </summary>         private MaizeEntities Context { get; set; }              public ProductDataService()         {             Context = new MaizeEntities();         }              public IEnumerable<TblProduct> GetAllProducts()         {             using(var context=new R_MaizeEntities())             {                var q = from p in context.TblProducts                        where p.IsDel == false                        select p;                      return new ObservableCollection<TblProduct>(q);             }         }              public void SaveProduct(TblProduct _product)         {             using(var context=new R_MaizeEntities())             {                 _product.LastModUserId = GlobalObjects.LoggedUserID;                 _product.LastModDttm = DateTime.Now;                 _product.CompanyId = GlobalObjects.CompanyID;                 context.TblProducts.Add(_product);                      context.SaveChanges();             }         }              public void UpdateProduct(TblProduct _product)         {             using (var context = new R_MaizeEntities())             {                 context.TblProducts.Attach(_product);                      context.Entry(_product).State = EntityState.Modified;                 _product.LastModUserId = GlobalObjects.LoggedUserID;                 _product.LastModDttm = DateTime.Now;                 _product.CompanyId = GlobalObjects.CompanyID;                 context.SaveChanges();             }         }              public void DeleteProduct(int _productId)         {             using (var context = new R_MaizeEntities())             {                 var product = (from c in context.TblProducts                         where c.ProductId == _productId                         select c).First();                      product.LastModUserId = GlobalObjects.LoggedUserID;                 product.LastModDttm = DateTime.Now;                 product.IsDel = true;                 context.SaveChanges();             }         }               }      I exposed my model object in my viewModel by creating an instance of it using new keyword, also I instantiated my DataService class in VM. I know this will cause a strong dependency. So:   1. What's the best way to expose a Model object in a ViewModel?   2. What's the best way to use DataService in VM?


What are your opinions on "Gamification"?

I watched an interesting Google Talk video (warning about an hour of your time) about Gamification of whatever you are doing. It's clear that the StackExchange set of sites employ quite a few of these principles. There's something compelling about making work fun, but I wonder how many problem domains can incorporate these ideas? They definitely apply to social applications, but is that all? The concept of a virtual loyalty program is also quite compelling. Short description of Gamification: There is a system of scoring and reward. For example, Reputation in StackExchange is a type of scoring. Badges are a type of reward. The additional priviledges you gain as your reputation goes up are also a type of reward. An example of a loyalty program with no real redemption would be a promotion that a convenience store did a while back where you buy their products and get FarmVille credits in return. No real money or goods exchange hands, and the costs to the retailer are minimal at best. Yet it brings in real money for these virtual paybacks. Shameless use of JohnL's link: http://en.wikipedia.org/wiki/Gamification **NOTE:** The speaker refers to four classes of users which seem to have become the archetypes. They are Achievers, Socializer, Explorer, and Killers. The Achievers would most likely apply to all of us programmers--we like to get things done. Apparently 80% of people are socializers and like light, non- confrontational interactions. Explorers go to every corner of a game/application to discover whatever easter eggs and hidden features they can. Killers not only want to win, they want you to lose and get praise/status for beating you.


Should I listen to my employer and use CASE tools?

My employer (Not a Developer) thinks that CASE tools will help us improve our development process and documentation. I am not sure about that, we are a small team of 5 developers building mobile banking solutions for local clients. I think CASE tools will be a waste of time and money as they need to be purchased and we will need some time before we get used to them and be efficient working with them for modeling and stuff. Code generation is another issue, I really think that the CASE generated code won't be as good as code written by good developers. I think that if we stick with agile principles, design patterns, use TDD, and keep our code clean. we should be good. And as far as Analysis and Design, I think simple UML diagrams on whiteboard should do the trick. Documentation is good and important, but should be made as little as possible and we should not focus on Docs and forget the code. This is what i think. Am I correct? or should I listen to my employer and start researching for an appropriate CASE Tool?


Does an Rcpp-dependent package require a GPL license?

I'm writing a commercial package that uses R (GPL) for its computation. The GPL FAQ clearly states that GPLed programming language interpreters do not impose licensing restrictions on the "program" (text file with R code). So far, so good. Part of the package is compiled using Rcpp, which also uses the GPL. The next paragraph in the FAQ reads: > However, when the interpreter is extended to provide "bindings" to other > facilities (often, but not necessarily, libraries), the interpreted program > is effectively linked to the facilities it uses through these bindings. It can be interpreted that R is providing a binding to the Rcpp libraries (`Rcpp.dll` in the windows package). The safe assumption is that this taints my code with the GPL, but is this really the right conclusion? Part of my uncertainty is the tightness of the link between my code and `Rcpp.dll`. There are references to Rcpp in the dll, but I'm not proficient enough to know if these are references to the development environment or to calls being placed to symbols within the Rcpp library. If the former, then I believe that the Rcpp library is being linked by R and not by my library. I suspect the latter, though, since Rcpp provides a glue (sugar, actually) to simplify code-writing and execution. There are countless related discussions related to the GPL in code distribution. To name a few:   * Inside a virtual machine   * Exposure of intellectual property   * Consequences of GPL dependencies   * Using a GPL library in commercial software NB: I'm generally a big supporter of OSS and have participated in development and distribution in the past. Questions of "protecting code" often raise hackles of open-source programmers, frequently resulting in heated debates over software philosophy. I recognize value on both sides and want to ensure that I'm meeting the letter and (if possible) spirit of the laws. I'm not fishing for a loop-hole in the license; I'm looking for help interpreting and placing it into context. **Are R packages that depend on Rcpp required to use the GPL?**


Release cycle as a game

I thinking about how increase developer's commitment to release and create release cycle as a game for more fun in office. Current suggestions   * Building tower from bricks   * Climbing on some hypothetical everest, where each camp is release stage   * Some badges system, like StackExchange system


What are Some Real World Usage Scenarios for node.js

i would like to begin tinkering with Node.js but i am unsure of some "Real- World" situations where node.js would be considered the proper thing to be used. The last thing a developer wants is to learn a new technology and use it in-properly.. Can you provide real-world examples of where node.js would be used properly


Scrum: How to work on one story at a time

I was nominated as scrum master in a new formed scrum team. We have already done some sprints. In the beginning I tried to make my team to work on one story at a time. But it didn't work. My team had difficulties to distribute the tasks in a way that they can work simultaneously on one story. Maybe we are doing something wrong? For example: we have a story to create a new dialog. We create the following tasks:   * Create Model classes   * Read model data from database   * Connect model classes with view   * Implement dialog handling   * Save data on close   * Test Documentation   * Solution Description Can theses tasks be done by more than one person at a time? The tasks - more or less - build upon each other. Or do we design the tasks in a wrong way?


What criteria should be used to determine a programmer's salary?

Recently, I was a part of a discussion about which criteria should be used when determining a salary for a programmer: arguments varied from "it is a matter of employer's choice" to other arguments that took into account one's education, experience, understanding of technologies, etc. Not so long ago, I read a great post on the Stack Exchange blog on the subject and I couldn't agree more with it, but not many employers follow the described logic. In your experience, which elements are the most important ones when determining salary for a programmer? Which criteria are most often applied in those situations? Which criteria _should_ be most often applied? And finally, to which extent is formal education (college, university) important in determining salary?


C++ raw pointers for storage

I'm seeing a lot of people say you should never use raw pointers. What about in the case where you store the raw pointer in a class but how they get populated is from getting the pointer of an object that wasn't dynamically created? I'm curious about if this is bad practice and if so how to make it better. This seems ideal to me as I'm not required to delete anything myself so limited/no chance for a memory leak? The idea of "if you didn't create it you don't delete it". I can control everything by the scope of the variable I'm passing in right? If it goes out of scope then what it points to won't be valid anymore and it'll throw an exception if I try to access it and I'll be able to catch it and handle it. Curious on thoughts/comments/concerns on this.               class Object     {     private:        Object* object;     public:        void Object() { object = NULL; }        void AddObject(Object* obj)        {           object = obj;        }            Object* GetObject()       {          return object;       }     };               int main()     {        Object obj1;        Object obj2;             // obj2 wasn't dynamically created so no need to use a smart pointer        obj1.AddObject(&obj2);             return 0;     }


Where can I find an authoritative comparison of computer languages?

I've reached a point in my career where I want to consider myself less "an {x} engineer" where {x} is a specific programming language, and I want to be more of a language-agnostic software engineer. The obvious next step is to start learning as many languages as possible to build experience, but there's only so many hours in the day and I'd rather go about this in a more efficient way. Also, my end goal is not to be practically proficient in 20 languages, but rather to understand more deeply the variation among programming languages and what tradeoffs and design choices they made and why. I tend to learn better when I can see an overview of the topical landscape first, before diving into the details. Is there a good, long-form (i.e., not a blog post) work on comparative language analysis that does a good job exploring the variations in programming language features? Or maybe, alternately, a good coverage text on programming language design?


Taking a Projects Development to the Next Level

I have been looking for some advice for a while on how to handle a project I am working on, but to no avail. I am pretty much on my fourth iteration of improving an "application" I am working on; the first two times were in Excel, the third Time in Access, and now in Visual Studio. The field is manufacturing. The basic idea is I am taking read-only data from a massive Sybase server, filtering it and creating much smaller tables in Access daily (using delete and append Queries) and then doing a bunch of stuff. More specifically, I use a series of queries to either combine data from multiple tables or group data in specific ways (aggregate functions), and then I place this data into a table (so I can sort and manipulate data using DAO.recordset and run multiple custom algorithms). This process is then repeated multiple times throughout the database until a set of relevant tables are created. Many times I will create a field in a query with a value such as 1.1 so that when I append it to a table I can store information in the field from the algorithms. So as the process continues the number of fields for the tables change. The overall application consists of 4 "back-end" databases linked together on a shared drive, with various output (either front-end access applications or Excel). So question is: **Is this a common way how data driven applications work?** Each back-end database is updated with fresh data daily and updating each takes around 10 seconds (for three) and 2 minutes(for 1). **Project Objectives:** I want/am moving to SQL Server soon. Front End will be a Web Application (I know basic web-development and like the administration flexibility) and visual-studio will be IDE with c#/.NET. Should these algorithms be run "inside the database," or using a series of C# functions on each server request. I know you're not supposed to store data in a database unless it is an actual data point, and in Access I have many columns that just hold calculations from algorithms in vba. The truth is, I have seen multiple professional Access applications, and have never seen one that has the complexity or does even close to what mine does (for better or worse). But I know some professional software applications are 1000 times better then mine. I have been completely on my own and need some guidance on how to approach this project the right way. **What would be a good approach to follow ?**


Is it a bad practice to write shell script with many if-else statment and for loops?

I am maintaing several data process shell scripts which are full of if-else statements and for loops . I try to make the scritps tidy and easy to debug. When I read some suggestions about shell code best practice, it seems that is is not a best practice to have many if-else and for loop statements. So what should I do, to write a python or c++ script instead of those logical process?


Pros and cons of intrusive and non-intrusive serialization?

I am interesting in the pros and cons of serialization: intrusive and non- intrusive. On the one hand it seems non-intrusive is easy to use - class to be serialized should not be updated. It seems convenient for simple cases. E.g. XStream.Net implements such approach. But the issues can appear if this class is connected in some way with other classes, e.g. stores indices of global objects which should be serialized as well. In this case non-intrusive approach looks dangerous. Concerning intrusive implementation. It is good that developer can directly specify what and how to serialize (of course if serialization technology is flexible enough).   E.g. Microsoft .Net has intrusive approach implemented for XML serialization \- attributes should be specified for classes and members. Other ideas?


why is a naturally ordered set generated at 9 but not 10 digits

code found at: fatal error...Java Runtime Environment: EXCEPTION_ACCESS_VIOLATION Presuming that the problem indicated above is due to the test app and not due specifically to method generateRandomDigits(). When NUMBER_OF_DIGITS_TO_ORDER is <= 9, I do get a naturally ordered sets (just trying to prove that it is possible), but when it is set to 10 I never get such a set and I've run it many times. Why? I am more than open to suggested improvements to method generateRandomDigits() - it seems a bit convoluted.


Benefits of Java ByteArrayInputStream vs byte array?

I have a scenario where my Java process will be receiving a stream of binary data:               public class DataHandler {         public void handleData(DATA data) {             // TODO: Do something with data         }     }      I am trying to figure out the proper typing for `DATA`. I could use a `byte[]`:               public class DataHandler {         public void handleData(byte[] data) {             // TODO: Do something with data         }     }      Or a `ByteArrayInputStream`:               public class DataHandler {         public void handleData(ByteArrayInputStream dataStream) {             // TODO: Do something with dataStream         }     }      To me, "`ByteArrayInput` **`Stream`** " implies a continuous **stream** of data that is constantly being modified. Based on that, it _feels_ like `ByteArrayInputStream` is better suited for my use case as it probably adds a bunch of bells and whistles on top of a plain 'ole `byte[]`. But then I see that its constructor takes `byte[]` and doesn't allow you to add more `byte`s to it post-construction, which might not necessarily do anything for me in this particular case. So my questions:   1. In my use case, are there any benefits to `ByteArrayInputStream` over `byte[]`? Why/why not? What are the factors that drive this decision (in general)?   2. Is there a better way to represent a true _stream_ of flowing data (which ultimately comes in as bytes) besides the methods I've recommended here?


Am I right about the differences between Floyd-Warshall, Dijkstra's and Bellman-Ford algorithms?

I've been studying the three and I'm stating my inferences from them below. Could someone tell me if I have understood them accurately enough or not? Thank you.   1. Dijkstra's algorithm is used only when you have a single source and you want to know the smallest path from one node to another, but fails in cases like this   2. Floyd-Warshall's algorithm is used when any of all the nodes can be a source, so you want the shortest distance to reach any destination node from any source node. This only fails when there are negative cycles **(this is the most important one. I mean, this is the one I'm least sure about:)** 3.Bellman-Ford is used like Dijkstra's, when there is only one source. This can handle negative weights and **its working is the same as Floyd-Warshall's except for one source, right?** If you need to have a look, the corresponding algorithms are (courtesy Wikipedia): Bellman-Ford:                procedure BellmanFord(list vertices, list edges, vertex source)        // This implementation takes in a graph, represented as lists of vertices        // and edges, and modifies the vertices so that their distance and        // predecessor attributes store the shortest paths.             // Step 1: initialize graph        for each vertex v in vertices:            if v is source then v.distance := 0            else v.distance := infinity            v.predecessor := null             // Step 2: relax edges repeatedly        for i from 1 to size(vertices)-1:            for each edge uv in edges: // uv is the edge from u to v                u := uv.source                v := uv.destination                if u.distance + uv.weight < v.distance:                    v.distance := u.distance + uv.weight                    v.predecessor := u             // Step 3: check for negative-weight cycles        for each edge uv in edges:            u := uv.source            v := uv.destination            if u.distance + uv.weight < v.distance:                error "Graph contains a negative-weight cycle"      Dijkstra:                1  function Dijkstra(Graph, source):      2      for each vertex v in Graph:                                // Initializations      3          dist[v] := infinity ;                                  // Unknown distance function from       4                                                                 // source to v      5          previous[v] := undefined ;                             // Previous node in optimal path      6                                                                 // from source      7            8      dist[source] := 0 ;                                        // Distance from source to source      9      Q := the set of all nodes in Graph ;                       // All nodes in the graph are     10                                                                 // unoptimized - thus are in Q     11      while Q is not empty:                                      // The main loop     12          u := vertex in Q with smallest distance in dist[] ;    // Start node in first case     13          if dist[u] = infinity:     14              break ;                                            // all remaining vertices are     15                                                                 // inaccessible from source     16               17          remove u from Q ;     18          for each neighbor v of u:                              // where v has not yet been      19                                                                                removed from Q.     20              alt := dist[u] + dist_between(u, v) ;     21              if alt < dist[v]:                                  // Relax (u,v,a)     22                  dist[v] := alt ;     23                  previous[v] := u ;     24                  decrease-key v in Q;                           // Reorder v in the Queue     25      return dist;      Floyd-Warshall:                1 /* Assume a function edgeCost(i,j) which returns the cost of the edge from i to j      2    (infinity if there is none).      3    Also assume that n is the number of vertices and edgeCost(i,i) = 0      4 */      5      6 int path[][];      7 /* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path      8    from i to j using intermediate vertices (1..k−1).  Each path[i][j] is initialized to      9    edgeCost(i,j).     10 */     11     12 procedure FloydWarshall ()     13    for k := 1 to n     14       for i := 1 to n     15          for j := 1 to n     16             path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );


How does one rein in the complexities of web development?

I have been a server-side programmer for most of my career and have only recently started spending more time on web development. I am amazed at the number of things I need to master in order to write a decent web application. Just to list down a few tools/technologies I need to learn,   * Server side programming language (Java/JSP, ASP, PHP, Ruby or something else)   * A decent web framework (for any medium to big size application).    * HTML & CSS   * Javascript   * Javascript library (JQuery/ExtJS etc. primarily for AJAX). Good to know even if not necessary.   * At least a basic knowledge of web design - layouts, colors, fonts etc.   * A good understanding of web security.   * A good understanding of Performance/scalability issues.   * Testing, browser compatibility issues etc. The list goes on. So, my question to seasoned web developers is - How do you guys manage to learn and keep yourself updated on so many things? While developing a web application, how do you handle the complexities involved in these areas and yet manage to write an application that is well designed, user friendly, secure, performant and scalable. As a web developer, does one have to be a jack of all trades or should one specialize in one or two areas and leave the rest to other members of the team ?


Is it safe to use LAST_INSERT_ID() in a system like Point of Sale

Is it safe to use `LAST_INSERT_ID()` in a system using `MySQL` like Point Of Sale when there are multiple users using the system at the same time?


Why is there so much buzz about closures?

Why is there so much buzz about closures among developers? In my career I never intentionally used them, though don't clearly understand what they are. UPD: just to clarify. The question is about why the closure concept became so talky these days.


ado.net or EF for a point-of-sale system

We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow. The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?


Should an XML Schema be specified in a software specification?

Would you include an XML schema for a new file format in a software specification document or would you consider this too specific? Or would it be already too specific to require XML at this point?


What are the advantages and disadvantages of having a subdomain for each user account?

I notice two types of design used in web applications, some with a particular subdomain for users contents, and some with same URL structure for all the accounts. Ex: `unique.domain.com` and `another_unique.domain.com` for subdomains for sites like blogspot, wordpress, basecamp etc. while in the other approach `domain.com/action1` and `domain.com/action2` the content is shown according to the user logged in, but the URL is same for every user. What are main differences between both of these kind of design?


What does using ZeroMQ in Erlang offer that Erlang already didn't?

I'm only passingly familiar with either, but it seems like most of what ZeroMQ offers is already built into Erlang, yet there's an Erlang-ZeroMQ binding that's fairly active according to its github page. What am I missing?


One web service multiple sites

I don't know whether this is even possible or I imagine (according to my habit of over thinking) will bring through numerous issues but let me give it a go. I have an idea where I would like a single web service which a user will send a request to, for example logging in. The response back dictates a URL where they get redirected too so essentially this means for me less maintenance in updating web services etc as its all in one place. What I am trying to do is have a single service that routes people to the correct server to get data from instead of having the end user to have knowledge of the endpoint address etc. For example, I have a system on the web and want it visible to my windows, android and apple devices but there is a specific site for each client. Ideally, I only want the user to enter their login credentials and the web service does the rest, i.e. fetches data from the correct data source. I imagine this is common practice for many systems but I guess is there a risk factor in that a user being sent data from another request if they happen at the same time? Obviously this is a huge flaw and perhaps I am going completely the wrong route here. I would appreciate any resources to links, books etc. I was unsure of what to search for on the web so thought this is the best place for such questions. This is a system I am developing to help me understand web services better in general. A little project I am working on to help me explore different techniques and approaches towards development :)


New Team Lead - How to deal with a resentful former peer

I've been told that I am to be a team lead of an upcoming project. I've not ever been team lead before but the responsibilities are what you would typically expect, with revolving door of 3 to 4 other developers through the 8 or 9 months it takes to complete the project. My problem is this: one of the developers who will no doubt be working on this project will be a problem. He has more experience than me, has called me an idiot several times in the past, and has told me that he has taken this job because he is a natural leader. He has expected to be promoted to a leadership position with every new project (which has not happened to date), and even once told me that I was to report to him, even though the actual team lead was under no such illusion. Moreover, I've both observed and heard from others that he is extremely unprofessional (watches non-work videos at client sites - with no head phones, dresses unprofessionally, comes to work late, makes inappropriate jokes, etc.) He took or attempted to take credit for my work or insights multiple times while I worked with him as a peer. My current team lead told me that she threw out 1/2 of this guy's code once he left her project because the quality was no good. I could go on. My fear is that this guy will actively work against me, because he will resent having to report to someone that he considers an inferior, especially since I have been given this opportunity before him. I've successfully dealt with this type of personality as a peer or even reporting to managers like this in the past. I've not dealt with, or ever thought about, having to deal with this type of character who is reporting to me. My question is: what kind of strategies can I use to effectively and professionally deal with this? Especially now, before it has become a problem, is there any way to cut it off before it gets out of hand etc. If anyone has a similar experience how did they deal with it?


Paradigm Diagram

Does anyone have a diagram showing all significant programming paradigms. Something like this but with paradigms as titles would be ideal: ![help page image](http://i.stack.imgur.com/rARsG.png)


How to Convert HTML to PDF Using PHP?

PDF or Portable Document Format is a popular file type that is often used for online documents. It's great for distributing downloadable written content, and is frequently used by governments and businesses alike. Because it's a format that's familiar to all, many applications allow the user to convert other document types to the PDF format. PHP is one programming language that has a built-in ability to convert to PDF. PHP scripts can be used to transform file types such as HTML into PDF files.


What should be stored in UserContext?

From my general understanding I believe UserContext for a web application is supposed to hold user authentication and authorization (user roles) information. As part of user roles, there are definitions on who can access what data and accordingly the corresponding reference data is loaded into the UserContext as well. Is this a good practice to load and use reference data from UserContext? Does this have any impact with the number of sessions vs size of data it is holding inside JVM? I am thinking we use UserContext only for authentication and authorization but load the reference data from cache on demand and use it if required.


Is it a better practice pre-initialize attributes in a class, or to add them along the way?

I'm sorry if this is a ABSOLUTELY sophomoric question, but I'm curious what the best practices are out there, and I can't seem to find a good answer on Google. In Python, I usually use an empty class as a super-catchall data structure container (sort of like a JSON file), and add attributes along the way:               class DataObj:         "Catch-all data object"         def __init__(self):             pass          def processData(inputs):         data = DataObj()         data.a = 1         data.b = "sym"         data.c = [2,5,2,1]      This gives me a tremendous amount of flexibility, because the container object can essentially store anything. So if new requirements crop up, I'll just add it as another attribute to the DataObj object (which I pass around in my code). However, recently it has been impressed upon me (by FP programmers) that this is an awful practice, because it makes it very hard to read the code. One has to go through all the code to figure out what attributes DataObj actually has. **Question** : How can I rewrite this for greater maintainability without sacrificing flexibility? Are there any ideas from functional programming that I can adopt? I'm looking for best-practices out there. **Note** : one idea is to pre-initialize the class with all the attributes that one expects to encounter, e.g.               class DataObj:         "Catch-all data object"         def __init__(self):             data.a = 0             data.b = ""             data.c = []          def processData(inputs):         data = DataObj()         data.a = 1         data.b = "sym"         data.c = [2,5,2,1]      Is this actually a good idea? What if I don't know what my attributes are a priori?


When to build(code) vs buy(download plugin)

Recently I have been working with a large set of talented programmers that lead to a discussion on when should we start building our own components (web js/css) vs downloading and modifying existing components that don't quite fit the needs of a project. Does anyone know or could suggest best practices for this type of conundrum?


Database fuzzy search concept

I thought about this, and have been trying to come up with solutions on how to fuzzy search a database, if for say example a user types a spelling mistake. Any glaring problems with the logic behind this? Will it work and has it been done before? Our table we wish to search:               **tblArticles**     Body - Soundex_Body - CharacterCoded_Body      So we store the raw text body for physical display. The other 2 columns are used for searches which are precomputed the following way: **Soundex** Body is split into it's words, and translated to it's soundex version. IE, resulting body might be something like:               H252 B54 C23 E33... etc      So someone might enter 'dinosore', and the article body reads 'dinosaur' these both evaluate to B26. We then run a LIKE on the soundex value of search term. **Character Coded** Given a character mapping that maps chars to prime numbers, IE:               h = 2     e = 3     l = 5     o = 7     p = 11     c = 13          help = 2*3*5*11     =   330     hello = 2*3*5*5*7   =   1050     hell = 2*3*5*5      =   150     hlep = 2*5*3*11     =   330     cello = 13*3*5*5*7  =   6825      If a user meant to type 'hello' but they switched two or more characters around for example 'hlelo', they would evaluate to the same number. Split raw body into words, prime encode every word and store in database giving you a field that looks like:               330 6825 330 1050... etc      We can then like search on this value to match mistypes. **Benefits**   * Typos protected against   * Phonetic incorrect spellings protected against   * More non native english speaking friendly   * Will work in any language (where soundex works) Comments and thoughts? A sort of multilayered search. You can of course weight return values to make it even better (IE a literal text body match is worth more), but is this a good solution for spelling errors and non native english speakers doing searches?


Side-by-side Configuration on Linux/ELF

One of the best/worst Microsoft software innovations (great for compatibility; terrible for efficiency) has been Windows' Side by Side Configuration. This allows, among other things, for different components of a program to have multiple versions of the C/C++ runtime libraries loaded into the same process. This has always impressed me because of the excellent backwards compatibility that it affords. For example, you can run an ancient program that links against very old C/C++ runtimes, and link it against or dynamically inject a new DLL that depends on a new C/C++ runtime, and all the separate instances of the runtimes will coexist simultaneously within the address space and will be called by the assembly that references them. On Linux, however, binaries for which the source is not available tend to "rot" over time -- rather quickly. The reason is that most interesting programs eventually have to link back into libraries that are installed in your system directories (`/usr/lib`, etc). But since the C/C++ runtimes and the system libraries frequently change ABI, your program just stops working when you upgrade your distro. This can also be caused, for example, by software with "backends" that eventually link to your system libraries. An example is OpenGL, which due to the variety and volatility of the implementations, cannot be provided by binary distributions. They simply must depend on the system's OpenGL implementation. But if your system OpenGL links against `libstdc++`, you could potentially be dead in the water. What happens is that the old executable loads its local copy of `libstdc++`, and the OpenGL shared library loads the system's copy of `libstdc++`. The two conflict, and one of them refuses to load, and usually this means that OpenGL refuses to work and the program comes crashing down. For a "mere" application developer, is something like WinSxS achievable on Linux without major architectural changes to the ELF binary format and Linux kernel ABI? Or is this something that would have to be built into the system libraries at compile-time and deployed over a long period of time by making changes to ELF, glibc, libstdc++, compilers, and so on?


How are objects modelled in a functional programming language?

In an answer to this question (written by Pete) there are some considerations about OOP versus FP. In particular, it is suggested that FP languages are not very suitable for modelling (persistent) objects that have an identity and a mutable state. I was wondering if this is true or, in other words, how one would model objects in a functional programming language. From my basic knowledge of Haskell I thought that one could use monads in some way, but I really do not know enough on this topic to come up with a clear answer. So, how are entities with an identity and a mutable persistent state normally modelled in a functional language? **EDIT** Here are some further details to clarify what I have in mind. Take a typical Java application in which I can (1) read a record from a database table into a Java object, (2) modify the object in different ways, (3) save the modified object to the database. How would this be implemented e.g. in Haskell? I would initially read the record into a record value (defined by a data definition), perform different transformations by applying functions to this initial value (each intermediate value is a new, modified copy of the original record) and then write the final record value to the database. Is this all there is to it? How can I ensure that at each moment in time only one copy of the record is valid / accessible? One does not want to have different immutable values representing different snapshots of the same object to be accessible at the same time.


btnBack vs backButtonField

For blackberry GUI developement. I am using the name convention like backButtonField and some of my colleagues are using btnBack. But sometimes I stuck with the names like loginVerticalFieldManager its a very long name. At that time vfmLogin looks better So for GUI components names what convention should I follow?


Should I avoid or embrace asking questions of other developers on the job?

As a CS undergraduate, the people around me are either learning or are paid to teach me, but as a software developer, the people around me have tasks of their own. They aren't paid to teach me, and conversely, I am paid to contribute. When I first started working as a software developer co-op, I was introduced to a huge code base written in a language I had never used before. I had plenty of questions, but didn't want to bother my co-workers with all of them - it wasted their time and hurt my pride. Instead, I spent a lot of time bouncing between IDE and browser, trying to make sense of what had already been written and differentiate between expected behavior and symptoms of bugs. I'd ask my co-workers when I felt that the root of my lack of understanding was an in-house concept that I wouldn't find on the internet, but aside from that, I tried to confine my questions to lunch hours. Naturally, there were occasions where I wasted time trying to understand something in code on the internet that had, at its heart, an in-house concept, but overall, I felt I was productive enough during my first semester, contributing about as much as one could expect and gaining a pretty decent understanding of large parts of the product. I was wondering what senior developers felt about that mindset. Should new developers ask more questions to get to speed faster, or should they do their own research for themselves? I see benefits to both mindsets, and anticipate a large variety of responses, but I figure new developers might appreciate your answers without thinking to ask this question.


C++ TDD open source projects

Are there any open source projects out there that are written in C++ in an agile way (TDD maybe?). I am trying to contribute to a C++ open source project in order to catch up with the language and I am not sure where to look for since the language is no longer mainstream amongst the hipsters :P **Edit** : I don't think I made myself clear (sorry about this, English is not my native language) - I want to contribute to an open source project written in C++ which follows TDD rules and such, not TDD frameworks implemented in C++ (though that might be an option).


Is reliance on parametrized queries the only way to protect against SQL injection?

All I have seen on SQL injection attacks seems to suggest that parametrized queries, particularly ones in stored procedures, are the only way to protect against such attacks. While I was working (back in the Dark Ages) stored procedures were viewed as poor practice, mainly because they were seen as less maintainable; less testable; highly coupled; and locked a system into one vendor; (this question covers some other reasons). Although when I was working, projects were virtually unaware of the possibility of such attacks; various rules were adopted to secure the database against corruption of various sorts. These rules can be summarised as:   1. No client/application had direct access to the database tables.   2. All accesses to all tables were through views (and all the updates to the base tables were done through triggers).   3. All data items had a domain specified.   4. No data item was permitted to be nullable - this had implications that had the DBAs grinding their teeth on occasion; but was enforced.   5. Roles and permissions were set up appropriately - for instance, a restricted role to give only views the right to change the data. **So is a set of (enforced) rules such as this (though not necessarily this particular set) an appropriate alternative to parametrized queries in preventing SQL injection attacks? If not, why not? Can a database be secured against such attacks by database (only) specific measures?** **EDIT** Emphasis of the question changed slightly, in the light of the initial responses received. Base question unchanged. **EDIT2** The approach of relying on paramaterized queries seems to be only a peripheral step in defense against attacks on systems. It seems to me that more fundamental defenses are both desirable, and may render reliance on such queries not necessary, or less critical, even to defend specifically against injection attacks. The approach implicit in my question was based on "armouring" the database and I had no idea whether it was a viable option. Further research has suggested that there are such approaches. I have found the following sources that provide some pointers to this type of approach: http://database-programmer.blogspot.com http://thehelsinkideclaration.blogspot.com The principle features I have taken from these sources is:   1. An extensive data dictionary, combined with an extensive security data dictionary   2. Generation of triggers, queries and constraints from the data dictionary   3. Minimize Code and maximize data While the answers I have had so far are very useful and point out difficulties arising from disregarding paramaterized queries, ultimately they do not answer my original question(s) (now emphasised in bold).


Exception when logging exception: is it correct to ignore them?

My question is specific to php, but i think it can be useful in other languages. I log into a table all the exception a code can throw:               try{      //Some code      } catch (Exception $e) {           $log = new Log(basename($_SERVER['PHP_SELF']), $_SESSION['id'], LogType::EXCEPTION, $e);           try {                $log ->addLog();            } catch (Exception $e2) {                     //            }      }      The function addLog insert the exception informations into a database. But (by example if the connection with the database is lost) this function can throw an exception. I can't see what i have to do with this exception except ignoring it. I know ignoring exception is a bad practice, but what can i do in this particular case? If there is no problem to ignore it, is there a better way to indicate that this exception should not be taken into account?


Reconstructing a huffman tree using minimal information in the header

I'm writing a huffman encoding program in C. I'm trying to include the least amount of information in the header as possible, I know the simplest way to decompress the file in the header would be to store the frequencies of each character in the file, but for a large file with 256 characters it would take 2304 bytes ((1 byte for character + 8 bytes for `long` frequency) * 256), which I don't think is optimal.   I know I can reconstruct a tree from a preorder scan and an inorder scan of it, but that requires having no duplicate values. That is bad because I now have to store each node in the tree (in a huffman tree: `n*2 - 1` with `n` being the number of unique characters), twice, having each node be a `long` value (which could take `((256*2 - 1) * 2) * 8 = 8176` bytes. Is there a way I'm missing here, or are those my only options? Thanks.


What interface does python use to implement sockets?

When I programmed in python, I believe I interfaced with the transport layer using sockets. If python was programmed by humans, they must have used an interface that was "lower" than sockets, to provide _us_ with the interface to sockets. I assume firewalls, also programmed by humans, use interfaces of lower layers in the same manner, so is there a way to access such lower layers, in terms of programming?


When running PHPUnit tests - is it common to use a separate database for testing?

I'm running tests from the same database as I use in development. I recall using Rails and I used a separate database for testing (mainly coz the tutorial I was going by said so). Made sense though. I was wondering it this was the common way to do things or whether there was an alternative. Can anyone shed a little light on this?


cx_Freeze'd application license

I have a python program packed to .exe using cx_Freeze. I am trying to understand licensing implications:   * do I have to reproduce cx_Freeze license agreement?   * do I have to reproduce python license (PSF)?   * as python has standard modules incorporated into it, which might have yet another license, do I have to attach them (this is because cx_Freeze will pack them probably too, even if I don't use them)? Any hints would be appreciated!


A study shows that lines_written/time is language-independent for most programmers. Where can it be found?

A study shows that lines_written/time is language-independent and application- independent for most programmers. If this were true it would imply that the most terse a language is, the more productive a programmer can be on it. Where can this study be found?


Use cases for "private" interfaces?

I was wondering if there was a valid use case for being able to properly define the specific internal properties and functions of a class in a way similar to how an interface defines the public properties and functions of a class. Imagine the task that you have to build a class that describes a human being. Obviously, each human is a humanoid creature but not every humanoid creature is a human so you'd probably have an interface IHumanoid with functions like these (since it isn't useful to hardcode the body plan into the class):               public interface IHumanoid {         function get head():IHead;         function get torso():ITorso;         function get leftArm():IArm;         function get rightArm():IArm;         function get leftLeg():ILeg;         function get rightLeg():ILeg;     }      Further and also obviously, each human is a mammal but not every mammal is a human, so there's probably another interface IMammal with two definitions for males and females floating around somewhere:               public interface IMammal {         function procreate(partner:IMammal):void;     }          public interface IMaleMammal extends IMammal {         function inseminate(female:IFemaleMammal):void;     }          public interface IFemaleMammal extends IMammal {         function conceive(partner:IMaleMammal):Boolean;         function giveBirth():IMammal;         function nurse(offspring:IMammal):void;     }      Thus our class probably looks something like this now:               public class Human implements IHumanoid, IMammal {         private var _head:IHead;         private var _torso:ITorso;         private var _leftArm:IArm;         private var _rightArm:IArm;         private var _leftLeg:ILeg;         private var _rightLeg:ILeg;              public function Human() {             // ctor...         }              public function get head():IHead {             return _head;         }              public function get torso():ITorso {             return _torso;         }              public function get leftArm():IArm {             return _leftArm;         }              public function get rightArm():IArm {             return _rightArm;         }              public function get leftLeg():ILeg {             return _leftLeg;         }              public function get rightLeg():ILeg {             return _rightLeg;         }              public function procreate(partner:IMammal):void {             // "abstract" function         }     }          public class MaleHuman extends Human implements IMaleMammal {         override public function procreate(partner:IMammal):void {             if (partner is IFemaleMammal) {                 inseminate(partner);             }         }              public function inseminate(female:IFemaleMammal):void {             female.conceive(this);         }     }          public class FemaleHuman extends Human implements IFemaleMammal {         override public function procreate(partner:IMammal):void {             if (partner is IMaleMammal) {                 conceive(partner);             }         }              public function conceive(partner:IMaleMammal):Boolean {             // ...         }              public function giveBirth():IMammal {             // ...         }              public function nurse(offspring:IMammal):void {             // ...         }     }      From this we can implement our classes further and everything's working nice and fine until we get the task to use the existing interfaces to implement some other classes. Perhaps a gorilla, an orca and a platypus. Ignoring the massive issue the platypus will pose to our current interface structure (*cough* egg laying mammal *cough*), we have the "problem" that nothing prevents us from giving the gorilla 2 brains, the orca 8 lungs and the platypus half a dozen livers. And while we might be disciplined enough to follow the structure mammals typically have we cannot guarantee the same if we open the API for other developers who might code some seriously screwed up things which still look okay to the outside world. Therefore I was wondering if there was a valid use case to create something like a "private interface" which defines non-public functions and properties. Perhaps something along these lines:               public structure SMammal {         function get brain():IBrain;         function get liver():ILiver;         function get leftLung():ILung;         function get rightLung():ILung;         function get leftKidney():IKidney;         function get rightKidney():IKidney;     }          public class Human implements IHumanoid, IMammal follows SMammal {         private function get brain():IBrain {             // ...         }              private function get liver():ILiver {             // ...         }              // etc. etc.     }      Does such a feature exist in any programming language? Can abstract classes be used to solve this? Or shouldn't we care about this at all as long as the public interface somehow works as expected?


Is it possible to create a single tokenizer to parse this?

This extends off this other Q&A thread, but is going into details that are out of scope from the original question. I am generating a parser that is to parse a context-sensitive grammar which can take in the following subset of symbols: `,`, `[`, `]`, `{`, `}`, `m/[a-zA-Z_][a-zA-Z_0-9]*/`, `m/[0-9]+/` The grammar can take in the following string `{ abc[1] }, }` and parse it as (`{`, `abc[1]`, `},` `}`). Another example would be to take: `{ abc[1] [, }` and parse it as (`{`, `abc[1]`, `[,`, `}`). This is similar to the grammar used in Perl for the qw() syntax. The braces indicate that the contents are to be whitespace tokenized. A closing brace must be on its own to indicate the end of the whitespace tokenized group. Can this be done using a single lexer/tokenizer, or would it be necessary to have a separate tokenizer when parsing this group?


Why are errors named as "Exception" but not as "Error" in programming languages?

I've been thinking about that for quite a while actually. I am not a native english speaker myself but still I have years of programming experience and I always asked me this. Why is it named as Exception but not Error since they are errors. It could be `PageNotFoundError`instead of `PageNotFoundException`.


Proper way to "compile" a javascript project?

I'm developing a small open-source javascript library, and I was wondering about the proper method for compiling the source into one javascript file. It's easier to develop if the code is split into multiple files, but libraries are included as one large file when used in another application. My current "compilation" method involves using a makefile to copy each submoudle into the main file and then minify it. What is the proper way to do this?


TFS non-chronological deployment?

We have the following scenario: Changeset #1 is some unfinished buildable checkin   Changeset #2 is a completed small task   ..   Changset #5 completes the work done at CS#1 They all affect the same output dll. How do we deploy changes done at CS#2 without the other work? Also how can we avoid this situation happening again in the future?


Managing multiple people working on a project with GIT

I'm very new to GIT/GitHub (as new as starting yesterday). I would like to know what is the best way to manage multiple people working on the same project with Github. Currently I'm managing one project with four developers.   1. How do I go about the workflow and making sure everything is in sync? (Note: All developers will have one universal account.)   2. Does each developer need to be on a different branch?   3. Will I be able to handle 2 people working on the same file? Please post a detailed answer, I'm not a shy reader. I need to understand this well.


How to find an error in a tcp server application for which there is no source code

I have a c++/cli tcp client application sending a data in a specific format like **`L,20100930033425093,-5.929958,13.164021`** to a main application on port 9000.The main application is actually done by the other vendor and I dont have the source code for that. Now,I can communicate to the desired application using the IP and Port No.But the data supposed to be visible on the Main Application GUI is not showing up. But I used a different socket server demo application with same IP as the main application to receive the data I am sending.It works perfectly fine. Now I do not know where the error is or whether the stream is received on the other side. How can I effectively solve this situation. I am asking this in a broader picture to get some ideas. Any suggestions or discussion on this will be helpful?


Is there any online video giving a useful insight on programming in certain languages or in general?

Recently I begun to watch the series of lecture Douglas Crockford made on Javascript and other topics. I've been wondering: is there also such lectures/lecturers for other other languages? **EDIT:** Thanks for the few answers I'll be sure to check them. But I must say, that personally, I have an interest on languages and technology relative to web development, or any kind of video which content could apply to more than one language. Of course, any good online video resource are still welcome, as I want this question to be as useful as possible for other people. Also bonus points if the content is downloadable and viewable on iTunes.


What is a non commital approach to software analysis

When I think about software analysis the first thing which comes to mind is SSADM and the UML. But, what I want is a high level view of the system before I commit to a programming paradigm. Where am I going wrong? How do I approach a problem in a high level and generic way before I commit to a paradigm? What are the diagrams/tools available to support me? Edit: Some examples of tools that appear to be what I'm after are... A block diagram - http://en.wikipedia.org/wiki/Block_diagram A data flow diagram - http://en.wikipedia.org/wiki/Data_flow_diagram


How to submit a bug/fix for jquery unobtrusive validation?

I found a small bug in the microsoft mvc3 remote validation, concerning the clientside javascript implemented in jquerys unobtrusive javascript. The problem/bug can be fixed by adding a few lines to jquery.validate.unobtrusive.js which is bundled in the microsoft mvc3 installation. I can't seem to find a bug repository on jquery.com or in its plugins area. Am i not seeing the tree in the forest, or am i not going insane - where should i go with this problem - i already have the fix ready, but i'm afraid the next time jquery.validate.unobtrusive.js is updated (new version) and it's being applied to my project, my fix is overwritten. I also fooled around with adding some javascript that replaces the adapter (that has the bug) with my own version after jquery.validate.unobtrusive.js has been loaded - the problem is, that it's pretty ugly and What to do?


File naming convention for images stored in version control?

My application has an icon file which is stored in version control. Now tomorrow I might decide to change the icon. I'm debating between two possible naming conventions for the icon file:   1. Keep the filename fixed, e.g., application.ico   2. Have the filename reflect the nature of the image, e.g., happyface.ico Option 1 doesn't say what the file is. It could give the illusion that two wildly different images are somehow different "versions" of the same thing. With option 2, I'd not only have to add a new file and delete the old one, I'd have to modify the resource file to reflect the new icon filename. On a related but different angle: A website with a header image. Is the filename header.jpg or sunrise-family- smiling.jpg? Should image file names reflect their function in the application or their content? What would be a best practice for this?


What's it like to program without eyesight?

At the urging of my father, I recently signed up for disability insurance. It got me wondering, if I were to become blind, what would it be like to write code without eyesight? An old question on Stack Overflow deals with the tools that are available, but I'm more interested in the experience, especially of someone who lost their vision after learning to program. I know that my own style is very visual: when writing code for the first time, I often write a big block of code, look it over to see what makes sense to split out, and then refactor it into separate functions by cut/paste. It seems like it would be hard to do that without _seeing_ the code. After learning to work with tools like a screen reader, is the experience basically the same? Or does it affect how you write code in a more substantial way?


Determining whether two binary search trees have the same set of values

This is an interview question: > Given two Binary Search Trees, write a program to determine whether they > contain the same set of values. Assume there are no duplicates. My idea is to perform an in-order traversal for both trees and compare each element one by one. It takes `O(n)` time and `O(n)` space. How could I do it in `O(lg(n))` time and `O(1)` space?


Finding subtree in a tree

I have a tree:                   a        / \       b   c      / \     d   f        / \        g   h      And the pattern:                   x        / \       y   z      / \     q   p      As output I would like to have:               x: a     y: b     z: c     q: d     p: f      and               x: b     y: f     z: c     q: g     p: h      Is there any algorithm I could look at?


How to write user stories for a framework API

I need help understanding what user stories should look like for a web testing framework we are building for our organization's QA department. We are trying to run this project using Scrum. The product will have 3 layers:   1. utility classes to make working with underlying web automation tool easier.   2. a page-object API layer which will allow our testers to write tests from the perspective of what services our web pages offer, instead from the perspective of the web automation tool.   3. a declarative layer, which will allow writing of tests in an English-type language--perhaps Cucumber-like scenarios. This layer will be mapped to the page-object API layer, so that if a test can't be performed declaratively, the test author can drop down into the page-object API layer. The end-user of this framework is our QA group who will be writing tests either at declarative level, or if they need to, the page-object API level. My question is what should our user stories look like? Currently we have stories that cover what the web automation should be able to do (ie. find elements on the page, wait for elements to appear), but that can't be right. Firstly, we could deliver this kind of stuff already by giving the QA group the underlying automation tool. These stories are clearly not worth demonstrating in a sprint review. Secondly, stories should indicate business value, which in this case is not in finding elements on a page, it's in:   * having tests based on an up-to-date, popular and effective web automation tool.   * having readable tests   * having the actual tests separated from the web automation tool which is driving them. Fine, but how do I break the product up into more specific user-stories?


Addition of double's is NOT Equal to Sum of the double as a whole

I am aware of the floating point errors as I had gained some knowledge with my question asked here in SE Floating Point Errors. What I am finding it difficult to understand is, the output of the following program.                       double d1 = 0 + 1.123 + 2.456;             double d2 = 3.579;                  float f1 = 0f + 1.123f + 2.456f;             float f2 = 3.579f;                  long l1 = (long)(0 + 1.123 + 2.456);             long l2 = (long)3.579;                  System.out.println(d1==d2);  // Output = false;             System.out.println(f1==f2);  // Output = true;             System.out.println(l1==l2);  // Output = true;      > Why is the output " **false" for double** and **not for float** , even when > float is single precision 32 bit and double is double precision 64 bit. > Oracle docs Any help with this would be highly appreciated.


What are some guidelines for submitting test cases with the code for an interview question?

I was interviewed by a big internet company. After describing the problem to solve, the interviewer requested that I also submit test cases with the code via email. I'm not sure if I should reveal the problem, but it was related to binary search trees. I wrote 4 test cases, varying from 0 to 10 nodes. I was rejected. What are some guidelines to writing test cases for interviews?   (How big a case do interviewers expect? How many cases do interviewers expect? etc.)


Catching an error?

Is catching an error with `try ... catch` a better practice than catching an error with proper analysis/error check? For instance, removing from an empty list: Does surround with a try catch clause considered as a more efficient way than testing if the list is empty beforehand?Or is it the same? Thanks. P.S: If a similar question was previously asked on the forum please feel free to refer it.


Tasks, jobs, activities, operations... which term to use when?

My application has a number of different asynchronous 'things' that it performs:   * There are things that fire off a schedule (every 5 minutes)   * There are things that are fired when a user clicks a button   * There are things that are triggered by an incoming web service call I use the terms like this:   * Scheduled things = Jobs   * User-triggered things = Tasks   * Web service-triggered things = Operations Tasks are quite complicated, so they're implemented using a hierarchy of different objects which I call Activities (operations and jobs may also begin to use these Activities as their building blocks). I feel like I might be using the wrong terms - for example, would you expect something that happens every 5 minutes automatically to be a Job or a Task? Is there an industry standard for this? All of the words seem to mean the same thing.


What programming/software sub-cultures exist? What defines them? Which do you belong to?

To the outside world, programmers, computer scientists, software engineers, and developers may all seem alike, but that's far from the case for the people who create software for a living. Any single programmer's ability and knowledge can range very widely, as well as their tools (OS, language, and yes, preferred editor), and that diversity spawns many sub-cultures in software - like programmers who actively use Stack Overflow and this site, versus many more who don't. I'm curious to hear from others what software sub-cultures they've encountered, belonged to, admired, disliked, or even created. For starters, I've encountered:   * **Microsoft-driven companies and developers** : their entire stack is from Redmond, WA. E-mail is Outlook is e-mail. The web is IE and IIS. They have large binders of their MS Developer Network subscription full of multiple versions of VB, .net, Visual Studio, etc. Avoids working with a shell/command-line. Don't see what the fuss with open-source and such is all about. MS-centric companies tend to be 9-5 and quite corporate (driven by business managers, not software people). Nowadays (given the wide availability of non-MS tools), this is the antithesis of hacker culture.   * **Old-school CS people** : they often know Lisp and Unix extremely well; sometimes, they may have written a semi-popular Lisp themselves, or a system utility. Few, if any, "software engineering" things are new to them, nor are they impressed by such. Know the references, history, and higher-level implications of programming languages like Lisp, C, Prolog, and Smalltalk. Can be bitter about AI outcomes of the 80's and 90's. Tend to be Emacs users. Can type out multi-line shell commands without blinking an eye. Their advice can by cryptic, but contains gold once understood.   * **New-school web developers** : played with computers and video games growing up, but often only really started programming in the late '90s or early '00's. Comfortable with 1 to 1.5 scripting/dynamic languages; think C and languages outside of Ruby/Perl/Python are unnecessary/magical. May have considered HTML as programming initially. Tend to get a Mac and be fanatical/irrational about it. Use frameworks more than build them. Often overly-enthusiastic about NoSQL and/or Ruby On Rails.   * **New-school CS** : lots of training in statistics, Bayesian models and inference; don't say "AI," say "machine learning." More Java than Lisp, but could also be expert Haskell programmers. Seeing major real-world successes by experts in their field (Google, finance/quants) often makes them (over) confident. But big data, and the distributed processing of such, really are changing the world. The examples above are by no means complete, correct, orthogonal, or objective. :) Just what I've seen personally, and provided to spark some discussion and outline of the broader question. Feel free to disagree!


Can a language support something like "Retry/Fix"?

I was just wondering if a language could support something like a Retry/Fix block? The answer to this question is probably the reason it's a bad idea or equivalent to something else, but the idea keeps popping into my head.               void F()     {       try       {         G();       }       fix(WrongNumber wn, out int x)       {          x = 1;       }     }          void G()     {       int x = 0;       retry<int>       {         if(x != 1) throw new WrongNumber(x);       }     }      After the fix block ran, the retry block would run again...


Abstract methods being used as static methods in java?

In an attempt to write some generic code I find myself putting, in my abstract class, a method that returns some static information about how the class should be treated. This method doesn't use any state data and would be static, except that static abstract methods aren't allowed. Is this a code smell? is there something one should do to avoid this? I haven't writtent he real code yet. Here is a quick example, conceptually. Little slopy programing wise to make to make it a quick read. basically a way for the code to return information to the model, in this case, about how it should be treated within the generic functions of the model. Assume the enum stored whatever configuration state in this case.               public abstract modelObject{              public abstract ModelGroup getModelGroup;              public final void addToModel(){             Model.store(this.getModelGroup, this);         }     }               public class myObject extends modelObject{         public ModelGroup getModelGroup(){             return ModelGroup.MyGroup;         }     }          public class DifferentClass extends ModelObject{         public ModelGroup getModelGroup(){             return ModelGroup.differentGroup;         }      }


How to react to wrong/not answered questions during interview?

Today I have held my first interview with potential interns. While this has been mostly open questions, I have had some trivial programming tasks for them:   * Write a function that returns true if triangle sides (all integers) a, b and c can represent a right triangle.   * FizzBuzz.   * Calculate the Nth element of Fibonacci using recursion (if they didn't know what Fibonacci was, I would even write them the definition F(n) = F(n-1) + F(n-2); F(1) = 1; F(0) = 1).    * Implement structure List for integer and write function to reverse it. These are obviously very easy tasks and I was not prepared for someone not to solve them. How should I act when they struggle with these questions? Should I give up the answer? Give tip by tip (I did that and ended up solving the problem myself)? Or just move on (or maybe just stop) with the interview? ps. By having problems with questions, I don't mean like having a bug, I mean if they can't even get started. This was a case with Fibonacci and List questions.


Why should I write all the Statements within Try-Catch?

My company head says that I must write all , i.e. ALL my code within Try-catch statements. Now, I can understand the 'better be safe than sorry' approach here, but isn't it too chicken-hearted to think that there will be an exception when the Labels are created, form's position is set. has there been instances where Exceptions in Such simple operations.


Inheritance vs composition in this example

I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments. In particular my example was Inheritance:               class Do:         def do(self):             self.doA()             self.doB()              def doA(self):             pass              def doB(self):             pass          class MyDo(Do):         def doA(self):             print("A")              def doB(self):             print("B")          x=MyDo()      vs Composition:               class Do:         def __init__(self, a, b):             self.a=a             self.b=b              def do(self):             self.a.do()             self.b.do()          x=Do(DoA(), DoB())      (Note for composition I'm missing code so it's not actually shorter) Can you name particular advantages of one or the other? I'm think of:   * composition is useful if you plan to reuse DoA() in another context   * inheritance seems easier; no additional references/variables/initialization   * method doA can access internal variable (be it a good or bad thing :) )   * inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object   * inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton   * ... _Basically I'd like to examine the implications of inheritance vs composition_. I heard often composition is prefered, but I'd like to understand that by example. Of course I can always start with one and refactor later to the other.


Change Management Standard

Is there any Change Management Standard which is widely accepted in software and other industries? I worked at several companies with absolutely different target domains (investment banking and telecommunications). Companies had very similar Global Change Management (GCM) organization and processes. More specifically:   1. There was **GCM department** responsible for all IT-related changes, such as company wide firewall changes, databases allocation/support, version control system support, etc.   2. There was such notion as **change freezes**. It was not possible to get my changes implemented if change implementation date was the same as change freeze date.   3. There was **GCM meeting** (conference call) when everybody discussed necessity and importance of their changes. It was hosted by GCM department representative every week at the same time (Tuesday, 17:00 GMT, for example).   4. Changes should have been approved by **Change approvers**. There were different kind of request which have their own list of mandatory approver groups. Groups had several members working at different time zones. At least one such member must have approved the GCM in order to have whole group approved the change. It was required that approves for all mandatory approver groups had been collected before scheduled implementation time came. Otherwise there was 100% guarantee that it will not be implemented.   5. **Bureaucracy** of GCM processes was remarkable. It was pure _bureaucratic hell_. Tools were awful, people slow and stubborn. It was nearly impossible to implement even minor changes. Sometimes I failed to get one last approve before implementation time or suddenly it turned out that implementation time is scheduled on the time of change freeze. I would like to have a look at it, so that I would have general understanding of GCM processes and how they work at different companies. I would like to know whether it is so _damn awful_ everywhere, or it was just poor GCM processes implementation at one specific company.


Designing a Technical Interview

The startup company that I'm employed at is looking to open an office overseas, and I've been tasked with coming up with some reasonable questions that will be used use to help find/hire some suitable candidates to kickstart the new office. We are primarily looking for Android and iPhone developers, as well as a couple of team-leaders (preferably with Android/iPhone experience). However, I'm really not a fan of using domain-specific questions as part of the interviewing process, so I'd very much like to avoid quizzing people about `CoreData` or `Activity`'s or other platform-specific aspects. Instead I prefer Google's general approach of looking for people with solid knowledge of CS fundamentals. With that in mind I've drafted up the following set of questions, and was hoping to get a bit of a peer review: **Language Agnostic Questions** (A candidate is expected to do well on _all_ of these)   1. Write a function that will convert a string to a double without calling any built-in utilities such as Double.parseDouble() or atof() or similar methods. You can assume that you input will always be well-formed, will always include a decimal point, and will always include at least one digit after the decimal point. You can implement your solution in the language of your choice, or using pseudo-code if you prefer. Java template: http://ideone.com/clone/y2Q6S   Objective-C template: http://ideone.com/clone/JcOR5 Free hint: To convert from a character to its integer value, you can do:              int charValue = character - '0';        2. Write a function that will reverse a given string. You can assume that you input will not be null or empty. You can implement your solution in the language of your choice, or using pseudo-code if you prefer (This is a basic sanity-check type question. Any engineer with any sort of expreience should be able to come up with some bit of code that reverses a string. If they can't then that should be an indicator that they are not very good at all.). Part 2: Write a function that uses the function you implemented above to test whether or not a given string is a palindrome (the same forwards as backwards). Java template: http://ideone.com/clone/36BlH   Objective-C template: http://ideone.com/clone/GZbha   3. You are reviewing the following code snippet submitted by a fellow engineer:              long fct(long n) {         int q;         int r = 1;              while (n != 1); {             r *= n;             n--;         }              return r;     }      What feedback would you give them? Are there any errors in this code? If so, what are they, and can you provide some test-cases that will highlight them? **Language Specific Questions** (A candidate is expected to do well on _at least one_ of these)   1. Consider the following Java code snippet:              public static synchronized int add(int num1, int num2) {         return num1 + num2;     }          public synchronized int add2(int num1, int num2) {         return num1 + num2;     }          public int add3(int num1, int num2) {         synchronized(this) {             return num1 + num2;         }     }      What is the difference between each method? Is one style preferred over the others? If so, which one, and why? What are the pros and cons of each style presented?   2. Consider the following Objective-C code:              @interface TestObj : NSObject {         NSString* string1;     }          @property(nonatomic, assign) NSString* string2;     @property(nonatomic, retain) NSString* string3;     @end               @implementation TestObj          @synthesize string2, string3;          - (void) processStrings {         string1 = @"A new string";         string2 = [[[NSString alloc] initWithString:@"String 2"] autorelease];         self.string3 = [[NSString alloc] initWithString:@"String 3"];              [string1 release];         [string2 release];         [string3 release];         self.string2 = nil;         string3 = nil;     }     @end      What is the difference between string1, string2, and string3? Are there any problems with the way the strings are used in the processStrings method? If so, what are they, and how would you fix them? For people who do well on these questions I also have a set of open-ended discussion questions that aren't posted here and which deal with things like complexity analysis, algorithms, hashing, optimization, and similar topics. I've used the open-ended questions on a number of candidates already and know that they do a good job of separating the talented engineers from the not so good ones. Anyways, does that all seem reasonable?


Setting permissions issue for admins and lower users in project

I am working in a jsp project an got stuck in a big problem. My project consist of accounts table for super admin, reseller, admin and users for executives and manager mapped in the account **Permission** **Super admin can see or add details of reseller, admin, executives and manager, and edit its own account** **Reseller can see or add details of admin,executives and manager ,and edit its own account but unable to create reseller** **Admin can see or add details of executives and manager ,and can see or edit its own account but unable to create admin** **Executives can see only his details and edit it** So the highest priority is for super admin account which have access of everyone,then comes reseller account which have access to the admin account and lower account that he created,then admin account can access manager and executives users ,then manager user can access executives and then executive can see only his information I have accounts and users table,Accounts can be super admin, reseller, and admin they all have an account_id and users are manager and executives which has a user_id My problem is that how to do that ,how to map these id because reseller have account_id and can add account id ( admin) so to fetch details of reseller i have to also fetch details of lower admin account In the same way for every type of account or user which login i have to apply a different sql query For ex if i have an extra table of call-details which have details on which user(user_id) receive call and which account(account_id) the user is mapped so i have to apply different sql query for different accounts and users login like for super-admin `select * from call-details` for reseller `select * from call-details` of reseller and call-details of account associated with it for admin `select * from call-details` where call receive on that account. and so on and i have more table and more pages then it is very difficult to apply this approach. Is there any approach by which i can solve this problem with a less difficult way. I tried my best to explain my problem please ask again if you have any doubts understanding my problem. Any help would be appreciated.


I've taken a job where there is no work to do!

This is related to the (closed) question New job - not got any work to do. I'm a week and a half into a brand new job and despite asking for work to do I keep being brushed off. The set-up here is just an aggregate of of services, which are then provided to the outside world, so any bugs that do occur are usuaully with the service provider so as far as I can tell there's very little to do. In my first week a contractor actually quit (after a month of just sitting there) and a co-worker (6 weeks in) was discussing leaving, am I destined to go the same way? I moved cities for this job, and would hate to think of the impact on my cv of a short stint at a big company - may look like I can't 'hack' it to future employers?


How often do you review and validate your practices/process?

We currently drive changes to our process through the following mechanisms:   * Weekly wrap-up meeting   * Project postmortem  We discuss what isn't working, what is working, etc. I use these settings to introduce new practices, and eliminate ones that aren't working. We usually only make 1 change at a time and try it for 2 weeks to a month. To validate our change we look at:   * our velocity and std. deviation (work accomplished week over week)   * dialectic   * our opinion/perception of the practices effect and effectiveness Those practices which seem to work for us we keep. Everything else is removed. This has worked pretty well for us, but I'm always interested in better ways to do this. **How often/When do you review you development process?** **How do you validate the changes in your process are effective?**


How do I create single object that changes functionality based on programmer input?

I have several classes that all behave according to one interface. But in each class there are additional functions defined that give each class slightly different behavior. What I want to do is have th programmer using this API to simply create one instance based on some parameter which generates the correct class type. And then he/she would only see the methods available to that type while programming So for example My interface               interface IChange     {         string Change(string inputString);     }      And say I have two classes that implement this interface               class Changer1 : IChange     {            public string Change(string input){            ...       }            public void DoSomethingSpecial1(){            ///code that does something specific to Changer1 class       }          }          class Changer2 : IChange{            public string Change(string input){            ...       }            public void DoSomethingSpecial2(){            ///code that does something specific to Changer2 class       }               }      Then I would have a wrapper that sets the appropriate Changer based on an enumeration or some other user input.               public enum ChangerType     {         Type1,         Type2     }          class MasterObject{                  public MasterObject(ChangerType type)             {                 if (type == ChangerType.Type1)                     SetChanger(new Changer1());                 if (type == ChangerType.Type2)                     SetChanger(new Changer2());             }                  private IChange _change;                  private void SetChanger(IChange change)             {                 this._change = change;             }               }      Then as a user of this, in my main program I want to do something like the following where the user creates the main object but it gets created in such a way that they only have access to the appropriate functions. I.e. Have available only DoSomethingSpecial1 or only DoSomethingSpecial2 based on the type you created.               class Program     {         static void Main(string[] args)         {             MasterObject obj1 = new MasterObject(ChangerType.Type1);             obj1.DoSomethingSpecial1();             string result1 = obj1.Change("test");                  /// OR                  MasterObject obj2 = new MasterObject(ChangerType.Type2);             obj2.DoSomethingSpecial2();             string result2 = obj2.Change("test");              }          }      I have a feeling this is Factory type pattern or maybe Abstract factory, but I'm not sure how to fix my code to implement it correctly.


Which areas( I.T.) are mostly affected by Outsourcing?

My parents complain about me choosing a career in IT instead of business since most companies outsource IT nowadays. I always thought IT/Desktop supports are the ones who got outsourced, but it seems programmers are being outsourced to India as well. I need to choose the most secure area (less affected by outsourcing) in order to convince my parents. Which areas in IT are mostly affected by outsourcing?


Is there a way to use a higher level language in a competition that only has C, C++ and Java by default?

On that competition, you gain access to a system with gcc, vim, emacs and Java. You can't take any file with you and there's no internet access, but you can do whatever you want inside that system. You're presented a set of problems and have some ours to send the results. I wonder if there's any way I can hack a higher level language into it? Maybe there's something useful hidden within Java default libs, or linux? Or maybe I can take a paper (not illegal) and type a compressed lightweight JS/Scheme/Clojure/Whatever interpretator and running it? Or anything really. Ideas?


GitHub access to repo: only with URL?

I'm finishing my dissertation and want/need to provide the source code of some analysis scripts I've used. I did all the version control with `git`. Because I want to publish the results generated with these scripts, I don't want to just put them in a public repository on GitHub. Is it possible to provide an "URL-only" access to a GitHub repo, meaning it is not publicly listed but only visible to persons who have the URL? If not with GitHub, is this possible with another service? I would like to have some kind of GUI to see the code, which is why I don't want to make a zip file with just the source code in it. Edit: To make that point more clear: There should not be any login or registration involved! Type in the URL printed in the dissertation and boom, there's the source code!


Example of an open source project using Spring

I'm trying to learn a bit about the Spring framework and I'm wondering if anyone can recommend an open source project using it so that I can have a look through the source. Any other recommendations around learning Spring would be helpful too.


why use a form object when you can get needed data from view object's html?

I am working with server side code. I have a request object that handles request data validation and filtering. I have a view object that uses template files to generate html for output. the template files are mostly html. you can put one view object inside of another view object in order to assemble a page piece by peice. for instance you might have a page layout view, and you might put a form view inside the page layout view. One of the features of the request object is that it can automatically build validations using an html5 string containing a form. It parses the html string and grabs input types and other tag attributes that determine HTML5 validation, then matches this validation server side. I get this html string from a view object. This way no matter what the designer puts in the view's template file, it will automatically get validated according to the html5 attributes server side. i create and use the same view that was originally used to generate the page, to build validations for the request when the page is then submitted back to the server. I would like to get feedback on this idea. Pros/Cons/Other Concerns.


Why does Donald Knuth write TAOCP using assembly language?

I don't hate using assembly language, since I have written some in my os course. But obviously, assembly language lacks abstraction, you have to pay more attention to the details. Is assembly language really essential to write TAOCP?


What is the convention regarding class names that may already exist in the ORM?

This is a generic question about class names and ORMs, but for context; I'm working on a Flask web app in Python using SQLalchemy. I'm struggling with naming a new class that will contain the business logic to process reminders. In the database there is a table named "reminders" that contains data I need. The ORM has created a class 'Reminders' to access it. Of course, for the business-logic class, the only good name I can think of is also "Reminders", but as I said, there already is a class with that name in my models. I was thinking this could potentially lead to confusion. My question is; is this still the way to go, two different classes with the same name (but with a different path), or is there a better way/convention to tackle this? PS: There is one limitation on what I can do; the database is legacy and used by other software, so renaming the table would be 'problematic' at best.