Single-responsibility and custom data types

In the past months I've asked for people here on SE and on other sites offer me some constructive criticism regarding my code. There's one thing that kept popping out almost every time and I still don't agree with that recommendation; :P I'd like to discuss it here and maybe things will become clearer to me. It's regarding the single-responsibility principle (SRP). Basically, I have a data class, `Font`, that not only holds functions for manipulating the data, but also for loading it. I'm told the two should be separate, that loading functions should be placed inside a factory class; I think this is a mis- interpretation of the SRP... ## A Fragment from My Font Class               class Font     {       public:         bool isLoaded() const;         void loadFromFile(const std::string& file);         void loadFromMemory(const void* buffer, std::size_t size);         void free();              void some();         void another();     };      ## Suggested Design               class Font     {       public:         void some();         void another();     };               class FontFactory     {       public:         virtual std::unique_ptr<Font> createFromFile(...) = 0;         virtual std::unique_ptr<Font> createFromMemory(...) = 0;     };      The suggested design supposedly follows the SRP, but I disagree -- I think it goes too far. The `Font` class is not longer self-sufficient (it is useless without the factory), and `FontFactory` needs to know details about the implementation of the resource, which is probably done through friendship or public getters, which further expose the implementation of `Font`. I think this is rather a case of _fragmented responsibility_. Here's why I think my approach is better:   * `Font` is self-sufficient -- Being self-sufficient, it's easier to understand and maintain. Also, you can use the class without having to include anything else. If, however, you find you need a more complex management of resources (a factory) you can easily do that as well (later I'll talk about my own factory, `ResourceManager<Font>`).   * Follows the standard library -- I believe user-defined types should try as much as possible to copy the behavior of the standard types in that respective language. The `std::fstream` is self-sufficient and it provides functions like `open` and `close`. Following the standard library means there's no need to spend effort learning yet another way of doing things. Besides, generally speaking, the C++ standard committee probably knows more about design than anyone here, so if ever in doubt, copy what they do.   * Testability -- Something goes wrong, where could the problem be? -- Is it the way `Font` handles its data or the way `FontFactory` loaded the data? You don't really know. Having the classes be self-sufficient reduces this problem: you can test `Font` in isolation. If you then have to test the factory and you know `Font` works fine, you'll also know that whenever a problem occurs it must be inside the factory.   * It is context agnostic -- (This intersects a bit with my first point.) `Font` does its thing and makes no assumptions about how you'll use it: you can use it any way you like. Forcing the user to use a factory increases coupling between classes. ## I too Have a Factory **(Because the design of`Font` allows me to.)** Or rather more of a manager, not merely a factory... `Font` is self-sufficient so the manager doesn't need to know _how_ to build one; instead the manager makes sure the same file or buffer isn't loaded into memory more than once. You could say a factory can do the same, but wouldn't that break the SRP? The factory would then not only have to build objects, but also manage them.               template<class T>     class ResourceManager     {       public:         ResourcePtr<T> acquire(const std::string& file);         ResourcePtr<T> acquire(const void* buffer, std::size_t size);     };      Here's a demonstration of how the manager could be used. Notice that it's used basically exactly as a factory would.               void test(ResourceManager<Font>* rm)     {         // The same file isn't loaded twice into memory.         // I can still have as many Fonts using that file as I want, though.         ResourcePtr<Font> font1 = rm->acquire("fonts/arial.ttf");         ResourcePtr<Font> font2 = rm->acquire("fonts/arial.ttf");              // Print something with the two fonts...     }      ## Bottom Line... (It'd like to put a tl;dr here, but I can't think of one. :\ )   Well, there you have it, I've made my case as best as I could. Please post any counter-arguments you have and also any advantages that you think the suggested design has over my own design. Basically, try to show me that I'm wrong. :)


What must testers be able to do to be 'highly qualified'?

**Are modern testers like 'stupid' users which try to find a bug clicking and filling fields or they have solid knowledge about product cores?** What modern testers must be able to do?   * Must they be coders creating independant/embed tests?   * Must they understand source code of products and even can fix easy bugs?   * Other things? I'm interested in real practice.


Javascript naming conventions

I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.               doSomething(a,b,c)      I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser. Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster. Is this a standard practice for web browsers? What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?


Building a webservice with mvc

I'am planning my website over here based on MVC. And I am thinking about a webservice (who knows, maybe one day I'll create an android app or something). The site and the webservice will behave diferently from each other. So what should I do? Write different controllers for each... or stuff IFs all over the place? For example: on the site, the controller will act as such:   Password correct?   \---->redirect user to welcome screen   Password incorrect?   \---->render login page again   But the webservice will simple show a json like:   {message: 'wrong password/sucess'} Which one you think is the best approach?


Tooling and support for message format specifications

How do most companies define and manage message format specifications? Is it common for companies to create custom tools for creating and working with these documents? At work we have a lot of systems that communicate via UDP messages. Each system has its own Interface Control Document (in Word or in HTML) which describes its message scheme. The documents have descriptions of each message along with its fields, and usage notes. We're looking to standardize the format of these ICDs and write some tools that help create them. I was thinking we should create an ICD schema, and define the ICDs in some data-interchange format (XML, JSON, protobuf). Then we could create parsers that generate human-readable documentation (HTML, PDF), or even message parsing code (where useful and appropriate). I don't want to reinvent the wheel, and I don't want to get too carried away. Does the above proposal sound reasonable?


Should I create my own Assert class based on these reasons?

