Login to a Web App using PKI Certs

I understand PKI reasonably well from a conceptual point of view - i.e. private keys/public keys - the math behind them, use of hash & encryption to sign a certificate, Digital Signing of Transactions or Documents etc. I have also worked on projects where openssl C libraries were used with certs for securing communication and authentication. I am also extremely familiar with openssl command line tools. However, I have very little experience with web based PKI enabled projects & hence I am trying to design and code a personal project for understanding this better. ## The requirements This is the website for a bank. All Internet Banking users are allowed use any certificate issued by a few known CAs (verisign, Thawte, entrust etc). The Bank is not responsible for procuring certificates for the user. These certificates will be used for authentication to the banks website either instead of or as an add-on to username/password login. The platforms/OS etc are still not fixed. Assume that enrollment has been done - i.e. bank knows the certificate going to be used by each user. ## Design I was wondering what's the best way to do authentication?   1. I saw that Apache has a way to enable 2 way ssl - in this case, i think navigating to the website would automatically ask for a cert from the user. But I am not sure if this is enough because it seems that all it verifies is whether a certificate is signed by a trusted CA & also may be whether it falls in a white list of subject lines of the certificates etc. But this is not enough for a bank case because you need to be able to associate a bankuserid with a certificate.   2. IIS seems to have a way by which I can have a certificate stored for each user in Active Directory. This is what I understood from reading few MSDN articles. You turn on 2 way SSL in IIS & then when the user tries to navigate to the website, IIS will send a request to the browser with a list of approved CAs and browser will let the user pick an appropriate certificate from his certstore and sends it to backend. I am assuming that IIS will do 2 things     * Ensure that the user has the private key corresponding to the cert (by under the cover negotiations)     * Based on the AD User-Cert Mapping, IIS will report the username to the application.   3. Do the authentication explicity by calling crypto functions rather depending on depending on the webserver to do it.     * Show a user screen where he uploads a certificate and the application ensures the user has the private key corresponding to the cert (by asking the front-end to sign some string using the cert).     * The application has a database some of data is stored which allows each user to be mapped to his userid. This may be      * the whole cert corresponding to each userid     * the CA and cert serial number corresponding to each user id. I was wondering which is the commonly used method? What are the best practices? If I should go with #3, what are the best ways to do this?


Adding explicit interfaces to Legacy managed C++ code

I have a bit of a challenge and I am not sure how to approach this. We have a very very large project (that is about 5 years old). The code base is HUGE so a full refactor is out of the question. What we will be doing is refactoring bits of code as we use those parts (this is backend code, which we will be using on a frontend system) The existing code has got zero abstraction, and we want to build unit tests for it. We use the RhinoMock framework and the call from my superiors are that we need to add explicit interfaces to the code, thereby abstracting it so that we can mock the objects in RhinoMock. I have one broader and one narrower question: 1) Is an explicit interface the best option? Or should I suggest some other technique... 2) Can anyone suggest a high-level approach to this type of code refactoring? I've never been in a position where I have had to add explicit interfaces to existing code. (The legacy code is Managed C++ by the way) Thanks in advance for your answers. Also, if this question is in the wrong place or too broad, I do apologize.


Is it more efficient to learn as you go along with a project or to develop a broad base of programming skill?

For example, let's say I want to build a game, and I have a limited knowledge of programming(some but definitely not enough). Should my first move be to design the game and then learn how to implement each separate part? Or should you learn a language really well before you design a game?


Static Analysis tools to detect architectural patterns

Currently for school we are working on a research project. The central question of this project is: Which architectural patterns can be detected using static code analysis? With architectural pattern is meant the architectural patterns from the book: Patterns of Enterprise Application Architecture written by Martin Fowler. During our literature research we didn't find any studies/articals/journals that adress this problem. So for our approach for this rpoject we where thinking to create a prototype of this kind of tool. But first we have to know if there are any (open-source)tools with the same functionality?(detect architectural patterns with a static code analysis) So my question is do you know a tool that kind detect architectural patterns? We know of the existence of tools that can detect design patterns of the Gang of Four. And do you have any suggestions for our approach? Thanks in advance


Where can I go to have a sample select2perform test taken?

I did a quick search before asking and it brought up this: Where are sample Select2Perform test questions? I'm looking to take a sample Java exam, but the above topic doesn't mention a resource I could go to - just that somebody had taken the C++ version. If anybody could help, that'd be great.


Regexp or custom parsing algo?

