title: Is "Hiring only the Best" a really practical advice for normal desktop application programming?

text: For background, we are doing desktop engineering applications, with an AutoCAD like UI, something similar to etabs. One thing that really bugs me is, is there any need to hire the very best developers? For starters, we are experiencing great difficulties in recruitment; most resumes we see are either doing simple CRUD apps, or SharePoint customization which I don't think really involves a lot of hardcore programming. Even those whom we call for interview, most can't do Fibonacci sequence and a simple binary search, and we are gracious enough to give out hints and **spell out the problems explicitly** so that the candidates don't have to lookup a dictionary to check what does "Fibonacci sequence" mean. This got me thinking: Yes, we do need some level of programming aptitude when doing computational geometry/ linear programming stuff, and we do need some level of programming aptitude when designing the software architecture/ or deciding which software pattern to use, but beyond that, a lot of our code are just plumbing code ( I think), which can be done by someone with some familiarity with programming. Given that we really need programming talents now, and given that hiring superstar developers are very hard, I want to lower my standard and hire only the so-so ones, in direct contradiction to what Joel preaches. What do you think? Edit: You don't need to rewrite the whole computational geometry/linear programming libraries; all you need to do, as far as my application is concerned, is to be able to know how to cast the problems at hand into appropriate computational geometrical/linear programming terms and know when/how to use the existing libraries. So it's not as difficult as it seems.


How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one? In other words, how to prevent a user from creating more than one user account in a site? What's this problem called? Is there any specific name to this problem? What are the solutions? Thanks.


title: Cross-library and cross-programming-environment support

text: Often people talk about cross-platform compatibility, but is it possible to write such "universal code" that would work both in browser, in desktop, on opengl, on webgl, and on html5 canvas-object? I'm thinking about writing a c-to-javascript compiler that would allow running desktop applications in browser. This utility would parse c/c++-code and generate javascript-code, and somehow replace all opengl-calls with webgl-calls. Something similar to Emscripten, but without assembly-like code (functions and statements would be converted one to one). Of course there will be some severe limitation on such c++ code. It will not support templates, dynamic polymorphism, etc. Also all libraries would have to be more or less substituted with javascript- implementations, so for example std-namespace will have to have javascript counterpart. Do you think this is worth the trouble? Or should we just optimize better desktop-application download and execution, and except users to press "download" on our site? Google earth seems to be pretty popular even though it has a mandatory installation-step.


title: How to choose data storage method for user generated data?