The main reason I don't like Debug.Assert is the fact that these assertions are disabled in Release. I know that there's a performance reason for that, but at least in my situation I believe the gains would outweigh the cost. (By the way, I'm guessing this is the situation in most cases). And yes, I know that you can use Trace.Assert instead. But even though that would work, I find the name Trace distracting, since I don't see this as tracing. The other reason to create my own class is laziness I guess, since I could write methods for the most usual cases like Assert.IsNotNull, Assert.Equals and so forth. The second part of my question has to do with using Environment.FailFast in this class. Would that be a good idea? I do like the ideas put forth in this document. That's pretty much where I got the idea from. One last point. Does creating a design like this imply having an untestable code path, as described in this answer by Eric Lippert on a different (but related) question?


Can the JSF 2.0.0 code be converted to JavaScript/HTML5?

I am developing an application using WebSocket to exchange messages; it is based on JSF 2.0.0, but the idea is similar and HTML5 have WebSocket support. Is the only difference between those language the used tag and the syntax? Is the logic behind it the same? I wonder if there any converter for this.


Is it a waste of time to free resources before I exit a process?

Let's consider a fictional program that builds a linked list in the heap, and at the end of the program there is a loop that frees all the nodes, and then exits. For this case let's say the linked list is just 500K of memory, and no special space managing is required.   * Is that a wast of time, because the OS will do that anyway?   * Will there be a different behavior later?   * Is that different according to the OS version? I'm mainly interested in UNIX based systems, but any information will be appreciated. I had today my first lesson in OS course and I'm wondering about that now. **Edit:** Since a lot of people here are concerned about side effects, and general 'good programming practice' and so. You are right! I agree 100% with your statements. But my question is only hypothetical, I want to know how the OS manages this. So please leave out things like 'finding other bugs when freeing all memory'.


Is Silverlight only for eye-candy, or does it have a use in business?

Granted that Silverlight may make eye-popping websites of great beauty, is there any justification for using it to make practical web applications that have serious business purposes? I'd like to use it (to learn it) for a new assignment I have, which is to build a web-based application that keeps track of the data interfaces used in our organization, but I'm not sure how to justify it, even to myself. Any thoughts on this? If I can't justify it then I will have to build the app using the same old tired straight ASP.NET approach I've used (it seems) a hundred times already.


Class table inheritance... To 'type' or not to 'type'

I currently have a database that uses Class table inheritance model. Three different tables inherit from this table. The child tables have all a FK to the parent table and the fields are properly indexed. We hare currently having some issues at the application level because it is difficult to figure out what child table we are referencing from the parent. In addition to this, a query where we organize by type seems costly. One developer argues that we should just join with all 3 tables to figure out what child the parent record corresponds to, and as long as the tables have the proper index queries shouldn't be costly. In the other hand we could avoid a lot of confusion and problems if we add a discriminator field in the parent table, that way we would know without having to do any joins the 'type' of record we are dealing with. Also grouping by type would be much simpler.   * Should we add a type in the parent table?    * What would be the disadvantages?   * Is it really not costly to join with multiple tables (as long as they are properly indexed) compared to having a discriminator field?   * Other thoughts? We are currently using an implementation of active record for PHP, and it doesn't support Class Table Inheritance.


Where should we put External Libraries in our SVN?

We have the following SVN structure.   * Projects: Our work   * Clients: Projects for clients, needs to be different   * Shared: Shared libraries we created   * Docs: Documents explaining how software development flows within the company (has nothing to do with my question anyway) Where should we put the external libraries? Let's say from opensource projects etc. ![enter image description here](http://i.stack.imgur.com/dYENF.png)


For what types of applications is Python a bad choice?

I just started learning Python, and I'd like to get some more context on the language. I realize that, in many cases, Python is a slow language relative to C or C++. Thus, Python is probably not the best choice for applications that need to run as quickly as possible. Outside of this, it seems like Python is a great general purpose language that is easy to read and write. The available libraries give it a huge amount of functionality. Outside of performance critical applications, where is it a bad choice to use Python (and why)?


How can I decouple configuration data from the program that uses it?

I am a beginning programmer who has written a spider application in PHP. Currently there are three parts:               1) The Spider (spider.php)     2) The Harvester (harvest.php)     3) The Configuration file (for example, craigslist_config.php)      I use the spider to search the web for items I want to buy. An item can be found on any website, like ebay, craigslist, etc. The Harvester provides three functions to spider so it can act on the data it finds - `get_title_from($markup)`, `get_description_from($markup)`, and `get_price_from($markup)`. Each web site that I want to spider has, of course, different markup surrounding the data that I want to extract. My config file contains a configuration array that holds the regex patterns for each of the items I want to find. The structure of the file is always the same, the only thing that changes is the regex patterns. So, I would have craigslist_config.php, ebay_config.php, etc.               $conf = array(         'title' => ' specific_site title pattern',         'description => 'specific_site description pattern',         'price' => 'specific_site price pattern'     );      My problem is when I want to add a new website. I have to edit the Spider.php file and add to an ever-growing "if, elseif" statement that detects what site is currently being read, and load the correct config file, which in turn feeds the correct REGEX data to the harvester functions. How can I decouple my configuration from my Spider.php file? What I have designed does not feel like a flexible, scalable solution, and I don't want to have to mess with spider.php everytime I want to add or take away a new site. Ultimately, what I am trying to achieve is the ability to simply drop in a new configuration file into my config directory and move the 'if, elseif' logic somewhere else so that the spider and harverster functions never have to worry about what files are or are not included in the config directory. It's the "somewhere else" I am having trouble figuring out. Actually, it would be even better if I could get rid of the 'if else' logic all together so that everything just 'works.' My current design is not an OOP approach, however I am not opposed to one. I am currently reading, "PHP Objects, Patterns, and Practice" to get up to speed on OOP and related design patterns, so feel free to suggest in that direction should you feel it a solution. **EDIT:** Based on Doc Brown's direction, I have come up with the following. I have individual configuration files with content like so:               $conf['specificwebsite1.com'] = array(         'title' => 'title pattern',         'price' => 'price pattern',              etc...     );        In my Harvester file I have a new function called `load_config($url, $config)`. As suggested, I loops through all the configuration files and load them into one large $conf array. Then, the `load_config` function checks if the key is a sub string of the url I'm currently reading. If so, then it loads all the necessary values to continue parsing. This is the function:               function load_config($url, $config){       foreach($config as $key => $value){         if(stristr($url, $key) !== FALSE){           ## see if a key in our config file           ## is a substring of our url.            $conf = $config[$key];           break;         } else {                $conf = FALSE;         }       }            return $conf;     }      This is working really well, so I'll accept that as the answer. But please feel free to make suggestions for improvements in the comments or as another answer.


Which one of these answers regarding functions is incorrect?

So while I've been doing some lengthy compiles I decided to take the C++ general test on ODesk and came across this question. ![This question](http://i.imgur.com/tyX95lv.png) If I'm not mistaken, given the wording (or lack thereof) **all** of these could be true. **a.**               int Foo() { }     int Foo(int bar) { }      **b.** Well, _"return`void`"_ would be incorrect semantically but functions can obviously have `void` return types.               void Foo() { }      **c.** This is the definition of inline functions, yes. **d.** Without going into much detail about the placement of the following elements,               typedef void (*Func)(int);          Func functions[2];          void Foo(int bar) { }     void Bar(int foo) { }          functions[0] = &Foo;     functions[1] = &Bar;      Further, you could always do this using lambdas and functors. **e.**               void Foo(int& bar)     {         ++bar;     }          int foobar = 5;     Foo(foobar);      **f.**               int bar = 5;          int& GetBar()     {         return bar;     }          GetBar() = 6;      **g.**               int bar = 5;          int* GetBar()     {         return &bar;     }          (*GetBar()) = 5;      * * * I fail to see where this question has any _truly false_ answers. Am I missing something? Needless to say I ran out of time and failed the whole thing. I guess I'm a bad C++ programmer. :(


Asking for a code sample of the company at an interview

Asking a job seeker to show some code is a fairly common practice for a software company. However, would it be acceptable for the candidate to ask the interviewer to show him a small piece of code that he thinks is well written?


Freelancing - Getting paid for the quote or estimate

It is often necessary to spend time designing a solution, breaking down the design into tasks and sub tasks and estimating the time it will take to complete each task in order to produce a reasonable estimate or quote for a programming task. This process can be a serious investment of time, often without any guarantee that the estimate/quote will be acceptable to the potential client and more often that not the time was 'wasted' with no hope of getting paid for it (in the event of not winning the job). Is it the case that this is a cost of doing business and what can be done to minimise this unpaid time?


Bump version before kicking off new development or when tagging a release, which is better?

Some projects bump version before kicking off a new development, while the other projects bump version when tagging a release. Which approach is better? If version number not changed at the start of new phase, the developers may forget to change it and simply release the program. If version number changed before tagging release, then 2 the version numbers (tag and Makefile/AssemblyInfo.cs) do not match. `git describe` may give you v1.2.3.4-15-g1234567 if current revision is after v1.2.3.4, but you have already changed the files to have v1.2.3.5


How to make C# methods work like javascript functions?

I'll keep it simple, I want to make C#'s methods work like javascript's functions. Mainly so I can convert this -               function makeVariable(terp) {         var me = {value: 0};         return function () { terp.stack.push(me); };     }      into C#. Is there ANY way, no matter how complex or time consuming, to do this?


Remote pair programming set up over a VM

We are looking for a new way of doing pair programming. It's looks like best way of programming, it is faster and you push out great tested code. But there are some downsides. Ad hoc items that pop up.   crashing.   back ups.   there is only ever one driver. What we thought might be the best possible environment is that we have a server running a VM. Both myself and my programming partner SSH inside and run some sort of VNC, or teamviewer locally between so that we can both work on files simultaneously and say one person works on the views and the other works on setting up apache. So we are looking at working on the same system from two different computer simultaneously. This way we could then when needed link to our other branches and have pairing "systems" that we could like to. Or if someone needs to jump out and work on something else the other person can carry on without him. What do we need to learn to set up such an environment, or accomplish something like this?


Does NASA license the software that it develops?

NASA provides a visualization software called Panoply. There is a Credits and Acknowledgments page that acknowledges and lists the licenses of software dependencies, but provides no information about its own license. I have looked at other software produced by NASA, including the source code for GISS and can not find any information about a licence. The closest information that I can find is in the FAQ for the global climate model EdGCM Global that says the code is in the "public domain"   * is it standard practice at NASA to release code into the public domain?      * are there exceptions?      * Can I assume that Panoply is public domain and can be used without restriction other than than those imposed by licenses of software dependencies?     * Is the absence of specific permission to reuse the code a concern (this issue was raised in the answer to a separate question)    * How common is this practice across government agencies?


My first development job working at a company, what things to look out for?

So I've worked on my own all this time, selling software, creating a few web applications on my own. I had an Arts background I was self taught. It was a bit difficult to find a development position after endless trying, I finally landed a LAMP position. What I realized was it was all confidence issue. Before when I didn't know a few things I panicked but after spending such a long time working on my own projects and solving various problems, I felt confident enough that I could fulfill requirements on my own. I hope this helps other people applying for jobs This is the first time I will be developing with other team members in an office, are there anything I should prepare for my first day at work next week? Any tips and pointers while working as a developer at a company? I'm kinda nervous but excited.


More Accurate Random in C

I have 3 IPs and every IP has a weight, I want to return the IP's according to its weights using the random function. For example if we have 3 IP's   * X with weight 3   * Y with weight 3   * and Z with weight 3 I want to return X in 33.3% of cases and Y in 33.3% of cases and Z in 33.3% of cases, depending on random function in C. I have tried this code :               double r = rand() / (double)RAND_MAX;     double denom = 3 + 3 + 3;     if (r < 3 / denom) {     // choose X     } else if (r < (3 + 3) / denom) {     // choose Y      } else {     // choose Z     }      I repeat the function 1000 and I get: Choose x 495 times and Choose y 189 times and choose z 316 times. But what I want is to get X:333 y:333 Z:334 How can the weighted random be more accurate?


Can a British programmer relocate to the US?

I'm considering a career change after having worked as a financial software developer in London over the past 8 years. I'd quite like to move to Silicon Valley but I'm not clear on the practicalities. 1) Given the visa requirements, am I limited to joining a large software firm such as Google? Or are startups or self employment open to me? 2) Does the visa requirement put me at a disadvantage compared to local hires?


How to implement smart card authentication with a .NET Fat client?

I know very little about smart card authentication in general so please point out or correct me if anything below doesn't make sense. Lets say i have:   * A Certificate Authority "X"-s smart card (non-exportable private key)   * Drivers for that smart card written in C    * A smart card reader    * CA-s authentication OCSP web service   * **A requirement to implement user authentication in a .NET fat client application via a smart card, that was given out by the CA "X".** I tried searching info on the web but no prevail. What would the steps be ? My first thought was: Set up a web service, that would allow saving of (for example) scores of a ping pong game for each user. Each time someone tries to submit a score via the client application, he can only do so by inserting the smart card into the reader. Then the public key is read from the smart card by native c calls through .NET and sent to my custom web service, which in return uses the CA-s authentication OCSP web service to prove the validity of the public key/public certificate (?). If the public key is okay and valid, encrypt a random sequence of bytes with the public key and send it to the client application. If the client application sends back the correctly decrypted random sequence of bytes along with the score of the ping pong game, then the score is saved in the database for the given user. My question is, is this the correct way to do it ? What else should i know about smart card authentication ?


SharePoint + InfoPath Joins

I am trying to do something somewhat unique, and the best path I can find at the moment is to use List joins, but I'm not sure this is possible. I'm hoping someone can suggest a best course of action. The issue at the moment is that I have several lists (i.e. Employees) that all have a lookup to the Assets list. I also have a Scheduling list that contains start and end dates during which assets are unavailable, which also has a lookup to the Assets list. I am trying to find a way to filter a selection list in an InfoPath form to only include Employees that are available. The problem is that I am dealing with five or six types of Assets, so I can't have the Scheduling list directly look up the Employee list (or any other Asset type). I am trying to find a way to have this work done server-side, so that the form doesn't get too heavy. I am accessing the lists via the REST API built in to SharePoint, and I am doing my form design with the InfoPath designer. Any thoughts as to how I can get this form working? **UPDATE 1:** My current thinking is that I may be better off splitting the Scheduling table into individual lists for each Asset type, then finding a way to toss everything back together when I need it later. Does this seem reasonable? I have no idea how difficult it would be to put the pieces back together later- has anyone attempted something like this? **UPDATE 2:** New line of though- I have resigned myself to being unable to do the joins that I would like to do, and instead am trying to accomplish my goal by filtering the data that appears in the selection lists. I am pulling the relevant data from the Scheduling list and all of the data from the Employees list, and trying to filter the Employees list for entries NOT IN the Scheduling list. Does anyone know how to do this, as it will accomplish the goal without having TOO much unneeded data downloaded to the form...


subclass reference to another subclass

Imagine I have the following code:               class A:         pass          class B(A):         pass          class C(A):         def __init__(self):             self.b = B()      Is the above code correct in terms of correct inheritance? I mean is it a good practice to reference another subclass in a subclass?


Getting in to smart card programming

I have a Compaq nw8440 with a smart card reader that is: > Compatible with ISO 7816 compliant Smart Cards. PC/SC interface support I have been interested in smart cards and wanted to start playing around with them. If I wanted to get in to programming smart cards where can I find resources on how to do it, and would I need any additional hardware other than what my laptop provides (besides the cards to program)?


How should I go about learning new technologies?

In a career of software engineer, you need to learn new technologies very often and always in less time due to deadlines. So just need to know how programmers should go about learning the technologies really quick still thoroughly. What approaches do you follow?


How to deal with a new version of visual studio's directory?

When upgrading Visual Studio to a newer version, a new directory is created e.g. "Visual Studio 2013". I understand that that makes sense as we want to differentiate between code targeting different versions of .net. But since some projects use other projects as their dll's for some repeated code - this raises a question - should we copy everything and have everything separate for .net 4.0 from .net 4.5 or should we have one library that works for both (since 90% of the code will be the same) and only create a special library for code that can't run on 4.0? Just suggesting doing "whatever works for you" is not a good solution - at the moment both look viable. If one of the options has some disadvantages, they might become apparent only after we have many internal links from solution to solution, and there's no real way to change all links at once - one must search for every one of them manually, hoping not to miss anything. Since we're obviously not the first facing this question, I'd like to hear from those with experience in the matter. (or anyone else, of course.) (Though there might not be a clear cut answer to this question, I hope it will be allowed here just as the highest voted question on this site is.)


What are the advantages of pass by value?

I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else. But after seeing the brand new languages like Go adapting the same principle confused me. The only advantage I can think of is you make sure that the value you are passing won't be modified. But every time you need to pass a big structure to a function, you need to pass the pointer (or reference) to prevent copying, if the language permits it. To prevent modification of parameters, some `const`ness mechanism could be introduced instead of making the whole language pass by value. I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call; and often I don't need it to be modified inside the function*. What is the motivation behind making modern languages pass by value? Are there any advantages that I am not aware of? **Edit:** When I say pass by value, I don't mean primitives. They are easy and cheap to pass by value. My main focus is objects or structs that consists of more than 1 primitive and thus _expensive_ to copy. *: I have asked around and others reported similar thing with their parameter usage.


Utilizing a Java Concurrent Utility from a Web App

I have the following lines of code in my application:               return "Service is alive since: " + TimeUnit.MILLISECONDS.toMinutes(mxBean.getUptime()) + " minutes";      It uses the following package:               import java.util.concurrent.TimeUnit;      My application is a web application. Does it means that I have something wrong logically if I use something from concurrent package at a web application?


Problem with opening JFrames from LWJGL

I'm making a program that uses LWJGL to render a Display window, and it also listens for keyboard input to prompt it to open a swing window. The problem is, upon the first keyboard prompt, it opens the window successfully. But when you close it and try it again, it seems the LWJGL window 'sticks' down the key you just pressed and instead starts opening up infinite new Swing windows... I'm not sure how to resolve this issue. Here is some code to demonstrate my problem... public class Launcher{               public static void main(String[] args){         new Launcher();     }          public Launcher(){         loadGUI();         go();     }          public void go(){         while(!Display.isCloseRequested()){             listen();             glClear(GL_COLOR_BUFFER_BIT);             Display.update();             Display.sync(60);              }     }          private void listen(){         if(Keyboard.isKeyDown(Keyboard.KEY_SPACE)){             System.out.println("fk");             Example e = new Example();         }     }          private void loadGUI(){              try{             Display.setDisplayMode(new DisplayMode(480,480));             Display.setTitle("Example");             Display.create();         }catch(LWJGLException e){             e.printStackTrace();             Display.destroy();             System.exit(1);         }              glMatrixMode(GL_PROJECTION);         glLoadIdentity();         glOrtho(0, 480, 480, 0, 1, -1);         glMatrixMode(GL_MODELVIEW);          }          private class Example extends JFrame{              public Example(){             add(new JPanel(), BorderLayout.NORTH);             pack();             setResizable(true);             setTitle("Test");             setVisible(true);         }          }      }


What is the best way to make UI in iOS?

I am frustrated with the numerous options available for creating UI in iOS. Each with their own downsides. I like doing programmatic UIs but the compile- debug loop is quite slow (10s each compile) which slows me down when I am endlessly trying to get programmatic auto-layout UIs to work. I would like to know what is the best approach to use for 2 specific screens with code examples. This might be a good way to compare the pros and cons of each approach. Here are two screens of a very common and simple interface - WhatsApp's phone number verification flow: http://www.whatsapp.com/faq/iphone/20902747 # Options   * Auto layout     * Apple NSLayoutConstraint SDK API     * Apple Visual Format Language     * Apple Interface Builder     * 3rd party library        * Pure Layout       * Masonry/KeepLayout   * Non auto layout Thanks!


Which parallel pattern to use?

I need to write a server application that fetches mails from different mail servers/mailboxes and then needs to process/analyze these mails. Traditionally, I would do this multi-threaded, launching a thread for fetching mails (or maybe one per mailbox) and then process the mails. We are moving more and more to servers where we have 8+ cores, so I would like to make use of these cores as much as possible (and not use 1 at 100% and leave the seven others untouched). So conceptually, as an example, it would be nice that I could write the application in such a way that two cores are "continuously" fetching emails and four cores are "continuously" processing/analyzing the emails (since processing and analyzing mails is more CPU intensive than fetching mails). This seems like a good concept, but after studying some parallel patterns, I'm not really sure how this is best implemented. None of the patterns really fit. I'm working in VS2012, native C++, but I guess from a design point of view this does not really matter and just some pointers on how to organize this would be great!


When in the project life-cycle would you fit in external penetration/security testing of the software?

Assuming that you're working on a piece of software which is required to pass a third party security/penetration test before being released to the client, at which point in the project life-cycle would you perform the tests? Passing the test means that no major flaws are detected, or, more likely, that any flaws detected have been properly corrected before release.


How important is it to pick the best IDE for your programming language of choice?

As I learned some basic programming languages I came across tens of IDEs, and tens of compilers. Most people you ask will tell you "Go with that IDE or go with the best" etc, however they do not provide a proper statement as to why this is important. I understand a good IDE will provide you with functionalities to save time and money, such as debugging or quick-word-fill, but I doubt that's the whole reason a programmer picks a good IDE. At school we work on old compilers (Money probably isn't the reason) because the theory "As long as you learn it's good" works. The bottom-line question is: How important is it to pick the best IDE for your programming language? YOu have Eclipse for Java, C++, Python and more, but can't you simply use a different one? What difference does a good IDE to your programming skills or your programming time?


Dual-licensing LGPL 2.1 and LGPL 3

I maintain a software, a small PHP library, that is released under the LGPL version 3 license (LGPLv3). Someone wants to use the library in their software which has the GPL version 2 license. This license compatibility matrix suggests this is not possible without changing the licensing terms of one of the software. I have been requested to dual-license my code under LGPLv2.1 and LGPLv3. Does it make sense, and what might the drawbacks be? Thank you.


Multiple orders in a single list

I have a problem with a ranking system I am using. Scenario: An online game with around 10k players calculates a real time ranking of points when a certain event occurs. Events don't occur that often, around 1 time per minute. This ranking is kept in the cache for quick calculations, sorting and access. Now players can form groups and play against each other, but the scoring system is the same, only the ranking is based for the players in that group. At first I created for every group a separate ranking, effectively having the same scores as the complete ranking, but with different positions in the ranking. This is trivial because there are over 1.000 groups and every time an event occurs all the groups would have to be updated. So what I did now is when the group ranking is requested take only the players that are in that group from the complete ranking and show them. The positions would have to be re-counted. That re-counting is where the problem is. Because the sub-list is by-reference from the complete ranking list I cannot change the position of the player in the sub-ranking without updating it in the complete ranking, because it's just a reference. I came up with two solutions:   * Create a copy from the record every time it is requested and do some output caching (not very desirable because the rankings are live)   * Create a copy and store this in a cache which is reset when an event occurs.   * Create a sub-list with just the positions which is updated when an event occurs. And the last solution: do the position counting in the output instead in the business side. This would be the best solution, only problem is that on some pages this text appears: "You are on position # in the ranking" where # is your ranking position. This number would be tedious to get then. Does anybody have any suggestions to this problem?


Display dynamic content from embedded web server

I have an embedded device running a slimmed down version of a HTTP server. Currently, it can display static HTML pages. Here is an example of how it displays a static HTML page:               char *text="HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"     "Hello World!";     IPWrite(socket, (uint8*)text, (int)strlen(text));     IPClose(socket);      What I'd like to do is display dynamic content, e.g. a reading from a sensor. What I thought of so far is to have the page refresh every once in awhile with               <meta http-equiv="refresh" content="600">      and use sprintf() to attach the sensor reading to the _text_ variable for the response. Is there a way I can do this without having to refresh the page constantly?


Are there any actual case studies on rewrites of software success/failure rates?

I've seen multiple posts about rewrites of applications being bad, people's experiences about it here on Programmers, and an article I've ready by Joel Spolsky on the subject, but no hard evidence or case studies. Other than the two examples Joel gave and some other posts here, what do you do with a bad codebase and how do you decide what to do with it based on real studies? For the case in point, there are two clients I know of that both have old legacy code. They keep limping along with it because as one of them found out, a rewrite was a disaster, it was expensive and didn't really work to improve the code much. That customer has some very complicated business logic as the rewriters quickly found out. In both cases, these are mission critical applications that brings in a lot of revenue for the company. The one that attempted the rewrite felt that they would hit a brick wall if the legacy software didn't get upgraded at some point in the future. To me, that kind of risk warrants research and analysis to ensure a successful path. Have there been actual case studies that have investigated this? I wouldn't want to attempt a major rewrite without knowing some best practices, pitfalls, and successes based on actual studies. **Aftermath:** okay, after more searching, I did find three interesting articles on case studies:   1. Rewrite or Reuse. They did a study on a Cobol app that was converted to Java.    2. The other was on Software Reuse: Developers Experiences and Perceptions.   3. Reuse or Rewrite Another study on costs of maintenance versus a rewrite. I recently found another article on the subject: The Great Rewrite. There the author seems to hit on some of the major issues. Along with this was the idea of prototyping by using the proposed new technology stack and measuring how quick the devs picked it up. This was all as a prelude to a rewrite, which I thought was a great idea!


Data structure to use for complex lookups in an event engine?

What would be an optimal way to organize arbitrary data types into a structure that allows for complex (non-index based) lookups into the data without performing full loop-through's? For a little background, I am not looking for an answer on how to architect an Event engine, rather I am looking for methods to improve a current implementation. With the 5 second tour, I have a architecture in place with the following components,   * Signals - Signals what handles to execute   * Handles - Executes when a signal is received   * Queue - Manages handles   * Engine - Manages the queues and processes signals, new handles etc.. My current implementation has a few pitfalls,   1. Signals are currently coupled into a Queue, this is done so the engine can identify Queues in storage and the signals they represent.   2. There are two separate Queue storages, indexed and non-indexed, index exists for lookups on strings/int's, non-index exists for complex signals such as regex, array comparisons etc.. I think that I may have a solution but would like the thoughts of others that have developed similar systems. With the new architecture I have thought of, it would consist of the following,   1. Queues would store only a "data" property rather than a signal which, would be would passed to the engine for signal comparisons.   2. The engine would no longer have non-index and index storage, rather a single storage would be used that would require loop through lookups. The library is written in PHP (if that matters), if you want to see the source it's at http://www.github.com/nwhitingx/prggmr.


Unit/Integration Testing my DAL

So I've done some research on this but I couldn't quite come to a conclusion, so I figured I'd ask you guys to see if I could get some other opinions. All of my database access is currently done through stored procedures. I am going to make no direct calls using custom queries. Because of this, my DAL is going to be pretty simple. It's basically going to just contain a bunch of methods that more or less interface out the different stored procedures in the database. It will always be in sync with the procedures that are there, and never call into the database any other way. I'm not sure if this is the greatest way to do things, and I am aware of the advantages and disadvantages of only using stored procedures, but it's just the way I've chosen. I think it will be the cleanest in the long run. But I want to test this DAL. I want to test this at a low level opposed to only testing it via the Business Objects that are going to be tied to these calls. I figure doing that will give me confidence that the procedures are working correctly, and than at a high level I can just mock this out and test business logic - but I'm fighting with how I test this stuff. If I write unit tests by the book, I would mock out the actual calls to the database and just make sure that they are getting called, or create some stubs or whatever that return fake data and do it that way (both make sure the function is actually called). However, what good is this if the _only_ thing these methods are doing are taking parameters and calling a stored procedure? All my mocks would be doing would be making sure I'm calling the method from the test more or less, and that seems like a huge waste of time and not really that effective. Now if I integration test this stuff, I could be dealing with real test data, real database calls, which is fine, but then it wouldn't be 100% considered a unit test, and since within the Business Objects I'm mocking these calls out, I'd technically never have official unit tests for this stuff, only integration ones. Does this all make sense? Basically, this seems fine to do for me. Have integration tests for the DAL, and have that be the only time the DAL itself is tested. When I unit test the business logic and mock out the DAL, I'd know it handles data correctly, and that would be comforting enough for me. What I'm asking is, am I approaching this correctly? Is there anything else you guys do that I am missing here that would shine some light on this stuff? Any feedback is much appreciated :)