I was trying to parse a java properties file to avoid some Properties loading pitfalls (non ordering, loss of comments). (Property are of the form 'key = value' where the value can span on multiple lines using the \ special char) I have tried to get the right regexp to parse the properties but after I gave up after fighting for more than one hour. (a version for groovy found here:   `~ /^([^#=].*?)=(.+)$/)` I manage to write the same thing using a single loop and very trivial code in 5 minutes... I'm an average programmer when dealing with regexp: I have to re-read the doc each time I want to use them and advanced feature are still obscure for me. Often when dealing with regexp I have the feeling that some very skilled developers can produce/decipher very elaborated regexp in seconds, but others have trouble to handle them. Question: should I take time to deeply learn regexp and produce cryptic and powerful parser, or should I keep using some ugly easy to debug/understand parsing algo ?


Is it Ok if Domain Object cross Service Boundary

Is it Ok if Domain Object cross Service-Boundary? Everyone recommend that only DTO should be returned by Services. I am creating simple CRUD application. Is it ok if my service methods return Domain object instead of flat DTO objects. It will save me from lots of mapping related setup. Is there any alternative approach?


exclamation points in error messages

What do you think about using exclamation points in error messages? i.e. "The address is not valid!". Personally, I think it adds nothing, insults the user, and makes the product look like it was written in TRS-80 BASIC by a 12-year-old.


Executing user configuration settings

For an API I'm building what it does is load an XML file that is passed to it as a string, drill to the correct element, modify values, and return the modified XML. I'm doing something like this in my code               if (valid)     {         XDocument docRoot = XDocument.Parse(XMLstring);              var node1 = docRoot.Descendants(namespace + @"node1");              foreach (var result in node1)          {             var child1 = result.Descendants(ns + "child1");                  var test = child1.First();             test.SetValue(Transform(test.Value));         }                   //return the transformed XML          }     else { }      Now I want to create a configuration file in XML format that allows user to specify which nodes in the XML to modify and what modification to perform, (later I want to make use of this in a GUI) so something like               <root Value="">         <Modify Xpath="\parent\child1\superchild\" Attribute="" Mode="delete" />         <Modify Xpath="\parent\child2\" Attribute="Value" Mode="multiply" />     </root>      And I have these two pieces but don't know how to connect them together. I think I have to make a class from my XML configuration file and somehow map those to the values in the other XML.


Is it still worth learning desktop gui development?

For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...). I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT. I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant? Also, do you expect developers you work with to have desktop gui expertise?


Why does automated testing keep failing in my company?

We have tried to introduce developer automated testing several times at my company. Our QA team uses Selenium to automate UI tests, but I always wanted to introduce unit tests and integration tests. In the past, each time we tried it, everyone got excited for the first month or two. Then, several months in, people simply stop doing it. A few observations and questions:   1. **Does automated testing actually work?** Most of of my colleagues who used to work at other companies have tried and failed to implement an automated testing strategy. I still haven't seen a real-life software company that actually uses it and doesn't just talk about it. So many developers see automated testing as something that is great in theory but doesn't work in reality. Our business team would love developers to do it even at a cost of 30% extra time (at least they say so). But developers are skeptics.   2. **No one really knows how to properly do automated testing.** Yes we have all read the unit testing examples on the internet, but using them for a big project is something else altogether. The main culprit is mocking/stubbing the database or anything else that is non-trivial. You end up spending more time mocking than writing actual tests. Then when it starts taking longer to write tests than code, that's when you give up.   3. Are there any good **examples** of unit tests/system integration tests used in a complex data centric web applications? Any open source projects? Our application is data centric but also has plenty of domain logic. I tried the repository approach at some point and found it pretty good for unit testing, but it came at the price of being able to optimize data access easily and it added another layer of complexity. We have a big project undertaken by 20 experienced developers. This would seem to be an ideal environment to introduce unit testing/integration testing. Why doesn't it work for us? How did you make it work at your company?


ASP.Net or WPF(C#)?

Our team is divided on this and I wanted to get some third-party opinions. We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased. Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity. Application Details:   * I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.   * We are looking to use two-way communication for reminder and event systems   * Currently has to support around 100 users, although we've been told to allow for growth up to 500 users   * We have multiple locations Items to consider (maybe not initially in some cases but in future releases):   * Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)   * Keyboard navigation   * Performance is a must   * Production Speed to initial version   * Low maintenance overhead   * Future support   * Softphone/Scanner integration Our Developers:   * We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.   * We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.   * There is me, who has worked with both and am comfortable in either   * We have an outside company doing the project management, and they are an ASP.Net company.   * We plan on hiring 1-2 others, however we need to know what direction we are going in first Environment:   * General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.   * Other locations connects to our network over a MPLS connection Based on that, what would you choose and why? I am asking here instead of SO because I am looking for opinions and not answers


Which do you code first, MVC?

I have been coding for a good bit, and I found a project I want to work on -- a python web app using django + mongodb. I know what I want my web app to do. When you are in this circumstance (just starting a brand new project) where do you start? What do you code first? Do you code the views first? Hope this hasn't been asked before (I did a quick look), but I could use some general direction.


Only functions without a class in cpp file! good design or not?

When I was going through the project on which I am working, I came across a cpp file, which has only functions and static variables.I was wondering why they have not put everything into a class! Whenever the inside functions have to be called, the cpp file is included. Is this a good design? what are the pros and cons of these type of design? for ex.               //independent.cpp     #include "someclass.h"     static int var1;     static someclass object("hello");     static bool var2;          void foo(const char* dir, const char* filename){     ...     }          somefile.cpp     #include "independent.cpp"     class sample{     public:       void caller(){       foo("c:\", "file.txt");       }     }


What is a good overview of options for access controls/permissions?

I'm in the process of designing the access control portion of a moderately complex application, but I feel like I'm re-discovering a lot of wheels. Does there exist a good overview of the "access control" domain, including terminology, discussion of the tradeoffs of different schemes (RBAC, ACL, ???), how it interacts with business policy ("Alice can only access the coffee machine before 11:30"), and possibly implementation suggestions? Sorry if this question is a bit vague. I'm still in the "I sort of know what I want to accomplish, but I don't know very much about the domain or terminology".


First ATMs programming language

First ATMs performed tasks like a cash dispenser, they were offline machines which worked with punch cards impregnated with Carbon and a 6-digit PIN code. Maximum withdrawal with a card was 10 pounds and each one was a one-time use card - ATM swallowed cards! The first ATM was installed in London in the year 1967, as I looked at time line of programming languages, there were many programming languages made before that decade. I don't know about the hardware neither, but in which programming language it was written? (also which hardwares were used?) _*I didn't find a detailed biography of John Shepherd-Barron (ATM inventor at 70s)_ **_Update_** I found this picture, which is taken from a newspaper back to the year 1972 in Iran. ![enter image description here](http://i.stack.imgur.com/eIQj8.jpg) **_Translated PS_** : > Shows Mr. Rad-lon _(if spelled correctly)_ , The manager of Barros _(if > spelled correctly)_ International Educational Institute in United Kingdom at > the right, and Mr. Jim Sutherland - Expert of Computer Kiosks. In the rest of the text I found on this paper, these kind of ATMs which called "Automated Computer Kiosk" were advertised with this: > Mr. Rad-lon _(if spelled correctly)_ puts his card to one specific location > of Automated Computer Kiosk and after 10 seconds he withdraws his cash. Two more questions are: **1-** How those ATMs were so fast? (withdrawal in 10 seconds in that year) **2-** I didn't find any text on Internet which state about "Automated Computer Kiosk", Is it valid or were they being called _Computer_ in that time?


Calling static method from instance of class

As a developer I am fan of static methods. Recently I come across difference between OOP languages about this static methods. All OOP language use static method to access any method without creating instance of than class. So we can call this kind of method with just class name. But some language allow to access static method from instance variable also like Java and some don't like Objective - C. So what is the reason of this kind of difference between two OOP language? Which is correct OOP behaviour? I am just curious to know this.


Algorithmic Forecasting and Pattern Recognition

Say a user could enter project data into my software. Each project has 2 variables "size" and "work" and they're related but the relationship is not known. Is there a way to programmatically determine the relationship between the variables based on previous data and forecast the amount of work provided if only given the size of the project in the future? For Example, say the user had manually entered the following projects.   * Project 1 - Size:1, Work: 4    * Project 2 - Size:2, Work: 7   * Project 3 - Size:3, Work: 10   * Project 4 - Size:4, Work: x What should I look into to be able to programmatically determine, that Work = Size*3+1 and therefor be able to say that x=13?


Ajax call or js to update a cart price

I am building a cart in Java and would like to give users the ability to update the quantity and see the new price instantly. I am using _BigDecimal_ on the back-end for complete accuracy, but the ajax call introduces a slight delay. It isn't much but I could make the update instant by sending the update to the server and just updating the price in Javascript before it even returns. The speed would be wonderful but it comes at the expense of rounding errors being presented to the user. Now the back-end computed price would be the one shown on the payment page so that would be accurate at least but is the speed worth the risk of a bad value showing in the cart in an eCommerce system?


JavaScript Print Formatting

I'm learning NodeJS and rewriting some code to see how it compares. For one script, I am trying to take dates in the form of strings and turn them into JavaScript Date objects to perform calculations on. I managed to do this, by converting the string into an array and processing each character. It looks so ugly though, I'm wondering if there is a cleaner way, like the equivalent to sprintf or something. I'm sure I can find a module but am wondering if there is a native way in JS. This is what I have:               var a = '081320141900'.split('');     creationDate = a[0] + a[1] + "/" + a[2] + a[3] + "/" + a[4] + a[5] + a[6] + a[7] + " " + a[8] + a[9] + ":" + a[10] + a[11];     console.log('Creation Date: ' + creationDate);      Output:               Creation Date: 08/13/2014 19:00      Again, the above works fine, just wondering if this can be done cleaner.


Is there a point to including a "change log" in every code file when you are using version control?

I was under the impression that a version control system eliminated the need to have "change logs" plastered everywhere in the code. I've often seen the continued use of change logs, including big long blocks at the start of stored procedures with a big section blocked out for changes to the file and littering the code with things like:               // 2011-06-14 (John Smith) Change XYZ to ABC to fix Bug #999      and:               // 2009-95-12 (Bob Jones) Extracted this code to Class Foo      // <commented-out code here>      The reason for this, as it was explained to me, is that it takes too long to sift through our VCS logs trying to find who changed what and why, while having it in the code file itself, either at the top or near the relevant change, makes it easy to see who changed what and when. While I see the point of that, it seems redundant and just kind of smacks of "Eh we don't really understand how to use our VCS properly, so we won't bother with that stuff at all." What do you think? Do you use both comments and the log? Just the log? Do you find that it's easier to code when you can see above a block of code that John Smith changed the method to check for XYZ a week ago, instead of having to search through logs and compare code files in a Diff tool? EDIT: Using SVN, but basically only as a repository. No branches, no merges, nothing except log + storage.


How to use ViewModels in a layered architecture?

I've got a Java application that is using a layered architecture, we have: presentation layer, business layer and data access layer. Our business layer uses the models to process the "requests". We are using the concept of "ViewModel", so every View-Action relation has its View. What is happening is that we have a lot of ViewModels. The number of files are kind of confusing but the real problem is that we are facing a name conflict problem. This raised some questions:   1. In this case we are using ViewModels in a layered architecture. Is this approach OK?   2. Is it normal to face a high number of files?   3. Is there any naming convention you use to make it clear to which View the model "belong" to?   4. If a model is exactly the same for two views, should they be shared or should I have two different models that have exactly the same content?


Tag an image in various places, and save to database

Id like to create something similar to what you see here... http://www.houzz.com/ideabooks/9424693/list/8-Beautiful-Ways-to-Work-Glass- Into-Your-Kitchen-Cabinets If you click on the second photo down, youll notice it has a bunch of tags, linking to actual products, or just descriptions of products. Is this done using HTML5 canvas overlayed onto the photo?   Or what would be the most efficient way to implement this?? I have a list of 1,000,000 products that the user will be able to tag. I wanna link the two, so that as he tags, it saves to a database, and then anyone else viewing his room, can come in and click a link, to go to that product. Thanks


How to measure algorithm accuracy?

I have a few optimization algorithms (for finding function minimum) and I'd like to check how good they are. Suppose I build test cases and compare the actual results to theoretical ones. What measures should I use to estimate if the function minimum was actually found? I thought about:   * mean number of function evaluations (± standard deviation)   * success rate (how often it actually finds minimum) Are there any others that I have missed (let's say algorithm finishes 1e-4 from known solution. so is it success already or not?) Edit: My main concern is **not** time complexity. It is algorithm accuracy in cases when exact solution might never be found (eg. multidimensional solution spaces). How do I calculate the rate of convergence?


Odd company release cycle: Go Distributed Source Control?

Sorry about this long post, but I think it is worth it. I have just started with a small .NET shop that operates quite a bit differently to other places that I have worked. Unlike any of my previous positions, the software written here is targeted at multiple customers and not every customer gets the latest release of the software at the same time. As such, there is no "current production version." When a customer does get an update, they also get all of the features added to the software since their last update, which could be a long time ago. The software is highly configurable and features can be turned on and off: so called "feature toggles." Release cycles are very tight here, in fact they are not on a schedule: when a feature is complete the software is deployed to the relevant customer. The team only last year moved from Visual Source Safe to Team Foundation Server. The problem is they still use TFS as if it were VSS and enforce Checkout locks on a single code branch. Whenever a bug fix gets put out into the field (even for a single customer) they simply build whatever is in TFS, test the bug was fixed and deploy to the customer! (Myself coming from a pharma and medical devices software background this is unbelievable!). The result is that half baked dev code gets put into production without being even tested. Bugs are always slipping into release builds, but often a customer who just got a build will not see these bugs if they don't use the feature the bug is in. The director knows this is a problem as the company is starting to grow all of a sudden with some big clients coming on board and more smaller ones. I have been asked to look at source control options in order to eliminate deploying of buggy or unfinished code but to not sacrifice the somewhat asynchronous nature of the teams releases. I have used VSS, TFS, SVN and Bazaar in my career, but TFS is where most of my experience has been. Previously most teams I have worked with use a two or three branch solution of Dev-Test-Prod, where for a month developers work directly in Dev and then changes are merged to Test then Prod, or promoted "when its done" rather than on a fixed cycle. Automated builds were used, using either Cruise Control or Team Build. In my previous job Bazaar was used sitting on top of SVN: devs worked in their own small feature branches then pushed their changes to SVN (which was tied into TeamCity). This was nice in that it was easy to isolate changes and share them with other peoples branches. With both of these models there was a central dev and prod (and sometimes test) branch through which code was pushed (and labels were used to mark builds in prod from which releases were made...and these were made into branches for bug fixes to releases and merged back to dev). This doesn't really suit the way of working here, however: there is no order to when various features will be released, they get pushed when they are complete. With this requirement the "continuous integration" approach as I see it breaks down. To get a new feature out with continuous integration it has to be pushed via dev-test-prod and that will capture any unfinished work in dev. I am thinking that to overcome this we should go down a heavily feature branched model with NO dev-test-prod branches, rather the source should exist as a series of feature branches which when development work is complete are locked, tested, fixed, locked, tested and then released. Other feature branches can grab changes from other branches when they need/want, so eventually all changes get absorbed into everyone elses. This fits very much down a pure Bazaar model from what I experienced at my last job. As flexible as this sounds it just seems odd to not have a dev trunk or prod branch somewhere, and I am worried about branches forking never to re- integrate, or small late changes made that never get pulled across to other branches and developers complaining about merge disasters... What are peoples thoughts on this? A second final question: I am somewhat confused about the exact definition of distributed source control: some people seem to suggest it is about just not having a central repository like TFS or SVN, some say it is about being disconnected (SVN is 90% disconnected and TFS has a perfectly functional offline mode) and others say it is about Feature Branching and ease of merging between branches with no parent-child relationship (TFS also has baseless merging!). Perhaps this is a second question!


Advantages of using business logic in model

In an MVC framework i have often heard that use business logic in a model. But i think using the business logic in controller would run faster as view is directly connected to controller. I want to know what are the advantages of using a business logic in model?


Which one is a better practice a static factory method of the same class or a separate factory class with methods?

I have seen this at many places. a Parent class has a static method to create objects of the right subclass and at times we have a dedicated factory class with instance methods to create object of various subclasses. Which one is used in which scenario ? Like static factory methods of InetAddress in java.net to create subclasses of InetAddress Vs BorderFactory class to create various Borders.


Software licenses in practice

Almost all questions and information on both SO and "Google" describes how different licenses works and what license to choose for your work? **But how do they work in reality.** Almost everyone I have spoken to have vastly different thoughts of how they work, including hard core open source developers that gladly share their libs and consultants who is only interested in money and would never reveal their libs. First I will give my impression of how they work in practice with three questions / statements and you can agree or disagree with me on those.   1. Lets say I make a large application and have a small portion of that from GPL code, then the copyright holder can't do much about it as it's deemed non essential code for my application and thereby the "law" rules over the GPL?   2. If the code is generic the copyright doesn't hold. For example if I make a tutorial on how to set up a chess engine no one have to care about my license. That's because my code is mechanical in nature.   3. If I use a lot of GPL code that is essential for my application and don't disclose it and someone finds out, my "punishment" will be to release all my source code, large companies are terrified by this.   But for a small hobby developer this isn't much of an issue as the software wouldn't be written at all or would be open sourced from the start anyway? I don't like this approach personally because I find it unethical and disrespectful to the original author. **EDIT:** Clarified as a comment made was that I din't ask a question. My question is are the 3 statements correct.


Is there a better way to design these classes?

I have two business classes: TimesheetDay and TimeSlot. One TimesheetDay can have one or more TimeSlots. The TimesheetDay and TimeSlot classes will be dependent on an object that implements a corresponding TimesheetDayData and TimeSlotData interface. That way, I can write data classes to map the objects to a MySQL database, but if I use another way to store the data in the future, I can inject objects from a different dataclass. These objects will not create other objects, and I refuse to use the "new" keyword in them. I want them to be testable in complete isolation. For example, I instantiate a TimesheetDay object like this (in a container):               $mTimesheetDayData = new TimesheetDayMysqlData($databaseHost, $timesheetDayId);     $mTimesheetDay = new TimesheetDay($mTimesheetDayData);      TimeSlot objects will be constructed the same way:               $mTimeSlotData = new TimeSlotMySqlData($databaseHost, $timeSlotId);     $mTimeSlot = new TimeSlot($mTimeSlotData);      My problem lies in getting TimeSlot objects that the TimesheetDay contains. I can't have the TimesheetDay class creating objects. Otherwise, I might write a method that returns an array of TimeSlot objects, something like:               $timeSlotsForThatDay = array();     $timeSlotsForThatDay = $mTimesheetDay->getTimeSlots();      But, that would require the method getTimeSlots() to create objects. How would you handle this?


Recommend self-talk logger software or technique

I observed that discussing with your self about a problem is a fairly common practice. I find it is even better to write what you think. Not only it forces you to materialize your problem, but the written material can serve you as a log for future reference. I have been trying different ways to log my self chatter, I created a gtalk account to whom I would talk to. But I found that this way I would ways have to set a lot of context before going to the problem. Made a small script where I would just append a text, properly dated, into the end of a journal file in the current working directory. By being in the project directory I would set part of the context I was in, and it would even leave some information to project contributors. I started to like this method, and I was about to improve over my script, but then I thought that maybe this is a solved problem. Some people like to blog. I tried that, but post are generally a synthesis of the whole story, and most of the time I would forget pieces that were relevant. I could be more atomic. Tweeter would seem a better fit for it, but then it falls into the context argument I described above. I thoughts? tweet


What is appropriate way for managing MySQL connection through C#

My question, at the bottom line, is what is the appropriate(best) way to manage our connection towards MySQL db with C#. Well, currently I'm working on some C# (winforms type) <-> MySQL application and I've been looking at Server Connections in MySQL Administrator, been witness of execution of my mysql_queries, connection opens an closes, ... an so on! In my C# code I'm working like this and this is an example:               public void InsertInto(string qs_insert)             {                 try                 {                     conn = new MySqlConnection(cs);                     conn.Open();                          cmd = new MySqlCommand();                     cmd.Connection = conn;                     cmd.CommandText = qs_insert;                     cmd.ExecuteNonQuery();                 }                 catch (MySqlException ex)                 {                     MessageBox.Show(ex.ToString());                 }                 finally                 {                     if (conn != null)                     {                         conn.Close();                     }                 }             }      Meaning, every time I want to insert something in db table I call this table and pass insert query string to this method. Connection is established, opened, query executed, connection closed. So, we could conclude that this is the way I manage MySQL connection. For me and my point of view, currently, this works and its enough for my requirements. Well, you have Java & Hibernate, C# & Entity Framework and I'm doing this :-/ and it's confusing me. Should I use MySQL with Entity Framework? What is the best way for collaboration between C# and MySQL? I don't want to worry about is connection that I've opened closed, can that same connection be faster, ...


How should standards and process improvements be introduced to an organization without them?

I've been tasked with improving the software development process through the implementation of process improvements, of which we will most likely be using CMMI for Development, Version 1.3 as a guideline and adopting the best practices in whole or in part. What is the best way to introduce standards and process improvements so that the degree of push back and resistance from developers is minimized?


Declarative input language strategies

I need to develop a simple declarative language to drive an application. I have various computational modules, some of them depending on other modules which also need setup. The problem is that I don't know how to manipulate the keywords. I will explain myself with an example               Task optimize     Units meters     System {        // input data     }          Optimizer {          type Simplex          convergenceCriteria 0.001     }          PointEvaluator {          type MyEvaluatorTechnique          convergenceCriteria = 0.1     }      this is a solution, which has header very generic entities which describe the meaning of each section, but I could also have sections that explicity concern specific techniques               Task {          type optimize          optimizer Simplex     }     Units meters     System {        // input data     }          Simplex {          convergenceCriteria 0.001          PointEvaluator MyEvaluatorTechnique     }          MyEvaluatorTechnique {          convergenceCriteria = 0.1     }      I would like to hear your opinion on which method may sound better in terms of design correctness, and pros and cons of both solutions. One thing I don't like in the first solution is, for example, the fact that depending on the type, I may have options that do not make sense for that specific type. In the second solution, however, I am setting up not the generic task (which then uses specific types of subsystem). Instead, I specify the specific subsystems performing the task.


Which of these two shuffle algorithms is more random?

Which of below two shuffle algorithms (`shuffle1` and `shuffle2`) is more random?               public final class Shuffle {         private static Random random;              public static void shuffle1(final Object[] array) {             if (random == null) {                 random = new Random();             }                  for (int i = array.length - 1; i > 0; i--) {                 swap(array, i, random.nextInt(i + 1));             }         }              public static void shuffle2(final Object[] array) {             if (random == null) {                 random = new Random();             }                  for (int i = 0; i < array.length; i++) {                 swap(array, i, i + random.nextInt(array.length - i));             }         }              protected static void swap(final Object[] array, final int i, final int j) {             final Object tmp = array[i];             array[i] = array[j];             array[j] = tmp;         }     }      The `shuffle2` algorithm guaranties that all elements are directly touched, but, in `shuffle1` algorithm, the element with index = 0 is never directly touched because of the condition `i > 0`.


Suggest other people's code to study

What open source Java code would you suggest for me to study? EDIT: I'm interested in the design, simplicity(?), their programming style, logic. EDIT2: The first thing that came to my mind is JUnit source code. I started looking into it and I was impressed by how 'Money' is designed/represented. Similarly are there any suggestible open-source projects.


Open source project question in interview

I've recently applied for a position as C# developer, and during the interview, the interviewers asked me many times if I contribute to develop one or more open source project. Since they let me write a lot of code (from basics to TDD,MVVM,MVP), I didn't get the meaning of such a question, especially cause they insisted a lot on the topic and the thing started to bother me. I wish I could have time enough to develop open source software, but I don't get why a company that sells software pretend that their employees work for free in their spare time. What's the real reason of this question (apart from checking your code)?


Well designed Open Source WPF Applications

I'm just wondering if anyone knows about some well designed .NET Open Source Applications using WPF? I have already tried to search at the usual sites like GitHub and Sourceforge, but I wasn't very satisfied by the results at all. Actually I'm interested in the right usage of MVVM, Data Binding etc. in the context of relatively large Software (at least more than the few lines of sample code, you will find at most Tutorials and Books). Also ORM with NHibernate lies in my main concern. Currently I also do have the overall impression WPF is not used very extensively at all, am I right with that? Which closed source (commercial) Software Products are out there, using it?


Updating settings on embedded systems device with non-reliable comms

I am writing a JavaFX GUI program for user configuration of an embedded systems device. The device will be connected by a wired or wireless serial connection which is not 100% reliable. Therefore when the user makes settings changes in the GUI, the program sends a set message to the device, then must verify they are set. My question is what program structures are useful for this purpose. My current approach is   * A class called `Sync` which contains two variables related to the particular setting. One is bound to the setting as it appears in the GUI and another to the setting as it has been received from the device.   * A property in `Sync` that describes if the two settings are the same, the device is setting is newer or the GUI setting is newer. Field decorations then bind to this setting.   * A button called `set` that sends a set message to the device   * A loop that continually polls the device for its settings (which are stored in the Sync class). The decorators then give feedback to the user whether the settings have synced. I'd like to do something a bit more elegant where the Sync class takes care of sending messages and checking if the setting were set. Some specific questions:   * Should I remove the 'set' button and have the Sync class update the device whenever it has valid settings?   * Is a decoration enough to indicate whether or not the setting has been set? Would a dialog box be better? Some general questions:   * Is there a best practice approach to this problem?   * Are there common classes that would be useful?   * Any other alternative designs? Edit: A constraint: I'd like to keep the device as dumb as possible. I've implemented custom protocols with CRC, ack/nack, retries, message buffers, etc. before, albeit between two embedded systems. The software will be modified for different beginner Arduino projects and I want to keep most of the logic (even validation) on the GUI side.


Confusion in understanding the theorem on Amortization

I was reading a book on Algorithm Analysis by Micheal T Goodrich. I came across amortization technique and I got struck in understanding the proof of theorem. I am putting the theorem and the proof and the part that I need some more explanation. Please help me: **Theorem:** A series of _n_ operations on an initially **empty** clearable table implemented with an array takes O(n) time Definition of clearable table: This Abstract data type stores table of elements, which can be accessed by their index in the table. In addition this ADT supports the following two methods: > add(e): Add the element _e_ to the next available cell in the table.   >  clear : Empty the table by removing all its elements. **Proof** : Let M0....,Mn-1 be the series of operations performed on S, and let Mi0,....,Mik-1 be the clear operations within the series. We then have, > 0<= i0 < .... < i k-1 <= n-1. > > Let us also define i-1 = -1. The running time of operation Mij (a clear > operation) is O(ij \- ij-1), because at most ij \- ij-1 -1 elements could > have been added into the table (using the add operation) since the previous > clear operation Mij-1 or since the beginning of the series. Question:   1. Why and how i-1 = -1 is defined?   2. I did not understand "because at most ij \- ij-1 -1 elements could have been added into the table (using the add operation) since the previous clear operation Mij-1 or since the beginning of the series". Please explain me more on this statement on why **-1** came into the picture.


An alternative for Game Maker on Linux?

Are there any alternatives to Game Maker built for Linux that get the job done using a familiar interface, similar converting scripting language(eg, Javascript) that DOESN'T export the games as either Flash or HTML5? Frankly, that's pretty specific, but hey. Multiple heads are better than one, especially when scrounging the dark depths of the Internet. :/


How should a programmer decide whether to get an MBA vs continuing as a programmer?

As I am from India, here most of the people think that if somebody has more than 5 Years of experience, he/she should not continue with it. Should go for an MBA degree and apply for the managerial job. What do you say?


I need to hire a web developer but I'm not sure which qualifications/skills they should have to do what I see in my head. Any help?

I'm looking to develop a simple image editor wherein a user can cycle through multiple layers (6-10) of images to develop a unique avatar. For example, the initial image layer will be a 2D character of their choice, mostly void of any accessories. The next image layer would be a shirt, another pants, another jewelry etc. I like the idea of frontend HTML5 so it can be a web app compatible across most platforms, but I'm lost on the backend requirements of such a project. #noob Any help would be greatly appreciated.


Custom use of Authorization header in a REST API

I'm building a REST api where clients are authenticated using client certificates. A client in this case is not an individual user, but some sort of a presentation layer. Users are authenticated using a custom approach and it's the responsibility of the presentation layer to see that this is properly done (note: I know this is not the proper approach, but the api is not public). I would like to pass the user name for each request (not the password), but I'm not sure where to do this. Would it be a good idea to use the Authorization header?


Best Practice: What can be the hashCode() method implementation if custom field used in equals() method are null?

What is the best practice to return a value for hashCode() method if custom field used in equals are null ? I have a situation, where equals() override is implemented using custom fields. Usually it is recommented to override hashCode() using that custom fields used in equals(). But if all the custom fields used in equals() are null, then what would be the best implementation for hashCode()? Example:               class Person {         private String firstName;         private String lastName;                 public String getFirstName() {             return firstName;         }                 public String getLastName() {             return lastName;         }         @Override         public boolean equals(Object object) {             boolean result = false;             if (object == null || object.getClass() != getClass()) {                 result = false;             } else {                 Person person = (Person) object;                 if (this.firstName == person.getFirstName()                     && this.lastName == tiger.getLastName()) {                     result = true;                 }             }             return result;         }                 @Override         public int hashCode() {             int hash = 3;             if(this.firstName == null || this.lastName == null) {                 // <b>What is the best practice here, </b>                 // <b>is return super.hashCode() better ?</b>             }                     hash = 7 * hash + this.firstName.hashCode();             hash = 7 * hash + this.lastName.hashCode();             return hash;         }     }        1. is it required to check for null in hashCode() ?   2. If yes, what should be returned if custom values are null ?


Is Multithreading Appropriate for Setting up Multiple Windows in the Same Application?

I am currently working with a Qt Application which tries to use multi threading to accomplish two task   * To Prevent the Main Thread's Event Loop from being blocked   * To increase computation efficiency You would think it is a good idea, but it turns out that this might be inefficient. In Qt, the client is not permitted to instantiate a QWidget subclass **only in the main thread**. The code I have seen so far seems really messy. The program has a "executive thread", in other words a background thread that manages user request (ie button click for a new gui panel), and of course there are 3 other thread (networking, script processing, and ofcourse the Main Thread) The setup is kind of funky to say the least, the action event (ie Button Click) is signaled to the executive thread, which then sends a **functor to the main thread** to instantiate the user requested gui panel. The above described make no sense. I am guessing that the original designers were concerned about the thread being blocked, but that shouldn't matter. Regardless of what thread instantiated in, it still ends up back in the main thread, and blocking it anyway. **This might not the be the best design choice, or is it? I am not sure, maybe there is someone here more experience that can shed light on this.** I personally think it would be better to let one thread handle all user interaction, and any intensive user processing should can be threaded. The other threaded parts make sense, having a seperate thread for processing scripts, networking actually could increase efficiency, while not blocking the main event loop so the gui can remain interactive. Also could some one also elaborate on when Multithreading is a good choice in GUI, and in regular circumstances? **Thanks**


Scrum for specialists teams

Scrum is best for teams with generalists members, that is teams where 2 people at least can do the same tasks. My main concern is to find good solutions **to adapt scrum (what to keep, what to remove, what to improve) for teams made of specialists?** Suppose you have a team of 5 developers (not real, just for the example):   1. One mathematician with strong skills in C;   2. One DB developer;   3. One Web Developer;   4. One UX/GUI developer;   5. One software architect; Here, all are specialists and no one can replace someone else (I don't care about the risks of building such a team, I want to focus on scrum). So, in a scrum context, here are my thoughts:   1. **Useless spring plannings:** indeed, when the mathematician says that a specific task is worth 2 points, nobody can vote against him;   2. **Useless team velocity metric:** as everybody can allocate any number of points to his own tasks, computing velocity makes not sense;   3. **Replace daily scrum meetings with weekly (longer) scrum meetings:** as each member of the team is working on his own tasks, daily scrum meetings should be really important to keep a "team spirit". However, daily scrum meetings are supposed to last around 15 minutes. This is clearly not sufficient to understand what the others are doing and will do. Moreover, the mathematician will most of the time answer the same things: "I am still doing _% &Lo( + ?$$_+&)"... Weekly meetings would give more time. To keep the same meetings time between "initial" scrum meetings and "weekly" scrum meetings, each weekly scrum meeting should last (5 days a week, with 4 weeks sprints, with sprint meetings lasting 4 hours and daily meetings lasting 15 minutes): (4*60 + 20*15)/ 4 => 2h-2h30 which seems reasonable. Or is scrum still usable? Maybe another agile technique should be used? Thanks for any help. Best regards.


Which license should I use in the program?

I have developed software that I would like to sell commercially. I don't know which license I should use. I've never used one before. I don't I think need/should to write one myself. Basically, I want to restrict end-used from doing these things without contacting me first:   * share binary program with others   * (re-)sell the software


Are there established practices on versioning of a shared web service?

We are working on an ASP.NET-based XML Web Service that we will be using for our own purposes as well as using it as part of a product offering for our integration partners. Once it goes live we will be working on future phases of the project, and it occurs to me that the service's details may need to change over time (method signatures, object types, etc.) and since we are not the only ones using the web service, we will need to have some level of coordination with our partners. What I'm not sure about is the best way to do this. When we update the web service in such a way that the WSDL would be changed, should we deploy it to a separate URL? Should we overload the existing methods? Have differently named methods? Ideally we would just have everything coordinated and cut over to the new methods but I don't see that happening. Are there established good ways to handle this?


What 's the essential difference between agile developing and plan based developing?

In agile process, the product owner put the unformal ideas/user story/backlog items to the sprint/iteration. Sprint/iteration is like a plan for a short term and it is drived by daily meeting. Planning is made in both processes. So what's the difference between agile and the old plan based developing?


What's the benefit of Azure ACS if ASP.NET 4.5 includes OAuth and OpenID providers?

Azure ACS offers OAuth and OpenID providers, and now that ASP.NET 4.5 offers the same thing, without the added cost, is there any reason for a .NET developer to consider ACS? (Disclaimer, I don't know what version of oauth each service provides)


Different kinds of safety

Programming languages and programs (as wells as individual functions, objects, etc.) are often described as being "safe" in one way or another. For example, they could be "type safe", "memory safe", "exception safe", "thread safe" - even "reentrant". Each of these concepts is about preventing erroneous or damaging code from executing, which makes them pretty important considerations in language and program design. So if I wanted to be super-pedantic about safety, what are all the different kinds of safety I could consider? Or could there be any number of them, leaving me to hope that I know all the ones which could be important for me? The context of the question involves comparing languages like Haskell to languages like C++: pure Haskell is great if you want to guarantee type, memory and thread safety. In C++, we can circumvent any of these. So I was thinking: "If we wanted to make a perfectly safe language, what are all the kinds of 'safety' that we could consider?"


Is it poor programming practice to pass parameters as Objects?

So, we've got a guy who likes to write methods that take Objects as parameters, so they can be 'very flexible.' Then, internally, he either does direct casting, reflection or method overloading to handle the different types. I feel like this is a bad practice, but I can't explain exactly why, except that it makes it more difficult to read. Are there other more concrete reasons why this would be a bad practice? What would those be? * * * So, some folks have asked for an example. He has an interface defined, something like:               public void construct(Object input, Object output);      And he plans to use these by putting several in a list, so it sort of builds bits and adds them to the output object, like so:               for (ConstructingThing thing : constructingThings)         thing.construct(input, output);     return output;      Then, in the thing that implements `construct`, there is a rickety reflection thing that finds the right method that matches the input/output and calls it, passing input/output. I keep telling him, it works, I understand it works, but so does putting everything into a single class. We're talking about reuse and maintainability, and I think he's actually constraining himself and has less reuse than he thinks. The maintainability, while probably high for him right now, will likely be very low for him and anyone else in the future.


How can I get more programming experience

I am going to be a third year computer science student and I have read Head first Java, Head First C, and I am currently reading C++ which is the language that I like the most since it has a good teaching style for people with experience. I am planning to either learn to make software with QT, learn objective-C(for iphone), or read Effective C++. How can I get experience as a programmer? Do I have the skills to join an open source project or do I need to learn php, mySQL or any other language. I love programming and computer science in general although some classes can be extremely hard (theoretical computer science). I also plan to become a guru in c++ but that's not going to be anytime soon.


Is the carriage-return char considered obsolete

I wrote an open source library that parses structured data but intentionally left out carriage-return detection because I don't see the point. It adds additional complexity and overhead for little/no benefit. To my surprise, a user submitted a bug where the parser wasn't working and I discovered the cause of the issue was that the data used CR line endings as opposed to LF or CRLF. Hasn't OSX been using LF style line-endings since switching over to a unix- based platform? I know there are applications like Notepad++ where line endings can be changed to use CR explicitly but I don't see why anybody would want to. Is it safe to exclude support for the statistically insignificant percentage of users who decide (for whatever reason) to the old Mac OS style line- endings? **Update:** To clarify, supporting Windows line endings (ie CRLF) doesn't require CR token recognition. For efficiency purposes the lexer matches on a per-char basis. By silently ignoring CR chars, the CRLF token simplifies to LF. As such, the CRLF token itself could be considered an anachronism all its own but that's not what this question is about. The last OS that provided system-wide support for CR style line endings was Mac OS 9. Ironically, the only application that still uses it as the default in OSX is Microsoft Excel.


Are there any podcasts (not lectures) about compiler development?

There are several podcasts with lectures from universities. I am looking for "other" podcasts. So are there any non-lecture podcasts about compiler development?


It usually takes me a very long time to learn new a programming concept. Am I suitable to be a programmer?

I admit that I haven't seen how fast other people people learn. But I in my case, it usually takes me a long time to understand few lines of a new programming concept. For instance, I've been programing in jQuery and a little of JavaScript for some time. I've been checking this Backbone.js tutorial. And it is taking me a lot of time to understand a simple block like this:                var ListView = Backbone.View.extend({             el: $('body'), // attaches `this.el` to an existing element.              initialize(): Automatically called upon instantiation. Where you make all types of bindings, excluding UI events, such as clicks, etc.              initialize: function(){           _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods                 this.render(); // not all views are self-rendering. This one is.         },      Even if it is all commented and explained (I still can't figure out what is `el` or why there is an underscore before `_.bindAll`, and I've been stuck with this for about an hour). This really make me wonder if I'm suitable to be a programmer or not?


What are the relative advantages of dictionaries versus databases?

I have an environment that supports both dictionaries (json style) and databases (not relational or anything, just formatted data by row and column). My application doesn't really need database functionality, butI'm somewhat more comfortable with the database system than I am with dictionaries. Is there a major performance advantage to dictionaries? What situations are there where a dictionary is better than a database?


An algorithm for reconstructing a graph from its shortest path information?

I have some shortest path data for a graph. Can I reconstruct the graph itself from this data? More precisely, I have a boolean (0/1) matrix for each vertex _v_ in graph _(V, E)_. Matrix element _[s,d]_ is equal to 1 iff _v_ is in the shortest path from source vertex _s_ to destination vertex _d_. All edges in the graph have the same length. For example, for the graph               (V1) -- (V2) -- (V3)      the three matrices would be: V1:               1 1 1     1 0 0     1 0 0      V2:               0 1 1     1 1 1     1 1 0      V3:               0 0 1     0 0 1     1 1 1      My questions: 1) is there an algorithm to reconstruct the set of edges E from these matrices? 2) is solution always unique? (this is more of a personal curiosity than a real requirement) 3) can the algorithm be generalized to nonuniform edge lengths?


Coupling business logic with class definitions

Perhaps it is my scripting background, but my perspective is that the purpose of an object should be to contain data. Classes are necessary in that they provide templates and standard ways to classify and construct objects with particular data attributes. Standard protocol in object oriented design seems to be to include business logic in class definitions. In a system that depends on state, I understand the motivation behind binding methods with the sole purpose of altering or retrieving the state of an object to the class definition. So let's exclude simple getters, setters, and constructors from the scope of the conversation. The problems, as I see them, start when _processes_ are bound to an object. Consider a simple "string.equals()" method that accepts a string as a parameter, and returns a boolean indicating whether strings are equivalent. I think this simple method can cause enormous problems. Let's say I have a LocationString class that inherited from String, where equals() is overridden as follows:               Boolean equals(LocationString otherLocation) {         return extractCountry().equals(otherLocation.extractCountry());     }          String extractCountry(){         return this.getCountry();     }      Now, assume I have a thousand such different objects with different equals() definitions, some of which are the same, and some of which are vastly different. Suddenly, the definition of equality changes for some of my classes. It becomes extremely painful to work out which equals definitions need to be changed. It becomes painful to work out whether other internal processes which called the equals method need to be changed. And eventually as the system expands, more hours are wasted searching through the code than analyzing it. As such, to me it makes far more sense that a generic equals rule is defined that modifies its behavior polymorphically depending on the inputs it receives. Consider the following definition:               public static Boolean equals(Object a, Object b) {         List locationClasses = Arrays.asList("LocationString")         if (locationClasses.contains(a.getClass().getName()) && locationClasses.contains(b.getClass().getName()){             return equals(a.extractCountry(), b.extractCountry());         }          else {             return StringUtils.equals(a,b);         }     }      If all processes were defined externally, a change in process would not be all that difficult to correct and provided these more generic rules could be stored and categorized logically, they would be easy to find and would only need to change once as the business logic changes. This approach seems relatively simple and straight forward. Why then, has it been generally rejected in favor of the typical object oriented coupling of data with methods?


License for code snippets

I'm wondering if there is a common license that would be good for _snippets_ of code (eg. things you might just paste into a file), which has the following conditions:   * Modifications of this snippet must be open-sourced   * No restrictions on code that uses the snippet Or would this license be too prone to workarounds to exist?


Is it right to persist a computed property to the DB?

I would like to know what do you think about persisting an "autocomputed property" to the database. For example I have these properties               decimal Price {get;set;}     decimal Tax {get;set;}     decimal PriceWithTax {get {return Price + Tax;}}      I think I need persist `PriceWithTax`. I can use this column, for example, in DB views. But I feel that this solution can lead to hidden bugs. What do you think? Edit: Ok, I try to explain our real problem. We have a class "Order" which has collection of items - class ItemOrders. Class ItemOrder has property Price and class Order has property TotalPrice. And implementation of TotalPrice:               TotalPrice {get { return ItemOrders.Sum(i => i.Price); }}      And we need sorting, grouping in the database. So its not a bussiness rule but a "data rule".


Referencing official documentation in source-code documentation

What are your preferences for referencing official documentation (like a white paper) for an algorithm from comments in the code that implements it? I'm trying to decide between two methods, as illustrated by the examples below, but am open to other suggestions. RFC 1321, for instance, describes the MD5 hash algorithm. If I were implementing MD5 in Python using the paper as a guide, and documented my code as I went, which of the following implementations of an example function `pad_string(str)` would you recommend, if not something entirely different? ### option 1               def pad_string(str):         """         Pads the string to be hashed to an appropriate length. See RFC 1321 3.1.         """      where the relevant section of the RFC is:               3.1 Step 1. Append Padding Bits              The message is "padded" (extended) so that its length (in bits) is         congruent to 448, modulo 512. That is, the message is extended so         that it is just 64 bits shy of being a multiple of 512 bits long.         Padding is always performed, even if the length of the message is         already congruent to 448, modulo 512.      **or** ### option 2               def pad_string(str):         """         Pads the argument string such that its length is congruent to 448, modulo 512.         """      Here, **option 1** simply references relevant parts of the "official" MD5 documentation by section number, where **option 2** doesn't make any mention of the paper and basically reiterates its contents where necessary. The advantage of the first is that the documentation adheres somewhat to DRY (Don't Repeat Yourself, in this case with respect to the RFC), but its disadvantage is that it relies on a third-party resource: if it's an obscure technical specification hosted in one place and the link provided inside the code documentation dies, then you're out of luck. The advantage of the second approach is that your source is self-contained: you don't need any other information when reading through it, and our example MD5 script would become as much a description of the algorithm as its implementation; this, of course, requires more writing on the code author's part, can bloat documentation, and, more importantly, may end up with mis-copied information and other errors. Is there any consensus on which is better?


Why is code sometimes called "listings"?

When reading _Programmers at Work_ (by Susan Lammers), they often refer to code as "listings". Why is that?


How would you go about creating a class diagram for a JPA/JSF application

I was creating a class diagram for an application I was working on today and I didnt include the JPA entities since I had all the information I thought was important in my DAOs, for example, I just care about how to register a user regardless of what information does a User object contain, so I only included the UserDao in my class diagram and added an operation called register which has a parameter of type User without having a User class in my diagram. My question is if its necessary to include every single class I have in my diagram or can I omit the classes that I will be forced to add because I am using a certain framework such as JSF or JPA?


Running Python script in background on Mac

I have a Python script that counts the number of file in a folder, and if the number of files exceeds 10 then it creates a popup window to ask the user to clean up the folder (I use tkMessageBox). How can I have the program run in the background so that it consumes only minimal resources? I tried running it as a daemon and as an agent but I couldn't see anything happen (no popup window).


how do design the database tables for file download statistics

I have the web application where i am serving file downloads in php. All is working fine and i have the download column in `file field` where i increment it. But i want to have full statictics of downloads like how many downloads on `each day` or in `month` or `time of day` or from `which location` But i am not able o find how to design the mysql tables for that. Do i need to lo every download request in database for that. Any design pattern or example of that in real world


IClass, Class, ClassImpl pattern?

I've been seeing a lot of code recently that looks like this:               public interface IFoo { int Bar(); }          public static class Foo      {         public static IFoo Create() { return new FooImpl(); }         private class FooImpl : IFoo         {             public int Bar () { ... }         }     }      Basically, there is a contract defined by an interface, the the main business object class is a static class that provides factory methods, and there is an embedded class that provides the actual implementation. There are some advantages to this pattern especially, the clean separation between the contract and the implementation. Still, it seems a little ugly to me: especially the naming of a static factory class with a business object name rubs me the wrong way. My questions are...   1\. Is there a name for this pattern or style of development?   2\. What do you think about this pattern? Are there any other advantages besides a rigorous hiding of implementation? Is there a better way to achieve the same goals?


How do I add another script engine to web browsers under Linux / Windows / Mac?

In my ample (NOT!) spare time, I'm fiddling with Lhogho and wondering how to go about morphing it into a script engine for web browsers, viz
My First Web Page
                                Any suggestions where to start? For Windows, I suppose Microsoft Windows Script Interfaces - Introduction. What about Linux and Mac? On the way there, I'm also trying to figure out how to make Lhogho into a server-side language, rather like PHP or ASP, viz                    <title>Lhogho Preprocessor</title>          <? print [Hello world] ?>                          I figure that'll be slightly easier. Maybe.


how to deal with parallel programming

I know that parallel programming is a big resource in computer graphics, with moder machines, and mayebe a computing model that will be grow up in the near future (is this trend true?). I want to know what is the best way to deal with it. there is some practical general purpose usefulness in studying processor n-dimensional mesh, or bitonic sort in p-ram machines or it's only theory for domain specific hardware used in real particular signal elaborations of scientific simulations? Is this the best way to acquire the know how for how to become acquainted with cuda or opencl? (i'm interested in computer graphics applications) and why functional programming is so important to understand parallel computing? ps: as someone has advice me i have forked this discussion from http://stackoverflow.com/questions/4908677/how-to-deal-with-parallel- programming


How to Improve this socket over TCP-IP system

Im new to Socket programming and im building a Socket over TCP-IP system with this architecture: ![system](http://i.stack.imgur.com/N2txX.png) **Server:** Basically a TCPIP Listener that waits for connection from the clients. **Client:** It knows the server Ip and try to connect, when the connection is set i can send commands from another client that acts like the ADMIN. In other words its like a chat system adapted to this use case. Once the client receive the commands form the admin console it pass it to the LED display connected by Serial Port. My question is: If want to remove those clients(Laptop, PC) from the system, and connect directly to the led Display, how can i do it? What happen to the Client logic? Can i send the commands from the server directly to the led display?


What are the software technologies behind real time web apps?

What are some of the software technologies behind "real-time" web apps, like Twitter, Trello, or even Gmail? I know there's a webserver and probably a database on the backend, but what are the software pieces that make for that rich web interaction that I'm seeing more of today?


What is a good code pattern for single retry then error?

I am writing a routine which has the following form:               TRY A     IF no success, B     IF no success, RETRY A     IF no success, throw error      It's not trivial to extract either A or B into it's own routine, so **what is most simple structure that will allow me to retry A without code duplication?** Currently, I have a `do..while` that allows `N` retries:               int retries = 1;          do {         // DO A              if ( /*success*/ ) {             break;         } else if (retries > 0)  {             // DO B                  if ( /*success*/) {                 break;             }         } else {             // throw Error         }     } while (retries-- > 0);      This is ugly and not ideal as it implies that I might want to ever retry more than once, which I don't. I will have to use a loop, but there has to be a more simple way that I'm not seeing. For context, this is code generated in Java, executing SQL statements to try an `UPDATE` first, then if no entry to update is found, `INSERT`, and if that command fails (concurrency, already created), try `UPDATE` again.


How to teach a class in management information systems without access to computers?

I teach evenings in a prison. The students need a computer course in management information systems to fulfill a degree requirement. There are no computers or calculators available and I am not allowed to bring equipment into the prison. Most of what I've found on the internet regarding this question is created for young children. I need something for adults.


Design pattern: static function call with input/output containers?

I work for a company in software research department. We use algorithms from our real software and wrap them so that we can use them for prototyping. Every time an algorithm interface changes, we need to adapt our wrappers respectively. Recently all algorithms have been refactored in such a manner that instead of accepting many different inputs and returning outputs via referenced parameters, they now accept one input data container and one output data container (the latter is passed by reference). Algorithm interface is limited to a static function call like that:               class MyAlgorithm{     static bool calculate(MyAlgorithmInput input, MyAlgorithmOutput &output);     }      This is actually a very powerful design, though I have never seen it in a C++ programming environment before. Changes in the number of parameters and their data types are now encapsulated and they don't change the algorithm callback. In the latest algorithm which I have developed I used the same scheme. Now I want to know if this is a popular design pattern and what it is called.


How much does the data model affect scalability and performance in so called "NoSQL" database?

You can't ever have a talk about so called "NoSQL" database without bringing the CAP theorem (Consistency, Availability, Partition : pick two). If you have to pick say, between MongoDB (Partition, Consistency) and CouchDB (Availability, Partition), the first you need to think about is "Do I need correct data or do I need access all the time?". Those new database were _made_ to be partitioned. But what If I _don't_? What if I just think its pretty cool to have a Key/Value, Column, Document, whatever database instead of a relational one, and just create one server instance and never shard it? In that case, wouldn't I have both availability and consistency? MongoDB wouldn't need to replicate anything, so it would be available. And CouchDB would have only one source of data, so it would be pretty consistent. So that would mean that, in that case, MongoDB and CouchDB would have little difference in term of use case? Well, except of course performance, API, and al, but that would be more like choosing between PostgreSQL and MySQL than having two fundamentally different set of requirements. Am I right here? Can I change a AP or CP database to an AC one by not creating more than one instance? Or is there something that I am missing? Let's ask the question in reverse. What if I take a relational database, let say MySQL, and put it in a master/slaves configuration. I don't use ACID transactions If I require that any write be synchronized to the slave immediately, wouldn't that make it a CP database? And what if I synchronise it a some predefined intervals, and it doesn't matter if a client read stale data from a slave. Wouldn't that make it an AP database? Wouldn't that mean that if I give up ACID compliance I can still use the relationnal model for a partionned database? In essence : is scalability about what you are ready to give up in the CAP theorem, more than the underlying data model? Does having Column, Document, Key Value, whatever give a boost to scalability over a relational model? Could we design a relational database designed from the ground up for partition tolerance? (Maybe it already exists). Could we make NoSQL database ACID compliant? Sorry, its a lot of questions, but I have read a lot about NoSQL database recently and it seem to me that the biggest benefit of using them is that they fit better the "shape" of your data, rather than just the partition, CAP and giving up ACID compliance. After all, not everyone has so much data that they need to partition it. Is there a performance/scalability benefit to not using the relational model _before I even think about partitioning my data?_


Is it out of line to give unsolicited constructive criticism to a programmer?

I recently started work at new office that uses a proprietary program written by a solo developer. He's occasionally around as part-time tech support, but the company has signed off on this software and he's no longer being paid to develop it. As a user of his software there are many issues that leap out to me as a source of concern:   * very simple to directly view the DB as a low-privilege user   * passwords stored as plaintext   * dictionary admin passwords   * app uses the DB root account   * DB doesn't meet 1NF (eg. appointment1, appointment2, etc.) I feel like these are serious issues and that if I were him I'd want them pointed out to me, but I'm not a qualified programmer (I'm a social worker) and I don't know if it would be rude of me to just buttonhole him and start blabbering about salted hashes and normal forms, especially when this is no longer a paid task of his. Is it out of line? If not, how would you broach it? **Edit - more info prompted by comments:**   * The application holds sensitive data.   * It's for internal use, but it's running on lots of machines in several cities and many visitors come through our offices.   * My concerns are for the developer's future projects as well as this specific one.


Technique for distorting part of an image to take features from another image?

I have a project of a community website, where people can alter/manipulate photos that they upload, in a particular way. For example, a person could select various contours and control points on their nose, and do the same for an image of another person's face, and hence morph their own photo so that it distorts the nose to match that of someone else's. The setting up of a profile based site, where images can be uploaded, is under the belt, but I was wondering if someone can point me in the right direction for image manipulation. I have been searching for scripts/libraries - chiefly php and python but gotten nowhere. I tried searching composite picture scripts, but what I found just stuck one picture onto another. Like cutting and pasting one nose onto another picture, without blending it in. I tried searching morphing scripts, but I just found scripts that turned one image into another image. I tried searching for image superposition, but that just gave composite image script. Neither of the above are what I am trying to do. What is the technique for distorting part of an image to take features from another image?


What's the most absurd myth about programming issues?

To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered? Which widespread and longstanding myths/misconceptions do you find **hard for programmers to dispel/correct**. Please, explain why this is a myth.


Modeling e-Commerce Content Relations with Entity Framework

I'm building an e-Commerce system in my spare time to better lean the ins and outs of ASP.net MVC, WebAPI, and Entity Framework. One of the things I'm struggling with is how to model the relations for the content pieces (categories, products, and webpages).   1. Categories can have 1 or no parent category.   2. Products can have 0 or more categories, but 1 may be specified as primary (for default breadcrumbs).   3. Webpages can have 0 or more categories, but 1 may be specified as primary (for default breadcrumbs).   4. I want to be able to specify the default sort order for each within the parent category. This tells me I'm going to need a many-to-many table with a sort column.   5. I want to be able to efficiently count and/or display products further down the category tree. For example: Using categories **Apple => MacBook** and **Apple => iMac** , I want to be able to display products from MacBook and iMac on the Apple category. Since categories, products, and webpages all share some similar properties like Name, Page Title, Meta Description, Main Content, and Published, I created an abstract base class called CatalogPage that they all inherit from. Since category, product, and webpage all have an optional default/parent category I also included nullable **DefaultCategory/DefaultCategoryId** properties on the CatalogPage class. I assume that if I want #5 to be efficient I'm going to have to store some redundant data. For example, store a Macbook Air 11" as a child of both Apple and Macbook. What are some good ways to model the rest of the relationships?


What type of encoding can I use to make a string shorter?

I am interested in encoding a string I have and I am curious if there is a type of encoding that can be used that will only include alpha and numeric characters and would preferably shorten the number of characters needed to represent the string. So far I have looked at using Base64 encoding to do this but it appears to make my string longer and sometimes includes `==` which I would like to avoid. Example: > test name|120101 becomes > dGVzdCBuYW1lfDEyMDEwMQ== which goes from 16 to 24 characters and includes non-alphanumeric. Does anyone know of a different type of encoding that I could use that will achieve my requirements? Bonus points if it's either built into the .NET framework or there exists a third party library that will do the encoding.


update methods in simple factories

I have simple factory class with differently named methods which create the same object but differently. These created objects are persisted to db. These are then retrieved from the db elsewhere and modified differently based on different conditions. I want to leave the conditional logic inside the service class and centralize this object modification, just like I did with object creation. Is it valid to add update* methods inside a simple factory ? Is there another pattern I should be using instead ? In an ideal world I could add these update methods to the Dao itself, but I am using JPA repositories for Dao. So it is not straight forward to add the update methods to Dao. These Message object updating methods have to live somewhere else and I cannot decide where.               public class Message {          // has some properties      }     public class Messagefactory {              public Message createMessageForConditionA() {}              public Message createMessageForConditionB() {}              public Message createMessageForConditionC() {}              public Message createMessageForConditionD() {}              // Is this okay ?         public Message updateMessageForConditionE() {}              public Message updateMessageForConditionF() {}          }          public class MessageService {              @Autowired         private MessageDao messageDao;              public Message createMessage(String condition){             Message message = null;             if(condition.equals(A)) {                 message = createMessageForConditionA();             } else if(condition.equals(B)) {                 message = createMessageForConditionB();             } else if(condition.equals(C)) {                 message = createMessageForConditionC();             } else if(condition.equals(D)) {                 message = createMessageForConditionD();             }             messageDao.save(message);             return message;         }              public Message updateMessage(string messageKey, String condition) {             Message message = messageDao.findByMessageId(messageKey);                  if(condition.equals(E)) {                 message = updateMessageForConditionE();             } else if(condition.equals(F)) {                 message = updateMessageForConditionF();             }                  messageDao.save(message);             return message;         }     }


What is the reasoning behind these design choices?

In ReactJS tutorial you are guided in the building of a commenting system. It's a very useful tutorial to understand ReactJS library, but there are some design choices I can't fully understand. So let's start from the initial setup: The system is composed of three components: CommentBox, CommentList, Comment and CommentForm. The hierarchy is the following               CommentBox         CommentList             Comment         CommentForm      The tutorial then implements all the data-fetching logic in the CommentBox component, which then pass this data to CommentList that renders it in the DOM. **Q1: Why? Is an arbitrary choice or there is some reasoning behind?** Then, when the tutorial come to the logic of new comments submission, it states: > When a user submits a comment, we will need to refresh the list of comments > to include the new one. It makes sense to do all of this logic in CommentBox > since CommentBox owns the state that **represents the list of comments**. **Q2: Why CommentBox represents a list of comments when there is another component representing it (CommentList, as the name seems to suggest)?** Further, implementing the submission logic, the code handling the comment POST to the server is part of the CommentBox component, wrapped in a method which is passed to CommentForm as a callback. So when the CommentForm form is submitted, it calls this CommentBox function to perform the server request, while the rest of the logic is implemented in CommentForm's functions. **Q3: Why isn't all submission logic implemented in CommentForm?** _EDIT: as I stated in a comment, " I already understood the application architecture and the concept of box. I'm arguing about the "individual implementation" details and **why some choices are preferable than others** "_


UI Applications and operations in background threads

I am not really sure about what is the best way to deal with operations executed in background threads in an application I am writing. I am writing it in C# and I am following the MVVM design pattern. Some user actions are expensive and I'd like to run them in a background thread, which is a quite straightforward approach. The worker thread then modifies my model, which notifies the ViewModel that something changed and finally the change gets propagated to the View. My problem is that the chain of events triggered would cause the modification of the View from the background thread, when it is only allowed in the UI thread. I know I can use the UI thread dispatcher but I am not really sure where (could the view-model be the right place?) so I'd like to know if you follow any design pattern to address this situation.


Is this approach to CSS correct?

Reading SASS basic features on their website, I stumbled upon the `@extend` feature. The example they give is the following:               .message {         border: 1px solid #ccc;         padding: 10px;         color: #333;     }          .success {         @extend .message;         border-color: green;     }          .error {         @extend .message;         border-color: red;     }          .warning {         @extend .message;         border-color: yellow;     }      That compiles to               .message, .success, .error, .warning {         border: 1px solid #cccccc;         padding: 10px;         color: #333;     }          .success {         border-color: green;     }          .error {         border-color: red;     }          .warning {         border-color: yellow;     }      Thus with this snippet of HTML
hello world
      you style your element with properties of `.message` and `.success`. However I feel this way of writing HTML (and CSS) very poor, in terms of semantic (you don't explicitly see from the markup above that the element has _also_ the styling of `.message`). Shouldn't the snippet above be
hello world
      ? I feel it to be more descriptive, and more easily reusable. For example I could assign the `.success` class (as written in the above CSS but without the `@extend`) to other elements which are not messages, and so using the class as a modifier, in a BEM-fashion. **So my question is, is the SASS example approach more desiderable than mine?**


How can I use guice to replace code dependent on service locator implementation?

Consider I have a service called FileSystem, and that this FileSystem is used by various classes throughout the application. Typically, the service is acquired via some static class method ServiceLocator.getService(FileSystem.class) Now consider I have a class Game, that depends on the FileSystem object to open up some UI resources. The game will also construct a world, using a WorldFactory. The WorldFactory also requires the FileSystem service. Here is where I encounter the problem, I construct a new instance of WorldFactory - which requires an instance of FileSystem to be injected into it. However, Guice will not inject into objects it has not constructed. So WorldFactory is left without a FileSystem injected into it. So I could pass a FileSystem object to the WorldFactory but then in essence Guice hasn't solved any of my problems and I have come to realize I haven't been using Guice correctly because I can do all of this without it? So then you get an odd instance where the constructor of a game entity requires that you pass an instance to the AudioSystem to it which it can play audio through. It just gets very messy with all these objects/services being explicitly passed around. Thanks. I'm still new to guice and trying to figure out how to use it.


How can I give my client "full access" to their PHP application's MySQL database?

I am building a PHP application for a client and I'm seriously considering WordPress or a simple framework that will allow me to quickly build out features like forums, etc. However, the client is adamant about having "full access" to the database and the ability to "mine the data." Unfortunately, I'm almost certain they will be disappointed when they realize they won't be able to easily glean meaningful insight by looking at serialized fields in wp_usermeta, etc. One thought I had was to replicate a variation on the live database where I flatten out all of those ambiguous and/or serialized fields into something that is then parsable by a mere mortal using a tool as simple as phpMyAdmin. Unfortunately, the client is not going to settle for a simple backend dashboard where I create the custom reports for them even though I know that would be the easiest and most sane approach.


Should I create a "placeholder" parent case, or set up Areas?

I'm using FogBugz for Project Management, and I'm unsure how to structure my cases. I have different features which require implementing as part of this project. For example, if I have a new feature to include autocomplete on a search text box, this would have cases such as:   * Method for returning search terms   * Front-end changes to request method   * Front-end changes to display search terms Should I create these as **subcases** under a "Autocomplete" case, or should they be created as top-level cases under an **area** called "Autocomplete"?


Looking for best practice for version numbering of dependent software components

We are trying to decide on a good way to do version numbering for software components, which are depending on each other. Let's be more specific: Software component A is a firmware running on an embedded device and component B is its respective driver for a normal PC (Linux/Windows machine). They are communicating with each other using a custom protocol. Since, our product is also targeted at developers, we will offer stable and unstable (experimental) versions of both components (the firmware is closed-source, while the driver is open-source). Our biggest difficulty is how to handle API changes in the communication protocol. While we were implementing a compatibility check in the driver - it checks if the firmware version is compatible to the driver's version - we started to discuss multiple ways of version numbering. We came up with one solution, but we also felt like reinventing the wheel. That is why I'd like to get some feedback from the programmer/software developer community, since we think this is a common problem. So here is our solution: We plan to follow the widely used _major.minor.patch_ version numbering and to use even/odd minor numbers for the stable/unstable versions. If we introduce changes in the API, we will increase the minor number. This convention will lead to the following example situation: Current stable branch is 1.2.1 and unstable is 1.3.7. Now, a new patch for unstable changes the API, what will cause the new unstable version number to become 1.5.0. Once, the unstable branch is considered stable, let's say in 1.5.3, we will release it as 1.4.0. I would be happy about an answer to any of the related questions below:   * Can you suggest a best practice for handling the issues described above?   * Do you think our "custom" convention is good?   * What changes would you apply to the described convention?


In Subversion, how should I set up a new major version of my application?

I'm about to start work on a new version (version 4) of my commercial application. I use Subversion. Based on your experiences, mistakes, and successes, how would you recommend I set up the new version in Subversion? Here's some info: I intend to keep releasing critical updates in version 3 for some time after version 4 is released. However all development of new features will be solely in version 4. In case it is relevant: I'm a solo developer on this product, and that is likely to remain the case. EDIT: I'm aware of SVN's tags and branches. I guess what I need is an optimal strategy for using tags and branches in my situation.


I feel stuck in the center of Python, How to get past beginner

I really apologize if this doesn't follow the S.O rules but I need a little help, I personally still classify myself as a beginner in python, Yet I've wrote a very small and VERY SURE impractical program for my boss to use. I know I'm still a beginner because simple things still perplex me but every book I read for beginners honestly just rehashes what I do already know but every 'more advanced' book doesn't really allow me to learn, they depend on example files and I never really understand why they built 'said' function or 'said' class. So onto my question... Is there any recommendations on a book or ANYTHING that pushes me out of this stage, I've used head first and normally they are really good but my issue there is they have me back tracking just to move forward again, It worked in HTML but its confusing in Python, basically I think I need to build a program while following along, Again I like HeadFirst's style but I need something that isn't going to make me have to remember one thing just to forget it... for record, I've checked into some O'Reilly books


Software Licenses: No Distribution and Private Selling Using Dual Licenses

I recently wrote a couple of WordPress Themes in PHP and was wondering what license I should put on it. I don't mind users reusing my code, but I don't want them to be able to sell and redistribute my themes as I want to retain that right. I heard somewhere that an _all rights reserved_ link would stop the distributing etc... Is that true or do I need to include another license and dual license my Themes? So to sum it up I want to use a license to stop others from selling and distributing my themes, while at the same time letting others use the code if they want to.


Have you tried Chronon the Java "Time Travelling Debugger" -- if so, is it worth trying and why?

First heard about it from Google Tech Talks, back 2009 when it was called Silver Bullet: http://www.youtube.com/watch?v=LpfmKIxusZY It's now called, Chronon... http://chrononsystems.com/ "Sounds" nice, have you tried Chronon the Java "Time Travelling Debugger" -- if so, is it worth trying and why?


Is macros support in a programming language considered harmful?

The first abuse that comes to my mind in C is:               #define if while       But at the same time it is extremely handy and powerful when used correctly. Something similar happens with Common Lisp macros. Why doesn't all the programming languages support macros like this and what are the alternatives? Is it they are considered harmful?