text: In a program I am writing, I have 3 different ways to store user generated data:               (a) XML Files for each object (.Net Serialization)     (b) SQL Database (MSSQL)     (c) Massive terrifying blob of data in 1 file (I'm against this one)      There is absolutely no theoretical difference in performance or file size in this (hypothetical) scenario, but which would be best to use? Is SQL overkill (Considering that there will be up to 2 million items in database), or the best option? Where does the line get drawn between BLOB, XML, and SQL? The index would either link to the filename (a GUID) or a SQL item id (a GUID), so there is not difference in search functionality. The XML is stored in multiple files and file size is not much of a concern, so you would not need to parse the entire thing to access a specific item (Just open a file stream to {GUID}.xml) **Edit:** I'm adding some more info to make it more clear what I'm asking. I am working on a program for a client who is in the perfume design industry. In all cases, the search index will be separate (Someone else's code that I don't dare touch), and will be indexed in memory. Random access of data isn't needed in this case, as people would be pulling up the full information for a single item. In a much more clear way of saying: If you do not need to access random data in a database, and XML is easier, is it ok to use that instead of an SQL file? **Edit II:** Either way, it will be installed on a large server, so, I am not concerned about the client having access to MSSQL or not having enough space for ~1KB extra per entry (If not using SQL). **Edit III:** I am only doing single select all queries (E.g. SELECT * FROM (DB) WHERE ID = (GUID)) Or (Xml.deserialize((GUID).xml))


title: Dynamic git URL for Jenkins builds

text: We internally use GitHub Enterprise and Jenkins. If I push on the main repository it is automatically build without and the Commit is marked as correct (just as Travis does this). However, I want to be able to fork a repository and let the Jenkins build run. Is it possible to say Jenkins that he also runs any fork of the project when opening a PR on the main repo?


title: Execute code every hour

text: I need to create a web service that executes every hour. It will be used to review data in a database and add alerts to a table in the same database if certain conditions are met/not met. What we currently have is: We have end devices that use Python to report to an Amazon Web Services (AWS) virtual server. The AWS server takes that information and stores it in a MySQL database. The AWS server is Linux running Django and Apache. I need to be able to have some python code run every hour that verifies the data that has been stored by the end devices. If certain conditions are not met then a record will be added to the `alerts` table in the database. We originally contracted to have the above setup created. I am new to Python, Django, and Apache. However, I have already made several changes to the Python code that sends and also receives the data from the end devices. I am a coder that is breaking into web programming. Does anyone have any recommendations on how I can do this?


title: Which is more maintainable -- boolean assignment via if/else or boolean expression?

text: Which would be considered more maintainable?               if (a == b) c = true; else c = false;      or                c = (a == b);      I've tried looking in Code Complete, but can't find an answer. I think the first is more readable (you can literally read it out loud), which I also think makes it more maintainable. The second one certainly makes more sense and reduces code, but I'm not sure it's as maintainable for C# developers (I'd expect to see this idiom more in, for example, Python).


title: Is having sensitive data in a PHP script secure?

text: I've heard that PHP is somewhat secure because Apache won't allow the download of raw PHP. Is this reliable, though? For example, if you wanted to password protect something, but didn't want to create a database, would something like `$pass = "123454321";` be safe? Bottom line, is it safe to assume that nobody has access to the actual .php file?


title: Javascript design pattern with jQuery Widget factory

text: I am using the jQuery widget framework for creating some graphical elements on a webpage, and I have a conseptual question about the overall structure of the code. I have 3 classes A, B and C which all inherits from the same parent(pABC). They are all different, but have similar functionality. I also have to prototype classes(X, Y). These classes provide functionality that needs to be combined with A, B, C so that i get Ax, Ay, Bx, By, Cx, Cy. I want to do this with as little duplication as possible, so that if i change something in the X prototype it automatically gets changed in all of Ax, Ay, Bx, By, Cx and Cy. My intention is to do something like               $.widget("Ax", $.A, $.extend(true, {}, X, { ... Specific code for the Ax ... }));     $.widget("Bx", $.B, $.extend(true, {}, X, { ... Specific code for the Bx ... }));     $.widget("Cx", $.C, $.extend(true, {}, X, { ... Specific code for the Cx ... }));               $.widget("Ay", $.A, $.extend(true, {}, Y, { ... Specific code for the Ay ... }));     $.widget("By", $.B, $.extend(true, {}, Y, { ... Specific code for the By ... }));     $.widget("Cy", $.C, $.extend(true, {}, Y, { ... Specific code for the Cy ... }));      Is there a more efficient way to solve this problem? The problem is essentially that I have the classes A, B, C which is going to be combined with x, y to get Ax, Ay, Bx, By, Cx, Cy.


title: Why are scientific programming languages so weird?

text: It seems to me that programming languages meant for use in science and engineering are consistently _weird_ compared to general-purpose languages. Some examples off the top of my head:   * In Matlab, each function has to be placed in a separate file   * In R, <\- is the assigment operator, as opposed to = in almost every other language   * Matlab, R, Julia and others are all 1-indexed   * Matlab uses % for comments, and not the standard # or // Of course, these languages all have several design features that _actually_ make them easier to use for scientific applications, such as more natural matrix notation. Still, they all inexplicably make all these bizarre choices which don't make anything easier and could easily have been avoided if the language designers had just chosen to do what 99% of other languages do. Is the reason vendor lock-in? A lack of contact with the wider software development community? Something else? I read this thread and didn't find the explanations satisfactory. Just because R were designed as a scientific language doesn't mean it _had_ to completely ignore conventions and use <\- instead of =.


title: Use Of Exists clause in SQL

text: Just finished Stanford lecture on `SQL` (by Prof. Jennifer Widom). However I have developed a confusion regarding the use of `EXISTS` clause. I thought it is just like a condition and an expression so that if it's true, the above query proceeds (much like the Boolean `AND`). So having a slight doubt regarding this question: > Passenger = {pid, pname, Age}   >  Reservation = {pid, class, tid} and tables are populated with some data and following query is executed:               SELECT pid      FROM Reservation      WHERE class = 'AC' AND EXISTS          (SELECT * FROM Passenger WHERE age > 65 AND Passenger.pid = Reservation.pid)      Now the thing that is getting me troubled is that I thought that the use of `EXISTS` is simply that the above main query proceeds if the subquery returns something. So as the subquery was returning something, I expected the query to return all PID's where `class = 'AC'`. I didn't think that it was executed tuple by tuple. So how to remove this confusion?


title: Can static and dynamically typed languages be seen as different tools for different types of jobs?

text: Yes, similar questions have been asked but always with the aim of finding out 'which one is better.' I'm asking because I came up as a dev primarily in JavaScript and don't really have any extensive experience writing in statically typed languages. In spite of this I definitely see value in learning C for handling demanding operations at lower levels of code (which I assume has a lot to do with static vs dynamic at the compiler level), but what I'm trying to wrap my head around is whether there are specific project contexts (maybe certain types of dynamic data-intensive operations?) involving things other than performance where it makes a lot more sense to go with Java or C# vs. something like Python.


title: Should software engineers also act as tech support?

text: Should a software engineer also act as technical support? That is, should a company allow their engineers to wear both the software engineer and technical support hats. It seems that it would remove the ability to write software if much of an engineer's time is taken up by technical support.


title: How can I simulate clicks for a mobile browser?

text: I am creating a web app. I was testing it on a mobile browser and noticed that `:active` pseudo class doesn't really work. How should I simulate clicks for a mobile browser? I'm specifically interested for Android and iPhone. I am using css sprites. I stumbled upon `ontouchstart` but don't know how to use that. Can anyone help me over it?


title: Why do .NET shops seem to prefer Crystal Report over RDLC reports?

text: I am currently using RDLC reports. But when interviewing for .NET jobs, they frequently ask "Have you worked with Crystal Reports?". Why do they like Crystal Reports when Visual Studio already has RDLC reports integrated?


title: Are outdated comments an urban myth?

text: I constantly see people making the claim that "comments tend to become outdated." The thing is, I think I have seen maybe two or three outdated comments my entire career. Outdated information in separate documents happens all the time, but in my experience outdated comments in the code itself are exceedingly rare. Have I just been lucky in who I work with? Are certain industries more prone to this problem than others? Do you have _specific_ examples of recent outdated comments you've seen? Or are outdated comments more of a theoretical problem than an actual one?


title: Where to Perform Authentication in REST API Server?

text: I am working on a set of REST APIs that needs to be secured so that only authenticated calls will be performed. There will be multiple web apps to service these APIs. Is there a best-practice approach as to where the authentication should occur? I have thought of two possible places.   1. Have each web app perform the authentication by using a shared authentication service. This seems to be in line with tools like Spring Security, which is configured at the web app level.   2. Protect each web app with a "gateway" for security. In this approach, the web app never receives unauthenticated calls. This seems to be the approach of Apache HTTP Server Authentication. With this approach, would you use Apache or nginx to protect it, or something else in between Apache/nginx and your web app? For additional reference, the authentication is similar to services like AWS that have a non-secret identifier combined with a shared secret key. I am also considering using HMAC. Also, we are writing the web services in Java using Spring. **Update:** To clarify, each request needs to be authenticated with the identifier and secret key. This is similar to how AWS REST requests work.


title: Product backlog- when do task hours get estimated?

text: I am wondering if when developing a product backlog do tasks have hours estimated for them. To confirm, i can talking about a product backlog here not a sprint backlog as I know it does have.


title: iOS In-App Purchases with dynamic content

text: I want to built an app that it will support In-App Purchases. In short, user will download the app (with some basic features), and he will have the ability to download extra layers (delivery content) with additional info (e.g. a recipe). I want the content of this layer (the recipe) to be dynamic, and be downloadable (through web services) from a server. What concerns me is, how i will secure the web services to be available, only to the users that have pay for the extra layer (using In-App Purchases)? Is this functionality possible to be implemented in Google Play?


title: How do you convince the client their application's backend needs a rewrite?

text: I have been supporting a LOB winforms application for a client the last 3 years. The application is built with a simple monolithic architecture and uses .NET 2.0. The application is a core part of their operations and its longevity is paramount. It needs to evolve with their evolving business processes, as well as implement improved functionality etc....this brings me to believe that this application needs an overhaul of sorts on the back-end. The problem is changing a back-end is "invisible"...i.e. the user never actually sees it. It's a quality of the system that is changing (stability, maintainability, reliability, longevity), not some functional requirement that will be easily seen...i.e. the ROI is not obvious. There is a lot of new functionality to be added to the front-end as well (user experience). I am considering a strategy of changing the back-end over time...i.e. when making a change or adding a feature to the front-end, change those components in the back-end that are affected, eventually you get to everything. How do I convince the client that we need to rebuild the back-end?


title: Using business objects in view models

text: When using reusable business objects, what is considered best practice when building view models? We use an object we call `Builder` to build our view models. One builder for each logical unit of views (orders, users etc), where each unit can contain a number of different view models (orders contains summary, order lines etc). A builder may pull data through one or more standard business objects in order to build a view model. What is considered the better practice when it comes to using business objects/models in view models? **Approach 1** Allow the use of business objects in the view model?               //Business object in some library     public class Order     {         public int OrderNum;         public int NumOrderLines;         //...     }          //Order builder in website     public class OrderBuilder     {         public OrderSummary BuildSummaryForOrder(int OrderNum)         {             Some.Business.Logic.Order obOrder = Some.Business.Logic.GetOrder(OrderNum);             //Any exception handling, additional logic, or whatever                  OrderSummary obModel = new OrderSummary();             obModel.Order = obOrder;                  return obModel;         }     }          //View model     public class OrderSummary     {         public Some.Business.Logic.Order Order;         //Other methods for additional logic based on the order         //and other properties     }      **Approach 2** Take only the necessary data from the business objects               //Business object in some library     public class Order     {         public int OrderNum;         public int NumOrderLines;         //...     }          //Order builder in website     public class OrderBuilder     {         public OrderSummary BuildSummaryForOrder(int OrderNum)         {             Some.Business.Logic.Order obOrder = Some.Business.Logic.GetOrder(OrderNum);             //Any exception handling, additional logic, or whatever                  OrderSummary obModel = new OrderSummary()             {                 OrderNum = obOrder.OrderNum,                 NumOrderLnes = obOrder.NumOrderLines,             }                  return obModel;         }     }          //View model     public class OrderSummary     {         public int OrderNum;         public int NumOrderLines         //Other methods for additional logic based on the order         //and other properties     }      I can see the benefits and drawbacks to both, but I wonder if there's an accepted approach? In approach 1, there's no duplication of code around the models, but it creates a dependency on the business logic. In approach 2, you take only the data needed for the view, but you duplicate code around models.


title: Strategy for writing a logic program

text: I have had a hard time learning logic programming thus far, and my request for outside resources on this site was met with some opprobrium, so perhaps this question better addresses both my needs and the requirements of this community: Is there a step-by-step approach to writing a problem in Prolog or related logic languages? For example, I initially found recursive functions difficult to create myself, though I could more or less understand those that I read, until the I learned the following approach (presented roughly and for example purposes only!):   1. Describe the base case, i.e. the smallest form of the problem.   2. Figure out how to combine the results of recursive cases, i.e. add numbers, cons elements, etc. Seeing that there were a few common patterns here helped immensely!   3. Figure out how to break the results of a larger recursive case up, i.e. cdr down list, subtract, etc. Again, seeing the limited number of common patters was key! So, a clear description of a related process for tackling a logic problem might be very useful.


title: Syntactic Sugar for old languages

text: I first learned about the existence of syntactic sugar languages, like CoffeeScript and SASS while working in Rails. This got me thinking... why do we not have well-known (if any at all) syntactic sugar for languages like C, C++ and Java? Imagine a language that reads like Python or Ruby that can be preprocessed to C, and then compiled to generate really fast code that also looks beautiful. For example, instead of:               #include <stdio.h>          int divide(int a, int b)     {         if(b != 0)             return a / b;              return 0;     }          int main()     {         int a, b;              scanf("%d", &a);         scanf("%d", &b);              printf("%d", divide(a, b));              return 0;     }      Why not have:               include stdio.h          fn divide(int a, int b):       a/b if b != 0       ret 0          fn main:       int a, b            scanf '%d', a       scanf '%d', b            print '%d', divide(a,b)       ret 0      And have this preprocess down to the same C code above? Why stick to language implementations that are either fast _or_ easy to read when you could have both?


title: How to avoid duplication of code related to shared entities in the repository pattern?

text: I'm building a repository for a large CRM schema that has a high number of relations between entities. Some of the entities are referenced by almost all entities, e.g. Person and Company. Where I have an aggregate root such as Order, that addresses Order Header, Order Lines etc. In the case where the Order is from a new Customer, I need to insert a Company and a Person record at the same time... so far so good. The difficulty is that this is the situation with very many **other** aggregate roots. I don't want to have a private method `insertPerson(IPerson)` in every single repository implementation. I have a Customer repository that already has public `InsertCustomer(ICustomer)` method, which persists a Company and a person record. But my reading indicates that repositories shouldn't depend on each other. If this is a case where it is okay for repositories to depend on each other, what is the best way to go about it? Should I inject the Customer Repository into the Order repository constuctor, pass it as a parameter to the methods that need it, or never commit this evil and duplicate the identical code in all repositories, in case those repositories need to specialise that code for their specific contexts?


title: How to refactor my design, if it seems to require multiple inheritance?

text: Recently I made a question about Java classes implementing methods from two sources (kinda like multiple inheritance). However, it was pointed out that this sort of need may be a sign of a design flaw. Hence, it is probably better to address my current design rather than trying to simulate multiple inheritance. * * * Before tackling the actual problem, some background info about a particular mechanic in this framework: It is a simple game development framework. Several components allocate some memory (like pixel data), and it is necessary to get rid of it as soon as you don't need it. Sprites are an example of this. Anyway, I decided to implement something ala Manual-Reference-Counting from Objective-C. Certain classes, like Sprites, contain an internal counter, which is increased when you call `retain()`, and decreased on `release()`. Thus the `Resource` abstract class was created. Any subclass of this will obtain the `retain()` and `release()` implementations for free. When its count hits 0 (nobody is using this class), it will call the `destroy()` method. The subclass needs only to implement `destroy()`. This is because I don't want to rely on the Garbage Collector to get rid of unused pixel data. * * * Game objects are all subclasses of the Node class - which is the main construction block, as it provides info such as position, size, rotation, etc. ![enter image description here](http://i.stack.imgur.com/97UIS.png) See, two classes are used often in my game. Sprites and Labels. Ah... but wait. Sprites contain pixel data, remember? And as such, they need to extend `Resource`. ![enter image description here](http://i.imgur.com/KwTcsLM.png) But this, of course, can't be done. Sprites ARE nodes, hence they must subclass `Node`. But heck, they are resources too. * * *   * **Why not making Resource an interface?**   * Because I'd have to re-implement `retain()` and `release()`. I am avoiding this in virtue of not writing the same code over and over (remember that there are multiple classes that need this memory-management system).   * **Why not composition?**   * Because I'd still have to implement methods in `Sprite` (and similar classes) that essentially call the methods of `Resource`. I'd still be writing the same code over and over! * * * What is your advice in this situation, then?


title: What license is the GPL License licensed under?

text: The actual GPL License (that is, the _text_ that contains the words _"The licenses for most software and other practical works are designed..."_ ) is a document; I would assume therefore that it is under some sort of copyright? What license is this license licensed under? That is, if I were to include the body of the GPL License in my own projects (and perhaps create a derivative work) what limitations am I under?


title: Practical programming test in interview for flex programmer

text: i'm looking for the best way to test a candidate for a position of flex programmer with a pracitical\interactive test in front of a computer 45-60 minutes test. need to test flex basic knowledge, abillity to solve UI programming challenges and maybe some flex mobile. any ideas?


title: Library planning

text: I have been searching all over the internet for exact answer for my question. I am hoping you can help me out. I wonder how professional programmers/coders planing their projects? Libraries, subpackages? For example when creating a user system, how do you aproach it? How do you decide your classes, functions, requirements, database structure, depencies... Here is a example of user system planning i tried. Am I doing it right? [planing] ## General   * User identity should be selectable (email, username etc.)   * Passwords: use sha1. mixed with salt   * email   * user meta (a placeholder for user profile)   * user group   * user access (group based)   * invitation   * referer   * register and last login dates   * .... ## Auth System ### Register   * Required fields:     * Username     * email     * password   * First Check     * Username, email, password fields are filled? [/planing] I am trying this aproach with planning. Is there a software to do a planning like this? What should I ask myself? what is the important questions that guide me to the end? Thank you for your advices that you will send.


title: What kind of things can you learn from a guy who only hacks existing code?

text: At my previous job I was the lead programmer and I worked with this guy who was a self-admitted hacker. We respected each other and had a great relationship. The company was much better off because we blended our talents. I would tend to look for an elegant, graceful solution that we could add to our code library. He would tend to find, tweak, and fit some strange piece of code into a solution. One of the most valuable lessons I learned from him was you don't always have to build the solution from scratch, there's a ton of code out there you can borrow from. What kind of things have you learned from a hacker? **Edit - Added My Definition of Hacker**   By hacker I mean someone who for the most part, cannot create something from scratch. However they are very good at morphing code that others have written.


title: Where should the ACL handler be called in a MVC architecture?

text: Thinking about Access Control Lists bound to a web MVC architecture, I have a doubt on where the verification should be done. Within Models? Controllers? FrontController? Imagine a multiple module web application (like a website). I have a public site and a restricted admin zone.   * All public site pages are acessible by anyone.    * The restricted admin area is only accessed by an authenticated user.    * There are some access levels for the users, such as root, admin and regular user. I gave this some thought during my lunch time today and some ideas came out. First, I needed to ask myself this question: > Is access control part of business logic? After some time, I figure out that the answer should be **no** for most cases. Normally, for the situation I described, the business logic of the public area is about the same of the restricted one. When is not exact the same, what I normally do is to create a superset of both business logic rules, that contains all logic needed. So, even if there are several modules in my application, I normally have only one model layer. Doing the ACL within my controllers leads to code duplication, since I'd have to check it everytime I'd need. Also, I'd get a high coupling between controllers and the ACL component. Thinking about putting it inside FrontController seems to be the right approach. In deed, my initial thought was to put the ACL handler as a dependency for the FrontController. This approach would have controller methods (actions) as **resources** of the ACL, creating roles for my users. Some pseudo-code (mixing Java, C#, PHP):               aclHandler = new DefaultAcl();     aclHandler.addRole('none'); // not authenticated     aclHandler.addRole('user');     aclHandler.addRole('admin', extend='user');     aclHandler.addRole('root', extend='admin');          aclHandler.addUser('john', 'root');     aclHandler.addUser('mary', 'admin');     aclHandler.addUser('jane', 'user');          aclHandler.addResource('admin.content.create'); // MODULE.CONTROLLER.ACTION     aclHandler.addResource('admin.content.view');     aclHandler.addResource('admin.content.edit');     aclHandler.addResource('admin.content.remove');          aclHandler.addResource('public.content.view');          aclHandler.allow('*', 'public.*');          aclHandler.deny('*', 'admin.*'); // deny from all     aclHandler.allow('user', 'admin.content.view'); // allow user to view content     aclHandler.allow('admin', 'admin.content.{edit,create}'); // allow admin to edit and create content     aclHandler.allow('root', '*'); // root can do anything      This way, my FrontController would have something like:               class DefaultFrontController implements FrontControllerInterface {         AclInterface acl {get};         User currentUser {get;set};         public DefaultFrontController(AclInterface acl, User user) {             this.acl = acl;             this.currentUser = user;             // ...         }              public void dispatch(ControllerRequest request, ControllerResponse response) {             try {                 this.acl.checkPrivileges(request.resource, this.currentUser);             } catch (AclException e) {                 this.forbiddenAccessCallback(request, response, this.acl, this.currentUser);                 return;             }                  // continue impl...         }     }          fc = new FrontController(aclHandler, new User(name='John', role='root'));     fc.dispatch(...);  // ...      This implementation makes an ACL component a mandatory parameter for the FrontController constructor, so, now it's part of its state. This could be a problem when I don't need an ACL, but can be overpassed by creating a mock implementation of ACL component, like `AllowFromAllAcl`, that would allow any users to do anything. Any ideas? Corrections? Suggestions?


title: Is logging hours for software work a good idea?

text: An employer I'm interviewing for does this, I have never heard of anyone doing it before and honestly I don't like the idea of being micromanaged. How does the community feel about this?


title: Zoom to Fit Points on Surface

text: I'm attempting to develop a piece of functionality using a 3rd party map control in an application that automatically pans/zooms the map surface to the best possible view given points on map. The map should be centered and zoomed in as close as possible without cutting out any points on the map. To determine the maps center point, I averaged all of the points on the map surface. This seems to be working fine, but there may be a better approach. The issue I'm running into is how to appropriately zoom in or out to accommodate all points on the map in the "best" possible view. I'm not very familiar with 3D techniques, so any terminology relating to this problem will probably be new to me. I'm not necessarily looking for a specific algorithm (though I certainly wouldn't turn one down). Mostly, I would like to understand the theory behind approaching such a problem so that I can implement it.


title: Message Queue: Which one is the best scenario?

text: I write a web crawler. The crawler has 2 steps:   1. get a html page   2. then parse the page I want to use message queue to improve performance and throughput. * * * I think 2 scenarios: ## scenario 1:                   structure:          urlProducer -> queue1 -> urlConsumer -> queue2 -> parserConsumer      urlProducer: get a target url and add it to queue1 urlConsumer: according to the job info, get the html page and add it to queue2 parserConsumer: according to the job info, parse the page ## scenario 2:                   structure:         urlProducer -> queue1 -> urlConsumer         parserProducer-> queue2 -> parserConsumer      urlProducer : get a target url and add it to queue1 urlConsumer: according to the job info, get the html page and write it to db parserProducer: get the html page from db and add it to queue2 parserConsumer: according to the job info, parse the page * * * There are multiple producers or consumers in each structure. scenario1 likes a chaining call. It's difficult to find the point of problem, when occurring errors. scenario2 decouples queue1 and queue2. It's easy to find the point of problem, when occurring errors. I'm not sure the notion is correct. Which one is the best scenario? Or other scenarios? Thanks~


title: How do developers verify that software requirement changes in one system do not violate a requirement of downstream software systems?

text: In my work, I do requirements gathering, analysis and design of business solutions in addition to coding. There are multiple software systems and packages, and developers are expected to work on any of them, instead of being assigned to make changes to only 1 system or just a few systems. How developers ensure they have captured all of the necessary requirements and resolved any conflicting requirements? An example of this type of scenario: Bob the developer is asked to modify the problem ticket system for a hypothetical utility repair business. They contract with a local utility company to provide this service. The old system provides a mechanism for an external customer to create a ticket indicating a problem with utility service at a particular address. There is a scheduling system and an invoicing system that is dependent on this data. Bob's new project is to modify the ticket placement system to allow for multiple addresses to entered by a landlord or other end customer with multiple properties. The invoicing system bills per ticket, but should be modified to bill per address. What practices would help Bob discover that the invoicing system needs to be changed as well? How might Bob discover what other systems in his company might need to be changed in order to support the new changes\business model? Let's say there is a documented specification for each system involved, but there are many systems and Bob is not familiar with all of them. End of example. We're often in this scenario, and we do have design reviews but management places ultimate responsibility for any defects (business process or software process) on the developer who is doing the design and the work. Some organizations seem to be better at this than others. How do they manage to detect and solve conflicting or incomplete requirements across software systems? We currently have a lot of tribal knowledge and just a few developers who understand the entire business and software chain. This seems highly ineffective and leads to problems at the requirements level.


title: Why do we need to include the .h while everything works when including only the .cpp file?

text: Why do we need to include both the `.h` and `.cpp` files , while we can make it works with making just a `.cpp` file and then including it . For example, Creating a `file.h` containing declarations, then creating a `file.cpp` containing definitions and including both on the `main.cpp`. Or, creating a `file.cpp` containing declaration/definitions ( no prototypes ) Including it on the `main.cpp`. Both worked for me , but still can't the difference since i do not have a background on the compiling and linking process .


title: How to model an address type in DDD?

text: I have an `User` entity that has a `Set` of `Address` where `Address` is a value object:               class User{         ...         private Set<Address> addresses;         ...         public setAddresses(Set<Address> addresses){             //set all addresses as a batch         }         ...     }      A `User` can have a `home address` and a `work address`, so I should have something that acts as a look up in the database: **tbl_address_type**               ------------------------------------------------     |    address_type_id       | address_type      |     ------------------------------------------------     |            1             |      work         |     ------------------------------------------------     |            2             |      home         |     ------------------------------------------------      and correspondingly **tbl_address**               -------------------------------------------------------------------------------------     |    address_id       |     address_description      |address_type_id|    user_id   |     -------------------------------------------------------------------------------------     |          1          |      123 main street         |      1        |      100     |     -------------------------------------------------------------------------------------     |          2          |      456 another street      |      1        |      100     |     -------------------------------------------------------------------------------------     |          3          |      789 long street         |      2        |      200     |     -------------------------------------------------------------------------------------     |          4          |      023 short street        |      2        |     200      |     -------------------------------------------------------------------------------------        1. Should the address type be modeled as an Entity or Value type? and Why?   2. Is it OK for the `Address` Value object to hold a reference to the Entity `AdressType` (in case it was modeled as an entity)? Is this something feasible using Hibernate/NHibernate?   3. If a user can change his home address, should I expose a `User.updateHomeAddress(Address homeAddress)` function on the `User` entity itself? How can I enforce that the client passes a Home address and not a work address in this case? (a sample implementation is most welcomed)   4. If I want to get the User's home address via `User.getHomeAddress()` function, must I load the whole addresses array then loop it and check each for its type till I find the correct type then return it? Is there a more efficient way than this?


title: Is there a certain way that I have to include a library and its license?

text: I know this may be a dumb question, but I'm only 15 so I don't really know how the legal part of it works. When I choose a .dll to be included in my project, Visual Studio only includes the .dll file with my project (of course) so I just copy the license and stick it in a folder called licenses. But now, I'm going to be making a program for a contest so I need to make sure I have the licenses done right or I'll get disqualified. So is there any specific location I have to keep the licenses in my project, is there a way for Visual Studio to automatically copy the license the way it does with .dll files and is there anything else I have to watch out for legally? PS: If it matters, the libraries I'm planning on using right now are WriteableBitmapEx and AvalonDock Thanks


title: Unit testing to prove balanced tree

text: I've just built a self-balancing tree (red-black) in Java (language should be irrelevant for this question though), and I'm trying to come up with a good means of testing that it's properly balanced. I've tested all the basic tree operations, but I can't think of a way to test that it is indeed well and truly balanced. I've tried inserting a large dictionary of words, both pre-sorted and un-sorted. With a balanced tree, those should take roughly the same amount of time, but an unbalanced tree would take significantly longer on the already-sorted list. But I don't know how to go about testing for that in any reasonable, reproducible way. (I've tried doing millisecond tests on these, but there's no noticeable difference - probably because my source data is too small.) Is there a better way to be sure that the tree is really balanced? Say, by looking at the tree after it's created and seeing how deep it goes? (That is, without modifying the tree itself by adding a depth field to each node, which is just wasteful if you don't need it for anything other than testing.)


title: Isolated Unit Tests and Fine Grained Failures

text: One of the reasons often given to write unit tests which mock out all dependencies and are thus completely isolated is to ensure that when a bug exists, only the unit tests for that bug will fail. (Obviously, an integration tests may fail as well). That way you can readily determine where the bug is. But I don't understand why this is a useful property. If my code were undergoing spontaneous failures, I could see why its useful to readily identify the failure point. But if I have a failing test its either because I just wrote the test or because I just modified the code under test. In either case, I already know which unit contains a bug. What is the useful in ensuring that a test only fails due to bugs in the unit under test? I don't see how it gives me any more precision in identifying the bug than I already had.


title: What are the pros (and cons) of using “Sign in with Twitter/Facebook” for a new website?

text: Myself and a friend are looking to launch a little forum site. I’m considering using the “Sign in with Facebook/Twitter” APIs, possibly exclusively (a la e.g. Lanyrd), for user login. I haven’t used either of these before, nor run a site with user logins at all. What are the pros (and cons) of these APIs? Specifically:   1. **What benefits do I get as a developer from using them?** What drawbacks are there?   2. Do end users actually like/dislike them?   3. Have you experienced any technical/logistical issues with these APIs specifically? Here are the pros and cons I’ve got so far: ### Pros   * More convenient for the user (“register” with two clicks, sign in with one)   * Possibly no need to maintain our own login system ###  Cons   * No control over our login process   * Exclude Facebook/Twitter users who are worried about us having some sort of access to their accounts   * Users’ accounts on our site are compromised if their Facebook/Twitter accounts are compromised.   * And if we don’t maintain our own alternative login system:      * Dependency on Facebook/Twitter for our login system     * Exclude non-Facebook/non-Twitter users from our site


title: What are good requirements for a QA engineer?

text: We're hiring a QA person and I am supposed to come up with some interview questions. The truth is, I don't know much about what a good QA engineer should know, much less what good interview questions might involve. Does anyone have suggestions? Some information: The environment is two separate (but intertwined) web applications for the Microsoft stack (ASP.NET, SQL Server, IIS).


title: Scriptable user-interfaces/frameworks for automated UI testing

text: I'm planning on using scripting for automated UI testing. Main application is written in c#, and I want it to be scriptable, so I can do everything end-user can do, but programmatically. I'll avoid opinion-based questions like "What do you think of software that provides an interface for scripting, like VBA macros in Excel?", or "Can this be future of all programming, big and small?" although some inside would be great. Here goes the question:   * Which is most suitable to the purpose of building such an interface for your own application, dll-based approach or by parsing own scripting language?


title: What are the definitive guidelines for custom Error Handling in ASP.NET MVC 3?

text: The process of doing custom error handling in ASP.NET MVC (3 in this case) seems to be incredibly neglected. I've read through the various questions and answers here, on the web, help pages for various tools (like Elmah), but I feel like I've gone in a complete circle and still don't have the best solution. With your help, perhaps we can set a new standard approach for error handling. I'd like to keep things simple and not over-engineer this. Here are my goals: **For Server errors/exceptions:**   1. Display debugging information in dev   2. Display friendly error page in production   3. Log errors and email them to administrator in production   4. Return 500 HTTP Status Code **For 404 Not Found errors:**   1. Display friendly error page   2. Log errors and email them to administrator in production   3. Return 404 HTTP Status Code Is there a way to meet these goals with ASP.NET MVC?


title: System state design composition

text: Consider the following Java code:               public class HumanStateImpl implements HumanState {         private boolean alive;         private Color skinColor;              // getters and setters, other state fields              @Override         public boolean isAlive() {             return alive;         }     }      Now imagine I want to have a class that represents `HandState`, and a corresponding `HandController`. **Is it better to inject the state objects of each level of state separately, or compose them into one most-specific state object?** If it depends, what does it depend on? To clarify what I mean, here is an implementation of both sides, respectively:               public class HandState {         private final Side handSide;         private boolean closed;     }          public class HandController {         private final HumanState humanState;         private final HandState handState;              public HandController(HumanState humanState, HandState handState) {             this.humanState = humanState;             this.handState = handState;         }     }      Versus:               public class HandState implements HumanState {         private final HumanState outerState;         private final Side handSide;              public HandState(HumanState outerState, Side handSide) {             this.outerState = outerState;             this.handSide = handSide;         }              @Override         public boolean isAlive() {             return outerState.isAlive();         }     }          public class HandController {         private final HandState handState;              public HandController(HandState handState) {             this.handState = handState;         }     }


title: What defines the dimensionality of an array?

text: I know that when we speak about an array having 1, 2, or 4 dimensions, we mean arrays like this:               1: [0]     2: [0,0]     3: [0,0,0]     4: [0,0,0,0]     ...      Is the first 'axis' of an array the only thing that defines its dimensionality? Can an array with 4 dimensions be represented these ways?               [0, [0,0,0]]     [[0,0], [0,0]]      or does this fall under some other definition of dimensionality? Another option is that a 4-dimensional array would be of the form               [ [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]] ]      e.g.               [        [         [ [0,..],[0,..] ],          [ [0,..],[0,..] ]       ],        [         [ [0,..],[0,..] ],          [ [0,..],[0,..] ]       ],        [         [ [0,..],[0,..] ],          [ [0,..],[0,..] ]       ],        [         [ [0,..],[0,..] ],          [ [0,..],[0,..] ]       ]     ]      Is this just a nomenclature nuance that I'm bringing up? Is this definition relative to the field in which we are discussing (computation vs. physical systems)? * * * _(the thoughtscame from this question.)_


title: When adding 7, 3, and 1 into a red-black tree, do I need to perform a right rotation?

text: If I add the following in this order into a red-black tree:               tree.Put(7)     tree.Put(3)     tree.Put(1)                   7                  3             /   rotate(3)      / \            3    ----->        1   7           /          1      should I perform a right rotation after the insertion of `1` ? I am reading the algorithms bible but it the pseudocode doesn't indicate what to do.


title: using the presence of a value to control flow?

text: I have the following situation. I have a factory method that returns a matrix. This matrix can be calculated at two levels of accuracy: level1 and level2. In order to calculate the matrix, I need to pass a bunch of information to the factory method, and this information is nicely packed in another object Info. Info is passed to the factory method, and the matrix is returned. Info contains details that are needed for both levels of accuracy. a set of these details are used only by level1. If level2 is needed, info must contain additional data which are used to evaluate level2 accuracy. I have two strategies to perform the decision:   1. I pass the Info object to the factory method. If it finds the info for level2, it computes level2 accuracy. If it finds only info for level1, it computes level1.   2. you pass the factory method both the Info data and the requested accuracy level, then use only the Info contents useful for the appropriate level. There may be a case where level2 is requested, but Info does not contain any level2 information. In that case the program will throw an exception. Which option would you consider better ?


title: Passing a Context around with dependency injection

text: In the project I'm working on, I'm using Guice and trying to do as much as possible with Dependency Injection. However, there's one little snag; many of my objects rely on an object `Context`. This is an immutable object but has some information which most of the other objects need to function properly. It never changes for classes that are all working within the same `Context`, but my application must be able to support different `Context`s at the same time, in the same scope. I can think of three ways to solve my problem:   1. Currently, I've found myself writing lots of code with AssistedInject, which almost always has methods like `Factory.create(Context c)`. All my code that depends on `Context` is being created in this manner, even if they are otherwise simple.   2. I'm starting to consider using `Provider`s, and changing every line of `factory.create(context)` to `obj = provider.get(); obj.setContext(c);` but I don't want to rely on my code to do both calls, I like that the compiler makes sure that every object has it's `context` and that the `context` cannot change (it never will).   3. My research pointed me to this thread: http://stackoverflow.com/questions/16316719/guice-assisted-injection-deeper-down-the-dependency-hierarchy The idea of pairing each `Context` to a `childInjector` which has one line `bind(Context.class).toInstance(ContextFactory.makeInstance(args))`, but I'm not sure how to ensure that everything is using the correct child injector. This seems like it might be best, but other than that thread (which isn't my scenario) I'm not sure how to do it, or if it's right for my situation. Here's an sscce of what might be done by option 3:               public class GuiceChildTest {         public static void main(String... args) {             Injector inj = Guice.createInjector(new ParentModule());             Injector fooChildOne = inj.createChildInjector(new FooModule(new Foo(10)));             Injector fooChildTwo = inj.createChildInjector(new FooModule(new Foo(20)));                  Bar bar = fooChildOne.getInstance(Bar.class);             System.out.println(bar.baz());                  bar = fooChildTwo.getInstance(Bar.class);             System.out.println(bar.baz());         }              private static class ParentModule extends AbstractModule {             @Override             protected void configure() {             }         }              private static class Bar {             private MyInterface intf;             @Inject             public Bar(MyInterface in) {                 this.intf = in;             }                  public int baz() {                 return intf.doSomething();             }         }              private static class FooModule extends AbstractModule {             private Foo f;             public FooModule(Foo f) {                 this.f = f;             }                  @Override             protected void configure() {                 bind(MyInterface.class).toInstance(f);             }            }                 private static class Foo implements MyInterface {             private int i;             public Foo(int i) {                 this.i = i;             }             @Override             public int doSomething() {                 return i;             }         }              private static interface MyInterface {             int doSomething();         }     }


title: Business issues in the issue tracker?

text: Most issue trackers are targeted towards developers. But when working in a small team that includes business people: does it makes sense for them to put non-dev issues inside the tracker? I must say I have never heard of that combination. In my full-time job the business things are done somewhere else. But in a startup where you have limited cash, why not put business todos and dev todos in the same tracker?


title: What programming languages and skills are required in addition when building freelance platform with python?

text: I have a question about compatibility and co-integration of programming languages, databases, frameworks, libraries, different API and more (together referred as “items”). I have added a list of items that are planned to be used when building freelance platform/marketplaced, but I would like to know if I am missing anything, or if given combination could result in some compatibility issues. I’ve done a research on mentioned items, but there is still a list of things that are not clear, so I would be grateful to get more information on the topic. Sorry, if I am bad with terminology, codenames, or missing any valuable points to get accurate answer – I will add any additional information, if asked for clarification in any part. Here is basic information to help answer the question: We are looking to build a freelance platform with a need of:   \- high level of modularity and scalability;   \- autonomous development, which is to be processed by semi/fully-independent task groups;   \- ability to integrate/import a lot of third-party APIs (ie. Facebook connect).   Let’s take oDesk for benchmarking (thus at least such functionality possibilities are needed), where some of them are:   \- Business processes / work-flow (client – freelancer connection, client – consultant connection, etc.);   \- User listing and detailed profiling (portfolios, completed projects, etc.);   \- Semantic search;   \- … (ie. at least full currently existing freelance platforms functionality). I’ve developed a list of items that will be used in process of building the freelance platform, which is as follows: **Programming language (and framework): PHP (Zend) vs. Python (Django)**   Decision criteria: modularity (ease of updating individual modules | existing library of modules | ease of creating new modules) | availability of highly skilled work-force | development time | standardization (ease of autonomous development). Result was choosing Python v2.X/v3.X over PHP5.X. Decision was based on part of decision criteria (arguments for Python):   Possibility to update/edit certain module in most cases without a need to change other modules;   No huge hassle to create new modules from scratch (or at least does not take more time or resources as compared to the same result in php);   Approach of python developers seems to create more opportunities for autonomous development (person is developing in a way that others can develop their modules (or fragments of modules) separately, or take over the task quite easily from the point where this person ended – ie. updating).   Overall Python seems as a more long-run oriented solution, which does not create any big drawbacks in a short-run. **Database: MySQL vs. …:**   Decision criteria: functionality | popularity | initial costs | overheads   MySQL was chosen over MsSQL, as it seems to have fully sufficient functionality (in free version) and can be upgraded to enterprise version when it will make financial sense in terms of bandwidth overheads over licensing fees. **Business processes: Apache ODE vs. Oracle BPEL vs. …:**   Decision rules: python compatibility | modularity | customization | availability of highly skilled work-force   No clear decision here yet. Current front-runner seems to be Apache ODE, but adopting modules from one of python libraries, customizing them and creating new ones seems to be attractive option at the moment as well. **Front-end: HTML4/HTML5 + CSS2/CSS3 + AJAX;**   In the beginning there will be web-based UI only, afterwards we will also include desktop and mobile UI. I’ve listed items that are currently considered in order to develop the platform, please refer to any of the points in decision making if You think that they are flawed, and if I should consider more, or different decision criteria, which could influence which item to pick, etc. **Other things under consideration**   1) Have I picked proper combination of items considering they will be used for developing freelance platform; (1.1) Am I missing any items that will be necessary (ie. programming language / framework / platform); 2) Is it reasonable to use django framework to save time on development and could it result in some major scalability issues; (2.1) What libraries should be considered using to acquire as many prebuilt modules for freelance platform as possible; 3) BPEL (ie. using Apache ODE) can be adopted for a variety of business processes (including client-freelancer connection), but wouldn’t it result in great restrictions of what solutions can we offer; (3.1) Would it be better to consider developing our own modules in python to achieve needed result; (3.2) Or is there any python library that supports BPEL; 4) Is it possible to connect python with php in terms of using php libraries (example: http://code.google.com/p/php-excel/) when ones are not available in python;(4.1) If yes, what modules/platforms/solutions are needed for it; I will update any parts if needed as soon as I get feedback on it. Looking for Your answers. Thanks!


title: Implementing Generic Routines

text: Is it possible to implement generic routines in any language (C#, Java, etc). By generic routines I mean, in specific event Handlers. Lets say, I have 2 Buttons and 2 text boxes. One Button, when pressed, takes the first text box text and converts to Uppercase and second button prints the length of the string in the other text box. Now, Can I have a function as               button(type, textbox) {     if(type==1)     /*Convert to upper case*/     else if(type==2)     /*Print the length*/     }      The type takes any button as input and further processes it. I want to implement this because of redundancy in my code and I want to make my code portable to other languages. So that I need to modify only the syntax to make it work. Is it feasible?


title: Can I use "user stories" for process improvement tasks?

text: We currently use JIRA to track our development work. My management wants to format and categorize everything as "User Stories," including non-software development related tasks. For example: "As a test manager, can I perform testing of the application using only automated tests and no manual testing so that I can test the application as efficiently as possible? Acceptance Criteria: 1\. Convert 50 existing manual tests to fully automated tests 2\. Tests must execute in less than 1 hour" I want to get a sense from the community if it makes sense to use "user stories" for work that supports the software development process, is not done by the programmers, and does not directly results in deliverable code. Or should this be handled/classified differently (for example, in JIRA)? Updated 6/7/2011 - Rephrased question to focus on "user story" term.


title: Building a web application that is almost completely rendered by Javascript, while back end only delivers Json. Do or don't?

text: As a programmer, and taking into account the overall "funness" of the process, I'm tempted to start a project in Sinatra where the back end's sole concern is the logic, and returning a Json API, and then writing a javascript application that would interact with that API for rendering the actual content to the user. I'm fairly new to programming and I've never done anything remotely like this before. What would be the pitfalls, advantages and disadvantages of completely separating logic from presentation in such a way? Any examples of this being done in the wild? One concern off the top of my head is how would search engines respond to a site whose content is almost entirely served as Json...


title: T-SQL stored procs orders of magnitude faster than LINQ

text: According to answers I've seen on stackoverflow, stored procedures (and to a lesser extent db functions) tend to perform better vs. LINQ + ORM frameworks (e.g. Entity Framework). I want to determine if the performance difference is large enough to justify an increase in development time, assuming it takes more time to write equivalent, reasonably complex query operations in T-SQL vs. LINQ. In which scenarios is there an order-of-magnitude (or at least a very large constant factor) difference in running time, between a performance-optimized stored proc and its equivalent, performance-optimized LINQ counterpart? Or for scalar- or table- valued functions vs. the LINQ equivalent? Hopefully, it is not too difficult to see that this question follows the guidelines per the FAQ. It's not asking a subjective question like, "which is better, T-SQL or LINQ?". It's asking for a few specific scenarios (can give abstract or concrete examples) where there is a significant difference in performance. If that still doesn't make sense to you, and you still think this question is not constructive and should be closed, please leave an explanation why if you can.


title: Is Selling GPL licensed Software Effective?

text: Let us say that someone writes a piece of software and licenses it under the GPL. Then they go on to sell it. Will this be effective? Won't someone just buy it and redistribute at a lower price? Do any of you know GPL licensed software that is being sold? Also if you know of any instances where someone bought such software and redistributed at a lower price/free please share it here.


title: Is Flash disappearing?

text: http://w3techs.com/technologies/details/cp-flash/all/all People don't use Flash anymore? Why?


title: Are there similarities between operating system kernels and programming language kernels?

text: I know very little about Smalltalk but I noticed that there's a frequent mention of the "kernel". Dan Ingalls prime maintainer of several implementations of Smalltalk also worked on a Javascript environment called "Lively Kernel" and in Peter Siebel's book he kept mentionning the "kernel". I cannot help but think that it is no coincidence that the creators of Smalltalk used the name of a (central) part of operating systems to refer to a particular component of their language. Was it because Smalltalk intended to act as an operating system? Was it because theory behind programming languages and operating systems have a lot in common? What is the reason behind the common appelation of the two components?


title: Error Handling Strategies in Multithreaded Environments

text: **TL;DR** What error generating and handling strategies do you use in Multithreaded code intended for use by others and why do you use them? If applicable, state what programming paradigm it's useful for. I'm more interested in imperative, concurrent environments but any in general will be useful. I'm writing a little concurrency library that's currently a pet/C++11 learning project but may be used internally by my work later. In terms of the domain it's more in the realm of DSP and media streaming but since this will be used in a game engine I need fairly strong error handling. My big block at the moment is not getting my head around the parallel code and data structures but how to do error handling and reporting. My main experience in large systems is games but I'm usually using libraries, not designing them. I'm just looking for different strategies and how they might be used in different situations as this is a rather big gap in my knowledge. My biggest area of concern is employing a strategy so that if the program can recover, it should. If it does recover, there should be a way to notify a user as to what's happened through some kind of mechanism. Already I have some some data structures that although they can recover, memory may be leaked if a destructor fails for example. Some Approaches:   * Handle exceptions for which you can safely recover from inside the library, but let fatal exceptions propagate to users of the library to indicate that object is now in an undefined state. It's my preferred approach in single threaded environments but this approach won't communicate bad state to other threads.   * When an exception occurs that would put a data structure in an unrecoverable state, tear down the data structure and set a flag to block any more operations over that data structure then raise a general exception to the end user. This is hard for lock-free algorithms.    * Forward an error state through parallel computations. Works well for Kahn process networks and other high level concurrency models. No so helpful if a primitive supporting the high level model has failed.    * Terminate the thread/task that caused the exception. Works well for thread local data/computation but not much of a solution for shared data. Just as a note, I know that a good library will probably use a mix of more than just what's listed above. I just don't have the experience to know what strategy is good where for any sufficiently large system.


title: Where to put business rules before deleting entity

text: I have a Windows Forms App which has two classes:               Public Class Account         Public Property Number as String         Public Property Invoices as List(Of Invoice)     End Class          Public Class AccountRepository         Public Sub Delete(account as Account)              ...db access code here...         End Sub     End Class      The business logic is that an `Account` can't be deleted while it still has `Invoices` associated with it. How and where should I do the validation? _Note I could also do it via table restrictions on db foreign keys._


title: How to prove an application is built on a bad codebase?

text: I'm currently reviewing a system built by some developers that previously worked at my job. The system works pretty well from a user's point of view, but when delving into code review it's a utter mess. I'm more than convinced that the way the application is built won't hold up for future updates, let alone high increases in usage. The problem is that I know how bad it is, but my superiors don't. How can I prove it to my manager so he actually sees the problem and can be convinced to do minimal triage on the current codebase, and in the near future start a new line of development for the next version of the application?


title: Best approach for utility class library using Visual Studio

text: I have a collection of classes that I commonly (but not always) use when developing WPF applications. The trouble I have is that if I want to use only a subset of the classes, I have three options:   1. **Distribute the entire DLL.** While this approach makes code maintenance easier, it does require distributing a large DLL for minimal code functionality.   2. **Copy the classes I need to the current application.** This approach solves the problem of not distributing unused code, but completely eliminates code maintenance.   3. **Maintain each class/feature in a separate project.** This solves both problems from above, but then I have dramatically increased the number of files that need to be distributed, and it bloats my VS solution with tiny projects. Ideally, I'd like a combination of 1 & 3: A single project that contains all of my utility classes but builds to a DLL containing only the classes that are used in the current application. Are there any other common approaches that I haven't considered? Is there any way to do what I want? Thank you.


title: Violation of the C definition?

text: The C standard states that any character in the machine's standard printing set will never be negative.But the following code:               char c=1234;     printf("%d\t%c",c,c);      gives a negative output and prints a strange character,meaning that the character is in machine's printing character set.Is the C standard being violated here?


title: Is it a good idea to write requirements specifications by stories?

text: We're using agile methods in my current project at the moment, and we have heaps of stories like these:   * As an assistant, I want to pay a customer a refund so that they can get some money when they request it   * As a customer, I want to pay for a purchase so that I can receive my item. How we've done it so far is to pick the most important stories every sprint and elaborate it into a number of formal requirements specs (we group some of the stories that are similar together in the same spec). Depending on the story, it could just be a button on a screen or an entire workflow. The problem now is that because there's so many stories, it's not immediately clear, for any part of the system which stories relate to it. It works at the time of developers, every sprint the devs just get a spec outlining what they need to do and the changes they need to make. But in terms of maintaining this story list and for testing, its starting to get really hard tracking bugs and in general just maintaining the specs, because one piece of functionality in the screen might have been documented in a number of different places due to it being split by story. Is writing specs based on stories a good idea? Have we written the stories in the wrong way?


title: How do you deal with lack of consensus on methodology and practices, without direction from management?

text: Until recently, I was the sole developer on several in-house projects. A few months ago, we added 0.4 of an FTE to our development team. It's nice not being alone on our projects, but it hasn't been easy. A bit of background: when I started in my position, there was no use of source control, issue tracking, or even testing. I implemented all of these practices myself, and the improvement in productivity has been noticed by multiple stakeholders. Our new 0.4FTE is basically 40% of the time of an employee in another department. He's a competent programmer, but collaboration has been difficult. Several months in, I'm still experiencing:   * Emailed source files rather than repositories being checked in to Git.   * Use of email and instant messaging instead of the issue tracker to discuss the project.   * Resistance to code reviews.   * Ego getting in the way of pair programming or early collaboration on components (i.e., I don't want to show you the source for this yet, it's ugly). Our department is weird. Our team lead has to divide his time between project management, system administration, and hardware installs/support. We got into probably the worst argument we've ever had over how I expected to interact with another developer vs. "This is just how he is, you need to email in addition to submitting an issue, etc." My question is, how do you deal with this? I've tried various approaches; refusing to acknowledge issues without a ticket, refusing to look at code not checked in to our Git repo, but ultimately, I'm the de facto lead developer on this project, and like it or not, I shoot myself in the foot by being a stickler for process. At the same time, I'm driving myself crazy (to the point of looking for a new job) in the process of trying to deal with the lack of coherent (or at least, enforceable) guidelines. I've brought up the notion with colleagues outside our department that maybe it's just a bad fit, but sadly, we don't have much of an option at this point. Any ideas for ameliorating this situation would be greatly appreciated.


title: What is a symbol in Ruby?

text: I'm totally new to the Ruby world, and I'm a bit confused with the concept of Symbols. What's the difference between Symbols and Variables? Why not just using variables? Thanks.


title: Why do most programming languages only support returning a single value from a function?

text: Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value? In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way. Is there an explanation for this?


title: How does one request / handle personal or financial information?

text: I would like to create a budget app for Android. Obviously, to be competitive, I would need to allow users to get data from their bank. For [huge] security reasons, this stuff is not just freely given to any would be developer, but I know it can be done. There are budget apps that connected to users banks. My question is, what do I need to do to poll users bank data? Do I need to contact every bank that I wish my app to deal with? Do I need to write the app and present it the the bank(s)? Or am I just too ignorant to take on a challenge of this magnitude? I ask because I obviously don't know the standards that are needed here and would like to learn about them, even if it ends up that I cannot write the bank interface section of my app.


title: Dynamically vs Statically typed languages studies

text: Do there exist studies done on the effectiveness of statically vs dynamically typed languages? In particular:   * Measurements of programmer productivity   * Defect Rate Also including the effects of whether or not unit testing is employed. I've seen lots of discussion of the merits of either side but I'm wondering whether anyone has done a study on it. **Edit** Sadly, only one of the papers shown is actually a study and it does nothing but conclude that the language matters. This leads me to ponder: what if I proposed doing such a study with volunteers from this site?


I'm studying dependency injection and I want to know if required function parameters can be considered dependencies. I'd just like to make sure before I go around referring to them dependencies and that turns out to not be exactly accurate.               function doSomething(required){              if(required !== null){                  // do stuff              }          }      **Are the required parameters of a function called dependencies?**


title: Mobile application: What should be the server authentication strategies?

text: I am developing an mobile application for the first time and have some confusions around it **What I plan to do?**   The `iPhone` application will have `Sign in with Google` where user will authenticate on client side (I don't plan to have server access unless needed) and the user details (id, email for example) will be send to backend server (planning to write RESTful APIs in Java). **What is the confusion then?**   1. Since multiple mobile devices would be hitting the APIs what would be CORS settings on the server? Would it allow **ALL** origins?   2. If the application authenticates on client side, how can backend makes sure that this is authenticated user only and no one is playing around with the system(by playing around with REST API)   3. The problem goes to next level when multiple providers are involved, example Facebook, Twitter  What are the recommendations, how should the system be designed in this case? Thanks P.S Sorry for not making it `programmatic` question.


title: Why does Haskell's built in max function run faster than mine?

text: I noticed that for some reason, Haskell's built in max function (which returns the greatest of two numbers) runs much faster than the one I wrote, even though they are essentially identical. From this site: http://www.haskell.org/onlinereport/standard-prelude.html, I found that the standard max function is defined as:                   max x y           | x <= y    =  y          | otherwise =  x      which is capable of executing               foldr max 0 [0..10000000]      in 7.6 seconds (my laptop is in super power saving mode) I wrote the exact same function though, and ran it, and               foldr myMax 0 [0..10000000]      took an average of 23.74 seconds The two functions look identical, except that the built-in max doesn't seem to have a type signature (unless its hidden somewhere.) Does anyone know what might be going on here? I seriously doubt that a built in function will run more than three times faster than an identical, user defined one. To me that would be very strange. (When I say that they're identical, I mean literally clones of each other. Just to test, I C&P'd it right out of the Prelude, and it's still significantly slower.) Edit: I thought about it more, and I think it might have something to do with the included functions being pre-compiled, where-as my functions are being interpreted via GHCI (Which would make sense then). I'll leave this up in case someone has a better answer, but I suspect this to be the cause. (One thing I realized that I don't understand though is why GHCI says that's it compiled my code after an edit, but then goes on the say that's it's interpreting it. You don't interpret compiled code do you?)


title: When is it the right time to start applying for jobs?

text: I am a graduate student in CIS, had BS in EE. I will be graduating next spring. This means I still have one more semester before I graduate. I really don't want to start looking for jobs after I graduate. The problem is that I will be doing some heavy courses along with a project next semester. I really want to snag something this semester, but do you think employers would recruit candidates so early?


title: The Definition of "Strong Type Systems"

text: I saw Martin Odersky's "The Trouble with Types" presenstaion. He divided programing-languages in two dimensions in the "Type Systems Landscape" chart; A "Static/Dynamic" dimension and A "Strong/Weak" one. I searched to find a definition for "strong/weak type systems" and its difference from "static/dynamic" type-systems that can explain why Python/Ruby have a "strong type system"? I've found something on Wikipedia, but it hasn't satisfied me. Now I want to know what's the "strong/weak"? and How Python has a strong type system (like as scala)? Is it about inheritance / composable / primitive types in a language or not? If 'no', What's the the concept and measurement-unit for these features (inheritance / compose / primitive / container / ...) in the type-systems?


title: What is a good design pattern for generating an Excel (xlsx) file in code?

text: I occasionally have projects where I have to output some data as an Excel file (xlsx format). The process is usually:   1. User clicks some buttons in my application   2. My code runs a DB query and processes the results somehow   3. My code generates an *.xlsx file using either the Excel com interop libraries or some third-party library (e.g., Aspose.Cells) I can easily find code examples for how to do this online, but I am looking for a more robust way to do this. I'd like my code to follow some design principles to ensure that my code is maintainable and easily understandable. * * * Here is what my initial attempt to generate an xlsx file looked like:               var wb = new Workbook();     var ws = wb.Worksheets[0];     ws.Cells[0, 0].Value = "Header";     ws.Cells[1, 0].Value = "Row 1";     ws.Cells[2, 0].Value = "Row 2";     ws.Cells[3, 0].Value = "Row 3";     wb.Save(path);      Pros: Not much. It works, so that's good. Cons:   * Cell references are hardcoded, so I have magic numbers littered throughout my code.   * It's difficult to add or remove columns and rows without updating many cell references.   * I need to learn some third-party library. Some libraries are used like other libraries, but there can still be problems. I had a problem where the com interop libraries use 1-based cell referencing whereas Aspose.Cells uses 0-based cell referencing. * * * Here is one solution that addresses some of the cons I listed above. I wanted to treat a table of data as its own object that can be moved around and changed without digging into cell manipulation and disturbing other cell references. Here is some pseudocode:               var headers = new Block(new string[] { "Col 1", "Col 2", "Col 3" });     var body = new Block(new string[,]         {             { "Row 1", "Row 1", "Row 1" },             { "Row 2", "Row 2", "Row 2" },             { "Row 3", "Row 3", "Row 3" }         });          body.PutBelow(headers);      As a part of this solution, I'll have some BlockEngine object that takes a container of Blocks and performs the cell manipulations required to output the data as an *.xlsx file. A Block object can have formatting attached to it. Pros:   * This removes most of the magic numbers that my initial code had.   * This hides a lot of cell manipulation code, although cell manipulation is still required in the BlockEngine object that I mentioned.   * It's much easier to add and remove rows without effecting other parts of the spreadsheet. Cons:   * It's still difficult to add or remove columns. If I wanted to swap the position of columns two and three, I'd have to directly swap the cell contents. In this case that'd be eight edits, and thus eight opportunities to make a mistake.      * If I have any formatting in place for those two columns, I have to update that as well.   * This solution doesn't support horizontal block placement; I can only place one block below another. Sure I could have `tableRight.PutToRightOf(tableLeft)`, but that would cause problems if tableRight and tableLeft had different numbers of rows. To place tables, the engine would have to be aware of every other table. This seems unnecessarily complicated to me.   * I still need to learn third-party code, though through a layer of abstraction via Block objects and a BlockEngine the code will be less tightly-coupled to the third-party library than my initial attempt. If I wanted to support lots of different formatting options in a loosely-coupled way, I'd probably have to write a lot of code; my BlockEngine would be a huge mess. * * * Here is a solution that takes a different route. Here's the process:   1. I take my report data and generate an xml file in some format that I choose.   2. I then use an xsl transformation to convert the xml file to an Excel 2003 XML Spreadsheet file.   3. From there I simply convert the xml Spreadsheet to an xlsx file using a third party library. Pros:   * This solution requires almost no cell manipulation. You instead use xsl/xpath to do your manipulations. In order to swap two columns in a table, you move the whole columns in the xsl file unlike my other solutions which would require cell-swapping.   * While you still need a third-party library that can convert an Excel 2003 XML Spreadsheet to an xlsx file, that's about all you'll need the library for. The amount of code you need to write that would call into the third-party library is tiny.   * I think this solution is the easiest to understand and requires the least amount of code.      * The code that creates the data in my own xml format will be simple.      * The xsl file will be complicated only because the Excel 2003 XML Spreadsheet is complicated. However it's easy to check the output of the xsl file: just open the output in Excel and check for error messages.     * It's easy to generate sample Excel 2003 XML Spreadsheet files: just create a spreadsheet that looks like your desired xlsx file, and then save it as an Excel 2003 XML Spreadsheet. Cons:   * Excel 2003 XML Spreadsheets don't support certain features. You can't autofit column widths for instance. You can't include images in headers or footers. If you're going to export the resultant xlsx file to pdf, you can't set pdf bookmarks. (I hacked together a fix for this using cell comments.). You have to do this using your third-party library.   * Requires a library that supports Excel 2003 XML Spreadsheets.   * Uses an 11-year old MS Office file format. Note: I realize that xlsx files are actually zip files containing xml files, but the xml formatting seems too complicated for my purposes. * * * Finally, I've looked into solutions involving SSRS, but it seems too bloated for my purposes. * * * Back to my initial question, what is a good design-pattern for generating Excel files in code?. I can think of a few solutions, but none seem to stick out as ideal. Each has drawbacks.


title: Strategy for generating unique and secure identifiers for use in a "sometimes offline" web app

text: I have a web based project that allows users to work both online and offline and I'm looking for a way to generate unique ids for records on the client side. I'd like an approach that works while a user is offline (i.e. unable to talk to a server), is guaranteed to be unique, and is secure. By "secure", I'm specifically worried about clients submitting duplicate id's (maliciously or otherwise) and thereby wreaking havoc on data integrity. I've been doing some googling, hoping this was already a solved problem. I haven't found anything that's very definitive, especially in terms of approaches that are in use in production systems. I found some examples for systems where users will only access the data that they've created (e.g. a Todo list that's accessed on multiple devices, but only by the user who created it). Unfortunately, I need something a bit more sophisticated. I did find some really good ideas here, which are in line with how I was thinking things might work. Below is my proposed solution. ## Some Requirements   1. IDs should be globally unique (or at least unique within the system)   2. Generated on the client (i.e. via javascript in the browser)   3. Secure (as outlined above and otherwise)   4. Data can be viewed/edited by multiple users, including users who didn't author it   5. Doesn't cause significant performance issues for backend db's (such as MongoDB or CouchDB) ## Proposed Solution When users create an account, they would be given a uuid which was generated by the server and known to be unique within the system. This id must NOT be the same as the users authentication token. Let's call this id the users "id token". When a user creates a new record, they generate a new uuid in javascript (generated using window.crypto when available. See examples here). This id is concatenated with the "id token" the user received when they created their account. This new composite id (server side id token + client side uuid) is now the unique identifier for the record. When the user is online and submits this new record to the backend server, the server would:   1. Identify this as an "insert" action (i.e. not an update or a delete)   2. Validate both parts of the composite key are valid uuids   3. Validate that the provided "id token" part of the composite id is correct for the current user (i.e. it matches the id token the server assigned to the user when they created their account)   4. If everything is copasetic, insert the data into the db (being careful to do an insert and not an "upsert" so that if the id _does_ already exists it doesn't update an existing record by mistake) Queries, updates, and deletes wouldn't require any special logic. They would simply use the id for the record in the same manner as traditional applications. ## What are the advantages of this approach?   1. Client code can create new data while offline and know the id for that record immediately. I considered alternate approaches where a temporary id would be generated on the client which would later be swapped out for a "final" id when the system was online. However, this felt very brittle. Especially when you start thinking about creating child data with foreign keys that would also need to be updated. Not to mention dealing with urls that would change when the id changed.   2. By making ids a composite of a client generated value AND a server generated value, each user is effectively creating ids in a sandbox. This is intended to limit the damage that can be done by a malicious/rogue client. Also, any id collisions are on a per user basis, not global to the entire system.   3. Since a users id token is tied to their account, ids can only be generated in a users sandbox by clients that are authenticated (i.e. where the user successfully logged in). This is intended to keep malicious clients from creating bad ids for a user. Of course if a users auth token were stolen by a malicious client, they could do bad things. But, once an auth token has been stolen the account is compromised anyhow. In the event that this did happened, the damage done would be limited to the compromised account (not the entire system). ## Concerns Here are some of my concerns with this approach   1. Will this generate sufficiently unique ids for a large scale application? Is there any reason to think this will result in id collisions? Can javascript generate a sufficiently random uuid for this to work? It looks like window.crypto is fairly widely available and this project already requires reasonably modern browsers. (this question now has a separate SO question of its own)   2. Are there any loopholes that I'm missing which could allow a malicious user to compromise the system?   3. Is there reason to worry about DB performance when querying for a composite key made up of 2 uuids. How should this id be stored for best performance? Two separate fields or a single object field? Would there be a different "best" approach for Mongo vs Couch? I know that having a non-sequential primary key can cause notable performance issues when doing inserts. Would it be smarter to have an auto generated value for the primary key and store this id as a separate field? (this question now has a separate SO question of its own)   4. With this strategy, it would be easy to determine that a particular set of records was created by the same user (since they'd all share the same publicly visible id token). While I don't see any immediate issues with this, it's always better to not leak more info about internal details than is needed. Another possibility would be to hash the composite key, but that seems like it may be more trouble than it's worth.   5. In the event that there is an id collision for a user, there's not a simple way to recover. I suppose the client could generate a new id, but this seems like a lot of work for an edge case that really shouldn't ever happen. I'm intending to leave this unaddressed.   6. Only authenticated users can view and/or edit data. This is an acceptable limitation for my system. ## Conclusion Is above a reasonable plan? I realize some of this comes down to a judgement call based on a fuller understanding of the application in question.


title: Server-side vs Client-side web application Performance

text: I am an entry level programmer with only a few months of experience. Yesterday I was discussing with a colleague how we can improve the performance of a project we are working on together. The project is built with C# + Ext.NET + JS The plan was to move as many things as possible to client-side JavaScript instead of interacting with the server all the time. I thought this was a good idea, but couldn't help but wonder if there is a point where bringing everything to client-side starts making the web application slower. I understand that interacting with the server and reloading unnecessary data all the time is a waste of time in most cases, but I've also seen websites loaded with so much JS that the browser actually lags and the browsing the web application is just a pain. Is there a golden point? Are there certain 'rules'? How do you achieve maximum performance? Take Google Cloud apps, such as Docs for example, they're pretty fast for what they do, and they're web applications. That is some very good performance.


title: At what point should one consider using sql databases?

text: As the size of my data and the structures I use to hold it get larger and more complex, I start to wonder if I should learn to use sql databases. In the past, instead of unique tables, I would do something like the following:               'class Dog            String name            Toy[] toys            long  numberOfHairs            short numberOfFlees            etc.      Then I might have a sorted array based on numberOfFlees, a hash of names, a set of toys, etc. to suit my needs. This has worked fine for me with smaller projects, but at what point should I consider SQL. What will I lose and gain?


title: Arithmetic Coding Questions

text: I have been reading up on arithmetic coding and, while I understand how it works, all the guides and instructions I've read start with something like: > Set up your intervals based upon the frequency of symbols in your data; > i.e., more likely symbols get proportionally larger intervals. My main query is, once I have encoded my data, presumably I also need to include this statistical model with the encoding, otherwise the compressed data can't be decoded. Is that correct? I don't see this mentioned anywhere -- the most I've seen is that you need to include the number of iterations (i.e., encoded symbols) -- but unless I'm missing something, this also seems necessary to me. If this is true, that will obviously add an overhead to the final output. At what point does this outweigh the benefits of compression (e.g., say if I'm trying to compress just a few thousand bits)? Will the choice of symbol size also make a significant difference (e.g., if I'm looking at 2-bit words, rather than full octets/whatever)?


title: Build filter conditions for entities on client side

text: I have the requirement that users should be able to specify filter conditions for one kind of entity through a GUI on a thin client. These conditions must be   * convenient to generate, meaning the GUI should guide users as much as possible. They shouldn't have to write SQL or anything.   * stored with a time stamp, a user ID, a description, and whatnot...   * loaded and edited   * reusable by other users   * used for loading matching entities from the DB via an ORM framework. Ideally I could generate a predicate out of them - SQL or maybe an Expression, which the ORM can translate to SQL In my case users specify a condition for customers, for who invoices should be generated. There will be many different such "customer selections". I think the specification pattern might be a good match, but couldn't find any examples, where specifications are built through a GUI, serialized and stored/reloaded/edited via an app server and used to retrieve matching entities. Am I maybe overlooking the standard way to do such a thing? Colleagues have suggested to just build the SQL WHERE predicate on client side, but I don't like that. The client shouldn't know that much about persistence (column names...), and should only be allowed to use certain predicates, but not others. Also I'd have to parse these strings into separate predicates when I reload a condition to display them in a user friendly way.


title: Should the helper function in class be defined before the usage or after

text: I need to do the code review of fellow members. One of the member always defined the helper functions at the bottom and use them at top e,g               class Sample {          public function SendFile(){     file = $this-convertFile($file);     }          public function convertFile(){     //bla bla     }          }      I sometimes dont know if he has custom defined this function of it is inherited from base class or some builin php function . when i reach bottom then i find it was custom defined