Why does microsoft's own included MVC3 template not follow fat models, skinny controllers?

**From Microsoft's own built in template for MVC3** The model is extremely skinny, having basically no code. **Model**               public class RegisterModel     {         [Required]         [Display(Name = "User name")]         public string UserName { get; set; }              [Required]         [DataType(DataType.EmailAddress)]         [Display(Name = "Email address")]         public string Email { get; set; }              [Required]         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]         [DataType(DataType.Password)]         [Display(Name = "Password")]         public string Password { get; set; }              [DataType(DataType.Password)]         [Display(Name = "Confirm password")]         [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]         public string ConfirmPassword { get; set; }     }      While the Controller on the other hand seems to be fat, doing more that simple routing... **Controller**               [HttpPost]     [AllowAnonymous]     public ActionResult Register(RegisterModel model)     {         if (ModelState.IsValid)         {             // Attempt to register the user             MembershipCreateStatus createStatus;             Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);                  if (createStatus == MembershipCreateStatus.Success)             {                 FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);                 return RedirectToAction("Index", "Home");             }             else             {                 ModelState.AddModelError("", ErrorCodeToString(createStatus));             }         }              // If we got this far, something failed, redisplay form         return View(model);     }


Is studying more than one programming language as a beginner confusing?

Intuitively it seems like this might be the case. Is there real research or authoritative anecdotal data (yes, please) supporting (or contradicting) this theory?


Which self balancing binary tree would you recommend?

I'm learning Haskell and as an exercise I'm making binary trees. Having made a regular binary tree, I want to adapt it to be self balancing. So:   * Which is most efficient?   * Which is easiest to implement?   * Which is most often used? But crucially, which do you recommend? _I assume this belongs here because it's open to debate._


Why do we have to use divs?

This morning, as I was writing some html and haml, it occurred to me that the way divs are used is ridiculous. Why are divs not implied? Imagine if this:

      was this:               <hero-img>             </hero-img>      If the "div class" portion of the element was assumed, HTML would be more semantic, and infinitely more readable with the matching closing tags! This is similar to HAML, where we have:               .content Hello, World!      Which becomes:
Hello, World!
      It seems to me the only thing that would have to happen for this to work in browsers is that the browsers could start interpreting every element without an existing html element definition as implying `<div class="<element name>">`. This could be completely backward compatible; for CSS and jQuery selectors etc, "div.hero-img" could still work, and be the required syntax to select the elements. I know about the new web components specification, but that is significantly more complicated than what is suggested here. Can you imagine how pleasant it would be to look at a website's source and see html that looked like that?! So why do we have to use divs? If you look at Mozilla's html5 element list, every element has a semantic meaning, and then we get to `<div>` and it says: "Represents a generic container with no special meaning." ..and then they list the arbitrary elements they are adding to html5 like `<details>`. Of course, if this concept of implied divs was added to the html spec, it would take ten years to become standard, which is a million years in web time. So I figure there must be a good reason this hasn't happened yet. Please, explain it to me!


Are there any significant advantages to using a native language for mobile app development?

Forgive me if this question has already been answered but I couldn't quite find the answer I was looking for. What I wanted to know was, is there any significant advantage to using a native language when developing and deploying apps to a mobile environment? The reason I ask is for a long while now I've been using Objective-C, Apple's native language for iOS, to build my apps. However I've been wondering whether or not there is any real benefit to doing this, over using a non-native language like JavaScript and then deploying it through a service like 'Phone Gap'? I do stress _'significant'_ advantages as native languages are always more likely to have the upper hand when it comes to speed and access to the latest APIs. However in general I don't see using a non-native language or a service like 'Phone Gap' causing and major slow down to my apps or restricting my development. Additionally having the ability to deploy to multiple services is also very handy indeed. This is why I put the question, are there any significant advantages to using a native language for mobile app development?


Writing a partnership contract for a website

My boss has offered me a 25% share, in exchange on more input from my side, of a website ( a crawling engine in php and a front end using ajax ) I developed for him. What are the things I should consider in writing the contract so that my share is future proof?


TDD with limited resources

I work in a large company, but on a just two man team developing desktop LOB applications. I have been researching TDD for quite a while now, and although it is easy to realize its benefits for larger applications, I am having a hard time trying to justify the time to begin using TDD on the scale of our applications. I understand its advantages in automating testing, improving maintainability, etc., but on our scale, writing even basic unit tests for all of our components could easily double development time. Since we are already undermanned with extreme deadlines, I am not sure what direction to take. While other practices such as agile iterative development make perfect since, I am kind of torn over the productivity trade-offs of TDD on a small team. **Are the advantages of TDD worth the extra development time on small teams with very tight schedules?**


Data classes: getters and setters or different method design

I've been trying to design an interface for a data class I'm writing. This class stores styles for characters, for example whether the character is bold, italic or underlined. But also the font-size and the font-family. So it has different types of member variables. The easiest way to implement this would be to add getters and setters for every member variable, but this just feels wrong to me. It feels way more logical (and more OOP) to call `style.format(BOLD, true)` instead of `style.setBold(true)`. So to use logical methods instead of getters/setters. But I am facing two problems while implementing these methods: I would need a big switch statement with all member variables, since you can't access a variable by the contents of a string in C++. Moreover, you can't overload by return type, which means you can't write one getter like `style.getFormatting(BOLD)` (I know there are some tricks to do this, but these don't allow for parameters, which I would obviously need). However, if I would implement getters and setters, there are also issues. I would have to duplicate quite some code because styles can also have a parent styles, which means the getters have to look not only at the member variables of this style, but also at the variables of the parent styles. Because I wasn't able to figure out how to do this, I decided to ask a question a couple of weeks ago. See Object Oriented Programming: getters/setters or logical names. But in that question I didn't stress it would be just a data object and that I'm not making a text rendering engine, which was the reason one of the people that answered suggested I ask another question while making that clear (because his solution, the decorator pattern, isn't suitable for my problem). So please note that I'm not creating my own text rendering engine, I just use these classes to store data. Because I still haven't been able to find a solution to this problem I'd like to ask this question again: how would you design a styles class like this? And why would you do that?


One page using querystring or many folders and pages?

I have an application where I have the 'core' code in one folder for which there is a virtual directory in the root, such that I can include any core files using /myApp/core/bla.asp. I then have two folders outside of this with a default.asp which currently use the querystring to define what page should be displayed. One page is for general users, the other will only be accessible to users who have permission to manage users / usergroups / permissions. The core code checks the querystring and then checks the permissions for that user. An example of this as it is now is default.asp?action=view&viewtype=list&objectid=server. I am not worried about SEO as this is an internal app and uses Windows Auth. My question is, is it better the way it is now or would it be better to have something like the following:   * /server/view/list/   * /server/view/?id=123   * /server/create/   * /server/edit/?id=123   * /server/remove/?id=123 In the above folders I would have a home page which defines all the variables which are currently determined by the querystring - in /server/create/ for example, I would define the action as 'create', object name as 'server' and so on. In terms of future development, I really have no idea which method would be best. I think the 2nd method would be best in terms of following what page does what but this is such a huge change to make at this stage that I would really like some opinions, preferably based on experience. PS Sorry if the tags are wrong - I am new to this forum and thought this was a bit too much of a discussion for StackOverflow as that is very much right / wrong answer based. I got the idea SE is more discussion based.


C Minishell Command Expansion Printing Gibberish

I'm writing a unix minishell in C, and am at the point where I'm adding command expansion. What I mean by this is that I can nest commands in other commands, for example:               $> echo hello $(echo world! ... $(echo and stuff))     hello world! ... and stuff      I think I have it working mostly, however it isn't marking the end of the expanded string correctly, for example if I do:               $> echo a $(echo b $(echo c))     a b c     $> echo d $(echo e)     d e c      See it prints the c, even though I didn't ask it to. Here is my code: msh.c - http://pastebin.com/sd6DZYwB expand.c - http://pastebin.com/uLqvFGPw I have a more code, but there's a lot of it, and these are the parts that I'm having trouble with at the moment. I'll try to tell you the basic way I'm doing this. Main is in msh.c, here it gets a line of input from either the commandline or a shellfile, and then calls processline (char *line, int outFD, int waitFlag), where line is the line we just got, outFD is the file descriptor of the output file, and waitFlag tells us whether or not we should wait if we fork. When we call this from main we do it like this:               processline (buffer, 1, 1);      In processline, we allocate a new line:               char expanded_line[EXPANDEDLEN];      We then call expand, in expand.c:               expand(line, expanded_line, EXPANDEDLEN);      In expand, we copy the characters literally from line to expanded_line until we find a $(, which then calls:               static int expCmdOutput(char *orig, char *new, int *oldl_ind, int *newl_ind)      orig is line, and new is expanded line. oldl_ind and newl_ind are the current positions in the line and expanded line, respectively. Then we pipe, and recursively call processline, passing it the nested command(for example, if we had "echo a $(echo b)", we would pass processline "echo b"). This is where I get confused, each time expand is called, is it allocating a new chunk of memory EXPANDEDLEN long? If so, this is bad because I'll run out of stack room really quickly(in the case of a hugely nested commandline input). In expand I insert a null character at the end of the expanded string, so why is it printing past it? If you guys need any more code, or explanations, just ask. Secondly, I put the code in pastebin because there's a ton of it, and in my experience people don't like it when I fill up several pages with code. Thanks.


function naming: plural form of "if not exists"

This is a question about function naming. I am writing some code that updates the structure of a database according to a specification. Somewhere in this code I have something like this:               void createIndices(Table tbl){         for(Index idx : table.getIndices()){             if(notExists(idx)){                 createIndex(idx);             }         }     }          void createIndex(Index idx){         ...     }      As you can see, the function `createIndices` is not well named because it doesn't quite create the indices. It creates only those indices _that do not already exist_. I can come up with a variety of names for the function:   * `createIndicesIfNotExist`   * `createIndicesThatDoNotExist`   * etc. However, because "if not exists" is such a recurring idiom in programming, I was wondering if there is some kind of standard for its plural form. Just like `createIndexIfNotExists` could be considered the standard singular form, even if it's not grammatically correct.


Wrapping function in closures to make testable functions

In my nodejs project, I have functions like this for socketio.               socket.on('draw', function (data) {         socket.broadcast.to(socket.room).emit('draw', data);         addEvent(socket, ["draw", data]);     });      I'd like to rewrite them to something like this:               function onDraw(socket, config) {         return function (data) {             socket.broadcast.to(socket.room).emit('draw', data);             addEvent(socket, ["draw", data]);         }     }          socket.on('draw', onDraw(socket, config));      The idea is that by placing all of my functions in simple closures like this, I can put them in different modules and it will make it easier to test by passing mockup objects to the function that construct the callback. **I was wondering if it was overkill or if there is a better way to make my code testable?**


Does open source licensing my code limit me later?

Suppose I develop a useful library and decide to publish it as open source. Some time later I have a business need to do something that wouldn't comply with the open source licence. Am I allowed to do that? How should I publish the software in a way that I keep ownership and don't block myself from using the library in the future in any way? Keep in mind that at least in theory, other developers may decide to contribute to my open-source project. Can I specify in a licence that I as the original developer get ownership of their contributions as well? Don't get me wrong here, I'm not trying to be evil and get ownership of other's work - I just want to keep ownership of mine, and if someone posts an important bugfix I could be rendered unable to use the original code unless I use his work as well.


How viable is a PhD in software security research?

I am planning to do a Ph.D in software security. My school is giving a full scholarship for "Detecting security vulnerabilities from source code and binary code" project. Is is worth taking it? I feel software security is a bit saturated field, I mean there are already lots of software vulnerability detection tools available in the market. Is this still a viable research field? Is software security a solved problem?


Is R6RS backwards compatible with R5RS?

Is the new Scheme standard, R6RS which was published in 2007, backwards compatible with the older standard R5RS? If not, is there a compatibility mode in R6RS?


Is it a good practice to decouple the membership system?

Currently I'm developing a project that basically is built with ASP.NET Web API. The membership system I'm using is ASP.NET Identity. The only problem I'm seeing with this is that the membership system is being highly coupled with the API I'm bulding. In that case I've thought on bulding interfaces to expose the membership system functionalities the app needs and then use dependency injection to inject the current Identity system. The only thing is that on all the time I've been looking on the internet about authentication and authorization in ASP.NET I've never seem this done. So I've started to wonder whether this is or not a good practice. Is this a good practice or no? If not, why?


How do you handle objects that need custom behavior, and need to exist as an entity in the database?

For a simple example, assume your application sends out notifications to users when various events happen. So in the database I might have the following tables:               TABLE Event         EventId uniqueidentifier         EventName varchar          TABLE User         UserId uniqueidentifier         Name varchar          TABLE EventSubscription         EventUserId         EventId         UserId      The events themselves are generated by the program. So there are hard-coded points in the application where an event instance is generated, and it needs to notify all the subscribed users. So, the application itself doesn't edit the `Event` table, except during initial installation, and during an update where a new `Event` might be created. At some point, when an event is generated, the application needs to lookup the `Event` and get a list of `User`s. What's the best way to link the event in the source code to the event in the database? ## Option 1: Store the `EventName` in the program as a fixed constant, and look it up by name. ## Option 2: Store the `EventId` in the program as a static `Guid`, and look it up by ID. ## Extra Credit In other similar circumstances I may want to include custom behavior with the event type. That is, I'll want subclasses of my `Event` entity class with different behaviors, and when I lookup an event, I want it to return an instance of my subclass. For instance:               class Event     {         public Guid Id { get;  }         public Guid EventName { get;  }         public ReadOnlyCollection<EventSubscription> EventSubscriptions { get; }         public void NotifySubscribers()         {             foreach(var eventSubscription in EventSubscriptions)             {                 eventSubscription.Notify();             }             this.OnSubscribersNotified();         }         public virtual void OnSubscribersNotified() {}     }          class WakingEvent : Event     {         private readonly IWaker waker;         public WakingEvent(IWaker waker)         {             if(waker == null) throw new ArgumentNullException("waker");             this.waker = waker;         }              public override void OnSubscribersNotified()         {             this.waker.Wake();             base.OnSubscribersNotified();         }     }      So, that means I need to map `WakingEvent` to whatever key I'm using to look it up in the database. Let's say that's the `EventId`. Where do I store this relationship? Does it go in the event repository class? Should the `WakingEvent` know declare its own ID in a static member or method? ...and then, is this all backwards? If all events have a subclass, then instead of retrieving events by ID, should I be asking my repository for the `WakingEvent` like this:               public T GetEvent<T>() where T : Event     {         ...         // what goes here?         ...     }      I can't be the first one to tackle this. What's the best practice?


Is it a good practice to use Auto Format the text?

I'm using Eclipse and I will talk about it as an example but I am sure that this is the case in any other IDE. Eclipse has the `CTRL`-`Shift`-`F` command which automatically formats your code. Is it a good practice to use this kind of formatting? I'm asking in the context of a big project in which there may be many programmers working on the same files and all these are administrated by a CSV system. Thank you!


Brief explanation for executables in a GNU/Clang Toolchain?

I roughly understand that cc, ld and other parts are called in a certain sequence according to schemes like Makefiles etc. Some of those commands are used to generate those configs and Makefiles. And some other tools are used to deal with libraries. But what are other parts used for? How are they called in this process? Which tool would use various parser generators? Which part is optional? Why? Is there a brief summary get these explained on how the tools in a GNU or LLVM/Clang toolchain are organised and called in a C/C++ project building? Thanks in advance. EDIT: Here is a list of executables for Clang/LLVM on Mac OS X: ar clang dsymutil gperf libtool nmedit rpcgen unwinddump as clang++ dwarfdump gprof lorder otool segedit vgrind asa cmpdylib dyldinfo indent m4 pagestuff size what bison codesign_allocate flex install_name_tool mig ranlib strip yacc c++ ctags flex++ ld mkdep rebase unifdef cc ctf_insert gm4 lex nm redo_prebinding unifdefall


tips, guidelines, points to remember for rendering professional code?

I'm talking about giving clients professional looking code. The whole nine yards, everything you hardcore professional highly experienced programmers here probably do when coding freelance or for the company you work in. I'm fresh out of college and I'm going into freelance. I just want to be sure that my first few projects leave a good after-taste of professionalism imprinted on the clients' minds. When I Googled what I'm asking here, I was given pages that showed various websites and tools that let you make flashy websites and templates etc. The `$N package` and such stuff. I can't recall the word experts use for it. Standard, framework [I know that's not it]. English isn't my first language so I'm sorry I don't really don't know the exact phrase for it. That abstract way of writing code so that you don't come across as a sloppy programmer. That above mentioned way for programming **websites and desktop software [in python/C/C++/Java]**. EDIT: I can work on the accruing vast knowledge and know-how and logic building etc. what I'm asking for is the programming standard/guidelines you guys follow so that the client on seeing code feels that its a professional solution. Like comment blocks, a particular indentation style something like that. Is there any book on it or specific list of points for enterprise type coding by them? Especially here as in my case, for building websites [php for now..], and desktop software [c/c++/java/python]


Should tests be in the same Ruby file or in separated Ruby files?

While using Selenium and Ruby to do some functional tests, I am worried with the performance. So is it better to add all test methods in the same Ruby file, or I should put each one in separated code files? Below a sample with all tests in the same file:               # encoding: utf-8     require "selenium-webdriver"     require "test/unit"          class Tests < Test::Unit::TestCase              def setup             @driver = Selenium::WebDriver.for :firefox             @base_url = "http://mysite"             @driver.manage.timeouts.implicit_wait = 30             @verification_errors = []             @wait = Selenium::WebDriver::Wait.new :timeout => 10         end                   def teardown             @driver.quit             assert_equal [], @verification_errors         end              def element_present?(how, what)             @driver.find_element(how, what)             true             rescue Selenium::WebDriver::Error::NoSuchElementError             false         end              def verify(&blk)             yield             rescue Test::Unit::AssertionFailedError => ex             @verification_errors << ex         end              def test_1                  @driver.get(@base_url + "/")             # a huge test here              end              def test_2                  @driver.get(@base_url + "/")             # a huge test here              end              def test_3                  @driver.get(@base_url + "/")             # a huge test here              end              def test_4                  @driver.get(@base_url + "/")             # a huge test here              end              def test_5                  @driver.get(@base_url + "/")             # a huge test here              end     end


Alternate method to dependent, nested if statements to check multiple states

Is there an easier way to process multiple true/false states than using nested if statements? I think there is, and it would be to create a sequence of states, and then use a function like `when` to determine if all states were true, and drop out if not. I am asking the question to make sure there is not a preferred Clojure way to do this. Here is the background of my problem: I have an application that depends on quite a few input files. The application depends on .csv data reports; column headers for each report (.csv files also), so each sequence in the sequence of sequences can be zipped together with its columns for the purposes of creating a smaller sequence; and column files for output data. I use the following functions to find out if a file is present:               (defn kind [filename]       (let [f (File. filename)]         (cond           (.isFile f)      "file"           (.isDirectory f) "directory"           (.exists f)      "other"            :else            "(cannot be found)" )))          (defn look-for        [filename expected-type]         (let [find-status (kind-stat filename expected-type)]           find-status))      And here are the first few lines of a multiple if which looks ugly and is hard to maintain:               (defn extract-re-values       "Plain old-fashioned sub-routine to process real-estate values / 3rd Q re bills extract."       [opts]       (if (= (utl/look-for (:ifm1 opts) "f") 0)             ; got re columns?         (if (= (utl/look-for (:ifn1 opts) "f") 0)           ; got re data?           (if (= (utl/look-for (:ifm3 opts) "f") 0)         ; got re values output columns?             (if (= (utl/look-for (:ifm4 opts) "f") 0)       ; got re_mixed_use_ratio columns?               (let [re-in-col-nams  (first (utl/fetch-csv-data (:ifm1 opts)))                     re-in-data      (utl/fetch-csv-data (:ifn1 opts))                     re-val-cols-out (first (utl/fetch-csv-data (:ifm3 opts)))                     mu-val-cols-out (first (utl/fetch-csv-data (:ifm4 opts)))                     chk-results     (utl/chk-seq-len re-in-col-nams (first re-in-data) re-rec-count)]      I am not looking for a discussion of the best way, but what is in Clojure that facilitates solving a problem like this.


Why is heap size fixed on JVMs?

Can anyone explain to me why JVMs (I didn't check too many, but I've never seen one that didn't do it that way) need to run on a fixed heap size? I know it's easier to implement on a simple contiguous heap, but the Sun JVM is now over a decade old, so I'd expect them to have had time to improve this. Needing to define the maximum memory size of your program at startup time seems such a 1960s thing to do, and then there are the bad interactions with OS virtual memory management (GC retrieving swapped out data, inability to determine how much memory the Java process is _really_ using from the OS side, huge amounts of VM space wasted (I know, you don't care on your fancy 48bit machines...)). I also guess that the various sad attempts to build small operating systems inside the JVM (EE application servers, OSGi) are at least partially to blame on this circumstance, because running multiple Java processes on a system invariably leads to wasted resources because you have to give each of them the memory it might have to use at peak. Surprisingly, Google didn't yield the storms of outrage over this that I would expect, but they may just have been buried under the millions of people finding out about fixed heap size and just accepting it for a fact.


My work isn't being used... what can/ should I do?

Several months ago I was approached by a small business, who had seen my work previously and asked me to create a website for them. Since then, the website hasn't changed one bit and I haven't heard a word from them. This sucks for them as they paid for a website and haven't used it. It''s frustrating for me because I spent a huge amount of time on the website and feel that all of that effort has been wasted, furthermore, I don't feel I can use the website on my portfolio/ CV. I was _thinking_ of offering to go round to their office for one day, and update the website for them then and there; but I'd need their support whilst there (to get the content for the about page, to get information for on their products etc.) and I don't want to disrupt their work day, nor do I want to sit there like a spare tyre and get nowhere. Furthermore, if I were to do this, should I expect to receive money for it? It's a day of my life, but I'm doing it for my benefit rather than theirs (but they benefit as well). Has anyone else had experience of a client not using their product; how did you handle it? **Additional background for those who want it:** The company is a local travel agent, and the website lets them CRUD offers and locations, and has several other static pages (about, contact, etc.) At the time of creating the website, I filled the static pages with lipsum, and the offers and locations with fake information, so that I could give the business an idea about what the final pages would look like; during the hand over, I guided them through the CRUD forms (they made notes) and said if they sent me the text for the pages, I'd update it.


How to manage scripting language file (Python, for example)?

I am writing python, but I find that the I can put all the script files on the directory, but it seems very messy. So, is there any conventions in the community to deal with the script files? Thanks.


How to translate formulas into form of natural language?

I am recently working on a project aiming at evaluating whether an android app crashes or not. The evaluation process is                 1.Collect the logs(which record the execution process of an app).       2.Generate formulas to predict the result         (formulas is generated by GP)       3.Evaluate the logs by formulas             Now I can produce formulas, but for convenience for users, I want to translate formulas into form of natural language and tell users why crash happened.(I think it looks like "inverse natural language processing".) To explain the idea more clearly, imagine you got a formula like this:                 155 - count(onKeyDown) >= 148      It's obvious that if count(onKeyDown) > 7, the result of "155 - count(onKeyDown) >= 148" is false, so the log contains more than 7 onKeyDown event would be predicted "Failed". I want to show users that if onKeyDown event appears more than 7 times(155-148=7), this app will crash. However, the real formula is much more complicated, such as:                 (< !( ( SUM( {Att[17]}, Event[5]) <= MAX( {Att[7]}, Att[0] >= Att[11]) OR SUM( {Att[17]}, Event[5]) > MIN( {Att[12]}, 734 > Att[19]) ) OR count(Event[5]) != 1 ) > (< count(Att[4] = Att[3]) >= count(702 != Att[8]) + 348 / SUM( {Att[13]}, 641 < Att[12]) mod 587 - SUM( {Att[13]}, Att[10] < Att[15]) mod MAX( {Att[13]}, Event[2]) + 384 > count(Event[10]) != 1))      I tried to implement this function by C++, but it's quite difficult, here's the snippet of code I am working right now. Does anyone knows how to implement this function quickly?(maybe by some tools or research findings?)Any idea is welcomed: ) Thanks in advance.


About compilers, coding, large code bases, and some other stuff too

This is not purely a programming question. I work in a large company. We have lots of code written in C++ language:   1. Multiple simultaneous projects in progress and implementations that have to be supported.   2. Multiple code paths due to first reason. Some are ~10 years old.   3. Multiple target platforms. Most of the code has to be standard. Compiler specific code is frowned upon.(Which is a good thing I suppose)   4. A large number of processes (>30 easily) each having in excess of 10k lines even in the smaller processes.   5. Multiple developers per process, multiple processes per developer, multiple owners for a process over time(Who may now be unavailable as some processes have had a fair number of owners). This means there is no definite authority on a process for some processes.    6. Not all functionality of all the processes are used all the time. There may exist many bugs in your process you don't know about simply because you haven't come across a situation where a certain branch of code is executed at runtime. Eliminating all these are not so easy.   7. Timeline constraints and allocation to multiple projects and multiple processes mean that developers are usually left with no choice rather than to make do with existing code and try and work around limitations rather than to radically change the coding of a process so that it can be much better.   8. Most processes are performance critical. This is a huge incentive for people to adhere to C style coding and shy away from OOP.   9. templates, STL and metaprogramming usage is near to non-existent.   10. Use of third party libraries is next to impossible. i.e. No Boost! Oracle is an exception.    11. Basic functionalities needed are implemented in libraries which expose C like interfaces which make you look like an idiot if you are trying to write something in OOP or using templates because every time you use them, you have to wrap them up to hide the C like interface or just forget about the whole thing and do C like coding yourself. Not to mention additional bugs you may introduce by trying to wrap. The libraries themselves have been heavily used and are quite reliable in most cases. So the natural inclination is to go with them in a time constrained project.   12. People are not very receptive to new ideas. I do not have **ANY** idea how to remedy this. I myself am curious and willing to try out new stuff. I find it hard to accept when other people don't. Especially when those people are not in managerial positions. Management decisions I can tolerate even if I don't agree. But what is there to do about decadence in developers? Q1: What are the questions I should be asking myself? Please note that I love C++, and I have no intention whatsoever of quitting my job because the company is great. And it's the best in my country. Q2: What are the ways I can, and help others improve? Q3: I had this discussion with a dev lead about upgrading our compiler to the newer version because it has a lot of nice features in c++0x and I thought the sooner we try to adjust to those, the better. His concern was the risk associated with it. Reasoning:   1. Do we really need those features?   2. Our current main OS does not support for compiler version XXX. Of course we can always use XXX, but if something goes wrong the OS can say "Hey, we don't support that!".   3. It has to be a gradual process not an overnight one. (In my opinion this implies that we should always be a couple of years or more behind the current front) I know this is not a "yes no question", but what is the correct approach to this problem? Q4: Are all or some of the above stupid questions? Thanks for any feedback. p.s. Writing this has also made me realize stuff that had not occurred to me before. So I guess it would not go to waste if someone were to close this even without a single answer (Which I hope will not happen). :)


How do you rate Hosting?

1) Up-time   2) Latency   3) Throughput   4) Server software such as SQL, etc.   5) $$$ -- transfer, overages, etc. What else? And is there a web site rating hosts by this criteria that is actually reliable and not simply a dishonest advertising site... or do you guys have any recommendations? (BTW, someone with 150+ rep should create "hosting" and "web hosting" tags.)


How can I make being code reviewed by someone who doesn't know the language easier?

I'm in a team where I am the only Java developer. The rest of the team are VERY experienced in their own programming language, but their area of expertise is not object orientated. I found the first time that I had a code review, it was a lengthy process that involved a lot of tangents about how Java works, or how OOP works etc. The second time, we got caught up on something and they had to bail as it was taking too long. **How can I make this process easier**?   I desperately want my code reviewed as I myself am quite new to Java programming, and really to programming in general, but this is taking a long time (especially as, for instance I'm writing quite large chunks of code by refactoring old code that the last Java dev worked on).


Internal exposure of implementation details on inheritance

I'm reading the "Effective Java" book which suggests to favor composition over inheritance. The example it gives shows something like this:               public class InstrumentedHashSet<E> extends HashSet<E> {          // The number of attempted element insertions           private int addCount = 0;               public InstrumentedHashSet() { }               public InstrumentedHashSet(int initCap, float loadFactor) {              super(initCap, loadFactor);          }               @Override public boolean add(E e) {              addCount++;              return super.add(e);          }               @Override public boolean addAll(Collection<? extends E> c) {              addCount += c.size();              return super.addAll(c);          }               public int getAddCount() {              return addCount;         }     }      This presents a problem because the implementation of `addAll` in `HashSet` uses the method `add`. So, when calling `addAll` each new elements is counted twice - once in `addAll` and once in `add`. In the next chapter it is explained that if we choose to allow extending our class we should explicitly explain the inner working of our methods that use overridable methods (meaning - in the `addAll` documentation we should specify its use of `add` and commit to this implementation **forever** ). I think that a better practice would be to decide that each method that is both an overridable, API method and also used by inner implementation should be extracted to an inner, private method. So Our ideal `HashSet` would have these methods:               public class HashSet<E> implements Set<E> {          // Ignore irrelevant code                    @Override public boolean add(E e) {              // The new add implementation only wraps the innerAdd method              return innerAdd(e);          }               @Override public boolean addAll(Collection<? extends E> c) {             // Do the same logic as before but use innerAdd instead of add          }               private boolean innerAdd(E e) {              // The original add logic will be moved to here          }     }      This way we encapsulate inner implementation and allow extending the class without fearing to override a method which is used by inner implementation. Of course that we can use the original add as before because by calling `super.add(e)` we de-facto use the `innerAdd` so that's not a problem. I would like to know whether this might be a good practice (not for `HashSet<E>` which is already committed to the code that use it, but to new classes that are meant to be overriden)?


How to maintain the 'LICENSE' file?

Many projects on Github comprise a `LICENSE` file, usually looking like:               Copyright (C) 2012-2013 Mr. Creator          Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:          ...etc...      My problems are:   1. If I create a project, should I add the name of every single contributor in `LICENSE`?   2. If I fork other's project, should I add my name in its `LICENSE`?   3. What if I add some files under another license?


Is hadoop designed only for "simple" data processing jobs, where communications between the distributed nodes are sparse?

I am not a professional coder, but rather an engineer/mathematician that uses computer to solve numerical problems. So far most of my problems are math- related, such as solving large scale linear systems, perform linear algebra operations, fft, mathematical optimization etc.. At smaller scale, these are best handled by Matlab (and similar high-level math packages). At large scale, however, I have to resort to old-fashioned (and VERY TEDIOUS) lower-level languages such as Fortran or C/C++. That is not all, when the problem become excessively large, parallelization becomes necessary, and MPI in that regard is a nightmare to wrestle through. I have been hearing about hadoop and "big data" recently on a regular basis. But my impression was hadoop is NOT a general-purpose parallel computing paradigm, in the sense that it handles data that need minimal mutual communications (correct me if I am wrong). For example, in a general LA operation on a large data set distributed among many nodes, rather than processing one's own piece of data independently, each node must communicate with EVERY other node to send/get info before it's own data can be correctly processed, and the whole data set is updated only after ALL communications have been done. I hope I made my point clear: in numerical applications, data- processing is naturally GLOBAL, and the "graph" for communication often is a FULL GRAPH (though there ARE exceptions). My question is, is hadoop suitable for such purpose, or is it only designed for "simple" data processing jobs, where communications between the distributed nodes are sparse?


Did eastern PKUFFT algorithm beat FFTW3 (Fastest FFT on the west) 20 fold?

I wonder if PKUFFT is Chinese algorithm/library and is it really better than FFTW, MKL ? Thank you Edit: I will elaborate. My personal programmers interest is in fast parallel algorithms like FFTW3, which was my favorite until I stumbled upon chinese claim of superior run with PKUFFT. It is on google, if you search for FFTW3, Intel MKL, GPU and things. I dont know anything about this library, but I would be very interested to learn. I can guess PKU stands for Peking Univ. There is nothing on web except presentation and mentioning of some commonly available hardware (GPU, infiniband, etc.). everything, including compilers was available for years. The improvement of 2000% is significant. The news are 1 year old. But no details about algorithm itself. It will be interesting to know if there is genuine discovery in algebra, or just technical effect with unfair advantage of knowing specific platform better than competing teams.


Checking out systems programming, what should I learn, using what resources?

I have done some hobby application development, but now I'm interested in checking out systems programming (mainly operating systems, Linux kernel etc.). I know low-level languages like C, and I know minimal amounts of x86 Assembly (should I improve on it?). What resources/books/websites/projects etc. do you recommend for one to get started with systems programming and what topics are important? Note that I know close to nothing about the subject, so whatever resources you suggest should be introductory resources. I still know what the subject _is_ and what it includes etc., but I have not done systems programming before (but some application development, as previously noted, and I'm familiar with a bunch of programming languages as well as software engineering in general and algorithms, data structures etc.).


What are steps in making an operating system in C ?

I am trying to make an my own OS. This is for educational purpose only, so that I get to understand the internals as well as get a good idea of low level programming. I have some prior application development experience in C#/python/C++/C. I am a noob in assembly language(very less experience and knowledge). I understand that in writing an operating system,we can't go without assembly language. Currently, I have just printed a string in assembly language in the boot sector using qemu and BIOS interrupts.   What I want is that, can someone specifically point out the steps that I need to follow to make my operating systems run C programs. So that, I can start writing my OS in C.   Any other piece of advice to help a newbie, regarding the same is also welcome. Although, I have looked into many os development related tutorials/websites, I can't seem to find this information anywhere.


Power of 2 and performance in SQL Server

Many mathematical operation (such as division, multiplication, etc.) are supposed to be computed faster when dealing with power of two numbers (C++, C#?, ...) For instance 15 * 256 = 0x0e right shifted (fast) 8 bits = 0x0e00 = 3840   Whereas 15 * 255 = 0x0e multiplied by (slow) 0xff = 0x0ef1 = 3825 Does this kind of optimization even happen in SQL Server? I don't think there are, I tried measuring a difference of execution time of queries such as those:               SET STATISTICS TIME ON          SELECT         AVG(N / 256)     FROM DBO.V_VIRTUAL_NUMBERS     WHERE N < 1048576               SELECT         AVG(N / 255)     FROM DBO.V_VIRTUAL_NUMBERS     WHERE N < 1000000          SET STATISTICS TIME OFF      which resulted in:                SQL Server Execution Times:        CPU time = 0 ms,  elapsed time = 0 ms.     SQL Server parse and compile time:         CPU time = 0 ms, elapsed time = 0 ms.          (1 row(s) affected)           SQL Server Execution Times:        CPU time = 203 ms,  elapsed time = 207 ms.           SQL Server Execution Times:        CPU time = 0 ms,  elapsed time = 0 ms.     SQL Server parse and compile time:         CPU time = 0 ms, elapsed time = 0 ms.          (1 row(s) affected)           SQL Server Execution Times:        CPU time = 218 ms,  elapsed time = 206 ms.


What would be the prototype of printf?

look at these calls closely:               printf("hello, world\n");     printf("%d", 2);     printf("%d%g\n", 2, 2.3);      we see that printf can accept any type and any number of args. however we know that functions in c only take fixed length args and should have a compatible prototype to match the arg. what would be the prototype of printf ?


Setting up CI with [Jenkins, TeamCity, etc] - which source code control?

I am bound and determined to setup CI at work. I have played with Jenkins, and will download TeamCity when I get home (damn you work enforced download filters!) I have no IT support, and only so much spare time. My main question: Can Jenkins or TeamCity integrate with git or mercurial repositories that exist only on a shared drive rather than a true server (via http, https, ssh, etc)? I would like to use a DVCS with my CI setup, but would also be ok with settling on SVN because it is familiar, and already setup (but no projects to migrate if I decide on a DVCS). I am familiar with the benefits of DVCS and I don't think they will come into play very often in my current environment. My CI will live on a plain Windows XP box on the network. Given the above, will it be fairly easy to integrate either Jenkins or TeamCity with git/mercurial, or should I just stick with SVN as it is more or less ready to go?


Rule order for Parsing Lists with LALR(1)

When creating the grammar for parsing a list (something like “`ITEM*`”) with a LALR(1) parser, this basically can be done in two ways:               list         : list ITEM         |         ;      or               list         : ITEM list         |         ;      What are the pros and cons of these two possibilities? In general, can an advice be given which one to choose, or does this depend on the complete grammar? What about the case “`ITEM+`”, i.e.               list         : list ITEM         | ITEM         ;      and               list         : ITEM list         | ITEM         ;      Do the same pros and cons apply here, or others?


C++ and system exceptions

Why standard C++ doesn't respect system (foreign or hardware) exceptions? E.g. when null pointer dereference occurs, stack isn't unwound, destructors aren't called, and RAII doesn't work. The common advice is "to use system API". But on certain systems, specifically Win32, this doesn't work. To enable stack unwinding for this C++ code               // class Foo;     // void bar(const Foo&);     bar(Foo(1, 2));      one should generate something like this C code               Foo tempFoo;     Foo_ctor(&tempFoo);     __try {         bar(&tempFoo);     }     __finally {         Foo_dtor(&tempFoo);     }     Foo_dtor(&tempFoo);      and it's impossible to implement this as C++ library. * * * **Upd:** Standard doesn't forbid handling system exceptions. But it seems that popular compilers like **g++** doesn't respect system exceptions on _any_ platforms just because standard doesn't require this. The only thing that I want - is to use RAII to make code readable and program reliable. I don't want to put hand-crafted try\finally around every call to unknown code. For example in this reusable code, `AbstractA::foo` is such unknown code:               void func(AbstractA* a, AbstractB* b) {         TempFile file;         a->foo(b, file);     }      Maybe one will pass to `func` such implementation of `AbstractA`, which every Friday will not check if `b` is NULL, so access violation will happen, application will terminate and temporary file will not be deleted. How many months uses will suffer because of this issue, until either author of `func` or author of `AbstractA` will do something with it? * * * Related: Is `catch(...) { throw; }` a bad practice?


Reasonable to use different version controls for different parts of a web application?

I am contemplating a few different techniques for organizing code for a larger web application. For this situation, the server runs some Microsoft solution (probably ASP.NET MVC or OpenRasta) and the client (JavaScript, CSS, etc.) will consume this. Traditionally in an MVC application, the controllers and models along with the client codebase all live in the same project/solution. Our current solutions use TFS for source control. I want to start using Sass and Compass for the front-end, which will require Ruby, and I would like to use git for the version control of the front-end and continue to use TFS for the server components. The problem I have is that in order for someone to run the solution, you would need to pull from both repositories, and I am not sure if that is reasonable. Would you attempt something like this? Can you think of a better way for the projects to be structured so that front-end is separated from back-end? If I have not explained this well enough I will be happy to elaborate.