What's more important: To write programs fast or to write fast programs? According to: http://math.stackexchange.com/questions/17478/how-quickly-with- better-tool it is better to write fast programs, but I wanted to ask this Q here to get the general gist of what you're thinking on this subject. Of course I'm taking as a given that all programs have to be correct etc. etc.


How to create scalable & side-effect free integration tests?

In my current project, I am having a hard time coming up with a good solution to create scalable integration tests that have no side effects. A little clarification on the side effect free property: it is mostly about the database; there shouldn't be any changes in the database after the tests are completed (state should be preserved). Maybe scalability and state preservation don't come together, but I really want to push for a better solution. Here is a typical integration test (these tests touch the database layer):               public class OrderTests {              List<Order> ordersToDelete = new ArrayList<Order>();               public testOrderCreation() {             Order order = new Order();             assertTrue(order.save());             orderToDelete.add(order);         }              public testOrderComparison() {             Order order = new Order();             Order order2 = new Order();             assertFalse(order.isEqual(order2);             orderToDelete.add(order);             orderToDelete.add(order2);         }         // More tests              public teardown() {              for(Order order : ordersToDelete)                  order.delete();         }     }      As one might imagine, this approach yields tests that are extremely slow. And, when applied to the whole integration tests, it takes around 5 seconds to test only a small portion of the system. I can imagine this number going up when the coverage is increased. **What would be another approach for writing such tests?** One alternative I can think of is having kind of global variables (within a class) and all test methods share this variable. As a result, only few orders get created & deleted; resulting in faster tests. However, I think this introduces a bigger problem; the tests are no longer isolated and it gets more and more difficult to understand & analyze them. It might just be that integration tests are not meant to be run as often as unit tests; therefore low performance might be acceptable for those. In any case, it would be great to know if someone came up with alternatives for improving scalability.


Indirection: Readability vs Performance

(I see there are a lot of similar questions, but answers are not really what I am interested at.) The thing that is bugging me is indirection. If I'm writing something, I do tend to inline as much stuff as possible. I might be less strict about it in compiled language hoping that compiler will do all the inlining for me. Still adding layers of indirection feels to me like "I'll just add some more burden onto user in runtime so that I could have nicer code here" - something that could be solved with either a comment or a different design (which I would actually prefer but it would take some more time). Seeing a small function that is used only once I have to actually fight the urge to inline it. Having a multitude of single-use classes makes me want to create a different (and usually totally procedure-oriented) solution. How bad is that? How many layers of indirection are actually OK to have?


Using Type Parameter (or not)

Effective Java provides 2 ways to implement `swap`:               // Two possible declarations for the swap method      public static <E> void swap(List<E> list, int i, int j);      public static void swap(List<?> list, int i, int j);      Then, Mr. Bloch says: > Which of these two declarations is preferable, and why? In a public API, the > second is better because it's simpler. You pass in a list—any list—and the > method swaps the indexed elements. There is no type parameter to worry > about. As a rule, if a type parameter appears only once in a method > declaration, replace it with a wildcard. It appears that `swapNoWildCard` could be used rather than the `swap` and `swapHelper` method. Mr. Bloch explains the reasoning for using the 2nd signature above.               public static <E> void swapNoWildcard(List<E> list, int i, int j) {         E e = list.set(j, list.get(i));         list.set(i, e);     }          public static void swap(List<?> list, int i, int j) {         swapHelper(list, i, j);     }          private static <E> void swapHelper(List<E> list, int i, int j) {         E e = list.set(j, list.get(i));         list.set(i, e);     }      However, is this debatable given the fact that `swapNoWildCard` is almost half the # of lines of code compared to implementing the other 2 methods? Why is it so useful to leave out the type parameter?


Writing tests for two methods that share functionality

I'm writing some tests for a NodeJS module, but this question can apply for any language / platform. I've got the following situation:               // in moduleA.js          exports.foo = function (var1, var2) {         // do something to var1 and var2 here              baz(var1, var2);     };          exports.bar = function (var1, var2) {         // do something completely different to var1 and var2 here              baz(var1, var2);     };          function baz(var1, var2) {         // do something to var1 and var2 yet again that both foo and bar need              moduleB.doSomething(var1, var2);     }      So, both `foo` and `bar` are public methods of `moduleA`. They've got some specific functionality (they do different things to `var1` and `var2`) but also some shared functionality (to keep things DRY I've moved it into a private method, `baz`) and then they both call a public method on `moduleB`. I've stubbed out `moduleB` so I know exactly what's going on after `foo` and `bar` have been called. I'm writing tests for `foo` and `bar`'s specific functionality but I'm not 100% sure how to approach testing the shared functionality in `baz`. It seems to me I've got three options:   * write identical tests for both `foo` and `bar` that test for the things in `baz`   * write a single test for `foo` and not write the same test for `bar` since know that `baz` works   * expose `baz` as another public method for the module and test it separately. I'm leaning towards the first option, but I feel I might be missing something.


How are hybrid VB6/.Net applications functioning in the Real World?

I am maintaining a VB6 application and we are studying how to migrate to .Net We are considering doing this gradually by implementing new features in COM visible .Net classes and migrating existing functionality slowly. I found some instructive 'Hello World' examples about how to do this and it works fine with our App. But how is the real world behaviour of these hybrid applications? Are they stable, maintainable? Particular of our program is that more users on the same computer will use it by switching user accounts. EDIT: The VB6 app reads data from a USB connection and stores it in an Access database. The user can call up various views on the data. The data is cached in a hardware device, so interuptions in the reading of it are not fatal.


What is the current state of Google's Dart programming language?

Dart has been out for ages (in internet years), but judging by Google Trends , it hasn't gotten much hype, and the fact that it only works in Chrome doesn't help either. Nonetheless, Chrome is gaining market share every day, which lends itself to a better view on Dart. What is the big picture now? What state is the language in? Do people regard highly of it? Market share? Web App showcase? Some feature implementations that make you go "I _have_ to use it"?


How to improve and start client interaction

How to remove hesitation of interacting with client ? As a Devloper i want to develop my career but this require the better Client Interaction,but as now i haven't done any major client interaction , and i want to do major client interaction, how i can proceed in this way ?


Why aren't user-defined operators more common?

One feature I miss in from functional languages is the idea that operators are just functions, so adding a custom operator is often as simple as adding a function. Many procedural languages allow operator overloads, so in some sense operators are still functions (this is very true in D where the operator is passed as a string in a template parameter). It seems that where operator overloading is allowed, it is often trivial to add additional, custom operators. I found this blog post, which argues that custom operators don't work nicely with infix notation because of precedence rules, but the author gives several solutions to this problem. I looked around and couldn't find any procedural languages that support custom operators in the language. There are hacks (such as macros in C++), but that's hardly the same as language support. **Since this feature is pretty trivial to implement, why isn't it more common?** I understand that it can lead to some ugly code, but that hasn't stopped language designers in the past from adding useful features that can be easily abused (macros, ternary operator, unsafe pointers). Actual use cases:   * Implement missing operators (e.g. Lua doesn't have bitwise operators)   * Mimic D's `~` (array concatenation)   * DSLs   * Use `|` as Unix pipe-style syntax sugar (using coroutines/generators) I'm also interested in languages that **do** allow custom operators, but I'm more interested in **why** it has been excluded. I thought about forking a scripting language to add user-defined operators, but stopped myself when I realized that I haven't seen it anywhere, so there's probably a good reason why language designers smarter than me haven't allowed it.


Is software design important to programmers?

I am studying software engineering, just finished the requirements course and going for more. I don't know how important software design is (in real world and actual projects) in later SDLC phases. As I read on the internet a lot of development teams like less documentation or design, and more coding. This makes my major worthless (in the real world). I am very good at programming and I like it but its not my main thing. I would like to hear from people about their experience with this, about a software engineer's actual role in real-world projects, and about how projects usually go?


How do I create an environment where fixing tests is seen as a priority?

I am a software engineer at a medium sized company. We have a fairly robust testing platform running on TeamCity. It does unit tests on every checkin, and a daily unit test/BVT run. The problem is - we have a great deal of broken unit tests. Quite often, I bring up the pointlessness of unit tests if they are constantly breaking and unmaintained. Being unable to see if a change has caused a regression removes most of the value of a unit testing platform. I would like to get a seed planted that will create a culture of good habits - fixing tests when they're broken, seeing them as valuable, prioritizing the fixing of tests along with other work. I've tried bribery (baked goods!), just plain asking, and speaking to team leads. Everyone says that it's a good idea, but I see to be the only one doing anything about it. What is the best way to get started on encouraging others to fix their tests, and prioritize test fixing within their sprints? If there is a less subjective way to ask this, I would be happy to accept any tips.


How to go about training IComparable to a team?

I (am just a developer) am tasked with training my team on a technique or technology. I zeroed upon System Interfaces, IComparable and IEquatable to be specific. How does one go about teaching (even if it is 1 hour), what an IComparable is and where we can use it by giving them an example. However, I am not entirely sure whether that would make my team to understand and start using IComparable. In my project, however, I do have a Discount class and there are instances where I have to merge two lists of Discounts. Now, that would be a really good instance of where IEquatable would be helpful when I do the merge wouldn't it? I had the following template for training.   * Introduction: Why does one need IComparable? (And, I could not get an answer that I can use for teaching).    * Structure of IComparable (Again, what else can I talk about other than CompareTo method).    * Sample Code   * Where we can use that in our project   * Questions.


Why is Python slower than Java but faster than PHP

I have many times seen various benchmarks that show how a bunch of languages perform on a given task. Always these benchmarks reveal that Python is slower then Java and faster than PHP. And I wonder why is that the case.   * Java, Python, and PHP run inside a virtual machine   * All three languages convert their programs into their custom byte codes that run **on top of** OS -- so none is running natively   * Both Java and Python can be "complied" (`.pyc` for Python) but the `__main__` module for Python is not compiled Python and PHP are dynamically typed and Java statically -- is this the reason Java is faster, and if so, please explain how that affects speed. And, even if the dynamic-vs-static argument is correct, this does not explain why PHP is slower than Python -- because both are dynamic languages. You can see some benchmarks here and here, and here


Why are inheritance and polymorphism so widely used?

The more I learn about different programming paradigms, such as functional programming, the more I begin to question the wisdom of OOP concepts like inheritance and polymorphism. I first learned about inheritance and polymorphism in school, and at the time polymorphism seemed like a wonderful way to write generic code that allowed for easy extensibility. But in the face of duck typing (both dynamic and static) and functional features such as higher-order functions, I've begun to look at inheritance and polymorphism as imposing an unnecessary restriction based on a fragile set of relationships between objects. The general idea behind polymorphism is that you write a function once, and later you can add new functionality to your program without changing the original function - all you need to do is create another derived class which implements the necessary methods. But this is a lot simpler to achieve through duck typing, whether it's in a dynamic language like Python, or a static language like C++. As an example, consider the following Python function, followed by its static C++ equivalent:               def foo(obj):        obj.doSomething()          template <class Obj>     void foo(Obj& obj)     {        obj.doSomething();     }      The OOP equivalent would be something like the following Java code:               public void foo(DoSomethingable obj)     {       obj.doSomething();     }      The major difference, of course, is that the Java version requires the creation of an interface or an inheritance hierarchy before it will work. The Java version thus involves more work, and is less flexible. Additionally, I find that most real-world inheritance hierarchies are somewhat unstable. We've all seen the contrived examples of Shapes and Animals, but in the real world, as business requirements change and new features are added, it's difficult to get any work done before you need to really stretch the "is-a" relationship between sub-classes, or else remodel/refactor your hierarchy to include further base-classes or interfaces in order to accommodate new requirements. With duck typing, you don't need to worry about modeling anything - you just worry about the _functionality_ you need. Yet, inheritance and polymorphism are so popular that I doubt it would be much of an exaggeration to call them the dominant strategy for extensibility and code reuse. So why are inheritance and polymorphism so wildly successful? Am I overlooking some serious advantages that inheritance/polymorphism have over duck typing?


How does the use of a rules engine impact the design, implementation, and performance of an application?

I'm interested in the ability of rules engines to:   * launch and iterate over business driven logic   * have "business users" perform the actual modification of those rules rather than developers   * comprehend the business rules in general Also, does using a rules engine impact the quality of an application? Does the use of a rules engine change if you were deploying to a 1-machine setup vs. your architecture vs. a multi-tier cloud-based distributed architecture using thousands of machines? How would it be different?


How can I get programmers to stop writing code vulnerable to SQL injection?

Sometimes you get busy and delegate small tasks to junior programmers. But if you don't pay close enough attention you find yourself with this kind of code in production:               class DivtoggleController extends Zend_Controller_Action {              public function closeAction() {             /* ... code removed for brevity ... */                  $req = $this->getRequest();             $formData = $req->getPost();                  $d = $formData['div'];             $i = $formData['id'];                  $dm = new Model_DivtoggleManager();             $rs = $dm->setDivToggleById($d, $i);              }          }               class Model_DivtoggleManager extends Zend_Db_Table {              public function setDivToggleById($div, $id) {             $result = $this->getAdapter()->query(                "update div_toggle set " . $div . "=1 where id=" . $id             );         }          }      So, given that I have removed the authentication / session management logic for brevity, who can tell me what possible problem there might be with this sample?


How to keep management out of our development process

I'm a software engineer in an software development team. The last 3 years we worked for an internal customer on a new product. Now this product is finished we're going to work on major new features for existing products. For a particular feature, product management have guessed it takes 150 hours to develop. Together with our project manager we have created a very detailed plan and we come to an effort of 300 hours. Yesterday we discussed this and they think we have grossly overestimated things. In our planning we estimated hours for writing unit tests, their idea is to dump them to save time. The decision has not been made yet and I will defend this planning and the unit tests if needed. But what I really don't like here is that management is interfering with our development process. How do I keep them out of our development process? And what arguments could I use to keep the unit testing in place (besides quality and long term time saving)? As a side note our company has 3 engineering teams and the team I'm in delivers their software on time (give or take a 10% margin). While the other teams always deliver late, mostly due to underestimation in planning. They only plan the coding and not the management, testing and handling around it.


Why are custom PDF download options preferred over ctrl+p?

Why do I, as a developer, have to go through so much trouble developing PDF download options for my clients when everyone in the world can simply hit Ctrl+P and life is good? The current issue I'm working on is dealing with Google Charts, so I'm not stating that offering PDF downloads in general is relatively difficult. On the contrary, particular cases are more trouble than they seem to be worth. See also: `@media print {}` Update: With a little research, I was able to find a perfectly workable solution. "Just hit Ctrl+P" now sounds like a ridiculous thing to say. Thanks everyone for your input. If you're interested to know what I decided to do, I realized that Google Charts are output as SVG markup and I think I should be able to use TCPDF to render them in a PDF document.


Formalizing programmers errors

Every one of us make errors leading to bugs. Once I wanted to start logging my errors for future analysis, probably mentioning project title, approximate time spent and the most important, the type of error. For example when I copy- pasted a fragment about 'x' and replaced every occurrence of 'x' with 'y' and forgot to replace a tiny piece, this goes to 'copy-paste error'. The usefulness of this approach depends on whether I can formalize my errors at all and probably minimizing the number of types to choose from. Otherwise I would start postponing, ignoring and so on so make this system useless. Are there existing research in this area, probably a known minimum set of errors? Maybe some of you already tried to implement something like this and succeeded/failed?


I hate one of our coding standards and it drives me insane, how to process it?

**Disclaimer** : Not as exaggerated as the title suggests, but it still makes me uncomfortable. I'm just going to express honestly, so take it with a grain of salt. Just pretend that I'm talking about _that_ coding standard that you don't like working with. **Edit** : The fact that I don't like it, doesn't mean I don't use it or enforce it. * * * I decided to ask this question in the spirit of how to get over a standard you don't like, not to get help on how to better argue how it can be changed (although any comments regarding this last part is appreciated). Besides, I work in a big company and such a change of something that has lived for so long and that matters so little is unlikely. The standard is the opening-curly-brace-on-dedicated-line standard:               somefunction()     {         //...     }      Instead of the ***clearly superior*** (note the joking/frustrated tone):               somefunction(){         //...     }      My personal arguments against the standard:   * **It bloats code** : extra unnecessary lines   * **Harder to type** : although probably this is just me struggling with the standard, I know one extra keystroke isn't that bad.   * **Not easier to read** : I start reading a function declaration, if statement, or any other scope-stacking statement and I already don't have to look for an opening brace. Nested blocks with this standard just make me angry for some reason.   * **Used by people who come from a Microsoft IDE background** : I think there should be an argumented reason (or more) behind a standard, not just take it in by paradigm. Their arguments (and my way of internally retorting to them):   * **Easier to read because you can see where blocks start and end right away** : I cannot understand this, what good is the block if you don't know what it is owned by, so then you have to read backwards.   * **I used it in a Microsoft IDE and I liked it** : Uhh... ok?   * **It is in the standard** : _*cringes*_ Am I the only one that struggles with an opinionated stance against a specific standard?, how have you gotten over these?, what is your opinion on what this particular standard should be (just for fun)?


Should all public methods in an abstract class be marked virtual?

I recently had to update an abstract base class on some OSS that I was using so that it was more testable by making them virtual (I could not use an interface as it combined two). This got me thinking whether I should mark all of the methods that I needed virtual, or if I should mark every public method/property virtual. I _generally_ agree with Roy Osherove that every method should be made virtual, but I came across this article that got me thinking about whether this was necessary or not. I am going to limit this down to abstract classes for simplicity, however (whether all concrete public methods should be virtual is especially debatable, I am sure). I could see where you might want to allow a sub-class to use a method, but not want it overriding the implementation. However, as long as you trust that Liskov's Substitution Principle will be followed, then why would you not allow it to be overriden? By marking it abstract, you are forcing a certain override anyway, so, it seems to me that all public methods inside of an abstract class should indeed be marked virtual. However, I wanted to ask in case there was something I might not be thinking. Should all public methods within an abstract class be made virtual?


How to increase the efficiency of an Immutable Queue in java?

I have been developing an Immutable queue in java, but the version I have developed is supposedly slow and I have been suggested to create a faster version of the same and I have no idea as to how to accomplish that.               import java.util.ArrayList;     import java.util.List;     import java.util.NoSuchElementException;     public class ImmutableQueueImpl<E> implements ImmutableQueue<E>     {              private List<E> queue;         public ImmutableQueueImpl()         {            queue=new ArrayList<E>();         }              public ImmutableQueueImpl(List<E> queue)         {            this.queue=queue;         }              public ImmutableQueue<E> enqueue(E e)         {                 if(e==null) throw new IllegalArgumentException();                 List<E> clone = new ArrayList<E>(queue);                 clone.add(e);                 return new ImmutableQueueImpl<E>(clone);         }              public ImmutableQueue<E> dequeue()         {                 if(queue.isEmpty())                 {                   throw new NoSuchElementException();                 }                 List<E> clone = new ArrayList<E>(queue);                 clone.remove(0);                 return new ImmutableQueueImpl<E>(clone);         }              public E peek()         {                 if(queue.isEmpty()) throw new NoSuchElementException();                 return queue.get(0);         }               public int size()     {         return queue.size();     }     }      Please suggest any improvements in the implementation or the libraries used . We remove elements from immutable lists all the time and dequeue is just a special case of that. The point is that the result is not really the element, but another immutable list without it. The point of this design is mutation safety and way better in parallelized settings than mutable data structures.


Enterprise Wide Keys

I have for a long time been working on an ODS as well as Data Warehouse. Both are integrating a wide variety of data sources from stove pipe applications. One of the uses of the ODS is to provide data to other stove pipe applications. Imagine one app maintains a database of personnel, and another app manages tracking sales. Occasionally the Sales app may need to have a drop down of personnel that someone can pick from, say to credit a particular employee with a sale/commission. The Sales application can query the ODS to get the list of personnel. This allows the Personnel app to change its data structure, and the ODS modifies the ETL process to adapt to that change. Thus all the other apps consuming that data will not be impacted by the change. The Sales app will need to save a PersonnelID to that sale/commission record in its own database. However, the next time the ODS is refreshed, if it is using a full load technique, the key will change. Since the PersonnelID stored in the Sales database is a separate database, there is no straight forward way to cascade that change. This creates a challenge where any changes made to the ODS have to be made very carefully, and may even limit certain designs because external applications are depending on those keys to never change. I would usually avoid exposing keys to users, but in this case it seems necessary to allow external apps to reference enterprise wide entities in their own applications. The same goes for lookup tables that are available in the ODS, where a lookup table has keys and text. After a full load of the ODS I can ensure the keys satisfy referential integrity within the database, but not with external databases utilizing those keys. Since there are some parts of the ODS currently coded as a full load, which would cause keys to be regenerated, I would need to recode that ETL to be incremental, so that external databases can reference those keys without fear of them changing. What techniques are used when you have an enterprise wide data source, and other applications consume that data and need to store foreign keys referencing entities in that data? How do you decouple the foreign key references as much as possible without complicating the access to that data? Currently I am using table valued functions to provide access to data. I chose this approach because it allows parameters, joins, and decouples access to underlying tables that may change later.


In Ruby, change global in thread safe block

In Ruby, I have a use case for a few common configuration options, e.g. NOOP, TRACE, SILENT. Right now I am using local vars instead of globals and passing them around all over the place and it's a pain. I be perfectly happy to use globals for these, if I could run a block where the globals can be temporarily changed and then reverted back. e.g.                global_configure(:TRACE=>true) do        ...      end      But how can I make that block of code thread safe, so that other threads can't change the globals on it?


Extracting data from log files

I will be extracting certain bits from log files using regular expressions to filter out bit of data. Initially I was going to do this with Python. I later started to think about the fastest way I can perform this task. This lead me to parallel programming. I remember hearing somewhere that Python can't be truly parallel. I'm by far an expert programmer. I have been playing with Java for a bit and I was considering parallel programming in Java to perform this task. I was wondering what would be the fastest way to perform this task?


What is a Spring AOP 'advice'?

As the question states. What is an 'advice'? More importantly, what does it even mean (semantics)? What's the etymology of 'advice' in the Spring context?


Presentation VS Application layer in DDD

I have trouble drawing a clear line between Presentation and Application layer in Domain Driven Design. Where should Controllers, Views, Layouts, Javascript and CSS files go? Is it in the Application or the Presentation layer? And if they go all together in the same layer, what contains the other one? Is it empty?


Best solution to run a Linux sandbox on my Windows machine?

I'd like to develop some node.js on my windows machine by using a virtual linux server that runs as a program and that I would access through ssh. I'd like this virtual linux instance to access the network as well. Is there any solution available? Preferably free ones.


Splitting 1 large object into 2 tightly-coupled ones - good, bad?

I have a complex object (call it BusinessLogic) which provides an RPC interface to semi-trusted users. The functions in the RPC interface have to decide which procedure to call, check authorisation for that function, perform some argument checking, and then call private functions to carry out the required functionality, and then return results to the caller. I decided to implement this by having the RPC functions in a separate stateless object (call it AppInterface), to separate out the concerns somewhat, so that BusinessLogic just moves its own data around and AppInterface decides which methods on BusinessLogic to call to implement the functionality it exposes. This works very well for the most part. However it feels a bit wrong to me. The BusinessLogic object has benefited from not having to worry about authorisation, argument checking, etc, which is good. But since the AppInterface implements all of its functionality in terms of BusinessLogic, it can just be a thin wrapper for some procedures (which makes me question its necessity) and is a complex wrapper in other procedures (which makes me wonder whether that complexity should be pushed back into the BusinessLogic, given that the BusinessLogic has all of the information needed to perform the task). It also means that AppInterface needs access to methods in BusinessLogic that would otherwise be private as nothing else uses them; think friend functions in C++. Finally, it means I can't effectively unit-test AppInterface without using a full BusinessLogic object as that is the only practical way to get valid output. I am happy to leave the system as it is, as it works, but I am curious as to whether there are obvious improvements I can make to such a system. (For what it's worth, I am using Python 2.7, in a primarily object-oriented style.)


Is CSS resizing of images still a bad idea?

It's always been looked at that using width/height attributes on images which aren't what the original image actual is is a bad idea. It could mean pixalated images or download sizes bigger than nessary. But, is this still an issue? I wouldn't suggest up-sizing photos, but downsizing shouldn't be an issue provided that its not too much of a difference from the original and keeping to scale. For example, I have a photo that is 600x400 and I stick a width of 400px on it. Most modern browser scale the image down and it looks like rendering is still decent. So, what is everyones view on this?


Better name for existsByUserNameAndPassword()

I wonder if there is a better name for a DB API function called `existsByUserNameAndPassword()` which returns boolean. There are more function called like this: `existsByOldId()`... It sounds a little bit unperfect... Is there a better concept for naming "exists" functions? I want to keep the "exists" somehow. To use this functions in a very speakable context like:               if ($DB->existsByUserNameAndPassword($name, $password)) {         // ...     }


Unit testing invalid inputs; ArgumentException vs. Custom Exception

In unit tested code I often have multiple checks on the arguments on any method before the actual "work" of the method is begun:               public void DoSomething(string test)     {        if (string.IsNullEmptyOrWhiteSpace(test))        {            throw new ArgumentException("Test must not be empty", "test");        }     }      In my corresponding test for this method I'll do the following:               [Test]     [ExpectedException(typeof(ArgumentException),         Message = "Parameter name: test",         MatchType = MatchType.Contains)]     public void TestNullInput()     {         var classToTest = new ClassToTest();         classToTest.DoSomething(null);     }      I'm thinking that this is quite a bad way to go about doing the test, however, as it relies on a specific named parameter (which does not necessarily hold true after any refactoring), as well as the format of the message of an ArgumentException. Another option might be to create a custom exception for this, some form of "TestWasNullOrEmptyException", but this also seems fairly awkward, as there will be many many different exceptions throughout the solution, each used to indicate only the absence/invalidity of a parameter. I am wondering if anyone else has dealt with this issue, and whether I'm simply going about my input validation tests the wrong way of it there's a more elegant solution. EDIT: This is C# code, and I'm using NUnit/Rhino Mocks.


Requirement gathering and use cases examples

I've heard a lot about requirement gathering and use cases in theory, but in practice often happens that we ask ourselves "should we include this? should this be a use case? in which language should we write this particular requirement" and so on. These questions are mainly because of lack of practice, and since we cannot go picking projects to "learn in practice" it's a little bit hard to get used to the kind of thinking we need in the process of gathering requirements for a new app. In that case, is there some place where can I find real life examples of requirements gathering and application of use cases? I've found some books, but they are mainly focused on teams and I work alone, so it becomes a little confusing.


what are your web application server side layering design rules and the best practices you like to apply?

A web application is often designed to be layered. Typically there would be a Repository (Dao) layer, a Service layer and a Control (web handling) layer. The Control layer uses the Service layer which in turn uses the Repository layer. Often you'll see the Control layer using the Repository layer directly. Also quite prevalent is Services using other Services. Quite often all Services inherit from a base service class which will contain all references to all Repository components. So my question is really how and why do you design your serverside application (in terms of layers) and what rules do you apply to them? What are the generally accepted justifications for these layers and these rules? What rules do you see that should be considered 'bad practice'? What rules do you considered essential? Have you tried anything new in this area that worked?


Documentation often ommits to specify which flavour of regular expression to use, so is there a default flavour that we should all be familiar with?

Often I come across documentation that says "use a regular expression here" I have to spend quite some time digging around trying to work out _which regular expression_ format they are expecting. As far as I can tell, there are many types of regular expression. But, at my last place of work I was made to feel stupid when I suggested adding some text to our User Documentation to specify _the type_ of regular expression to be used. When someone says "a regular expression" what is _the_ regular expression syntax most people expect and where is it documented? Update: I was prompted to single-out some examples - but no disrespect to these great projects:   * eregi docs page is not particularly helpful in explaining expected syntax.   * Nor can I easily work out the syntax expected here if i just land on the page from a search.   * No explicit mention of the regular expression pattern expected by `PatternExpectation()` on the SimpleTest page.    * etc. etc.   * here is a highly voted SO answer that seems to assume there is only one flavour of regular expressions.


Object orientated data structures in database driven applications

I've started working for a company that maintains a small/medium sized commercial website. The website is written in c# asp.net, and uses SQL Server as a database. The structure of the code is very messy at the moment (for instance, ~5000 line `Utility.cs` file) so I want to move towards a better design on the asp.net side of the application. I'm trying to figure out the right way to do this. My basic plan is to create a class for every logically distinct item in the application (mostly mapping 1-1 to database tables, but sometimes N-1 or 1-N). Then, I plan to have some static factory methods to instantiate these classes by querying the database. The developer should be able to manipulate the resultant object, and then use a `UpdateDatabase()` method to save the changes to the database. For example, here is how an `Email` object would work:               public class Email {         Guid userId;         Guid emailId;         String emailValueInitial = null;         Sting emailValueNew = null;              private Email();              public static Email RetrieveEmail(Guid UserId, Guid EmailId) {             // .. query             return new Email(UserId,EmailId,emailValueInitial);                     }              public String EmailValue {              get {                 if (emailValueNew == null) return emailValueInitial;                 else return emailValueNew;                          }             set {                 emailValueNew = value;             }         }              public bool Update() {            // .. update database with value of emailValueNew or do nothing if it hasn't             // been changed         }          }      Notes:   * I could update the database whenever a field is changed, but this is obviously inefficient.   * I don't know what to do in the event that the developer wants to insert a `null` value into the database - I suppose I need different concepts for 'null as variable not yet used' vs 'null as database value null'. The above is a simple case. I'd also need some way of knowing about many-one relationships in tables. For instance, a User could work like this:               public class User {         Guid userId;              public Emails emails = new Emails(userId);              private User(); // etc..              public RetrieveUser();         public CreateUser();              public Update();     }          public class Emails {         List<Email> emails = new List<Email>();              Guid userId;              public Emails(Guid userId); // etc..              public bool CreateEmail(); // its convinient to create/delete from here         public bool DeleteEmail(); // as I can enforce, say, minimum 1 email per user     }      * * * These above are my first thoughts on how to solve this problem, but I've never done anything like this before, and I don't know what problems I might come across. I want to make a system that will be scaleable and easy to develop as we take on more programmers, so its really important to get the initial design correct. What kind of design should I use in an object-orientated language to best represent and link with a database? What are important things to consider? Is there existing literature on this subject, or important libraries/constructs I have neglected?


What does well written, readable tests look like?

Doing unit testing for the first time at a large scale, I find myself writing a lot of repetitive unit tests for my business logic. Sure, to create complete test suites I need to test all possibilities but readability feels compromised doing what I do - as shown in the psuedocode below. **How would a well written, readable test suit look like?**               describe "UserEntity" ->       it "valid name validates"         ...       it "invalid name doesnt validate"         ...            it "valid list of followers validate"         ..


What's the difference between a stream and a queue? They both have the concept of an ordered set of elements, but tend to have different implementations and a different vocabulary of 'insert'/'extract' (streams) vs. 'enqueue'/'dequeue' (queue). Are these interchangable? Do they suggest different concepts or patterns? If so, what are the differences?


Looking for design pattern to represent shared state in music sequencer

I like to give lots of context, but also to state the basic question up top as concisely as possible. Feel free to read a little or a lot. I'm working on a music sequencer, and have been happy so far to be using a publish/subscribe approach to help decouple the major components of the application, which has helped testing and refactoring. However I'm wondering how components can share awareness of certain state without all adding a dependency on some new singleton OR abusing (published) events to each cache their own copies of this state. The specific example is the "playhead"; this and another example are explained below. Up until now, a playhead has been trivially represented as an instance of the immutable Timecode class, which has a measure, beat, and tick (essentially sub-beat unit). Components can subscribe to "beat" events and grab its timecode to update their internal "playhead" property. But as I get into other functionality like editing, I see components that track the playhead will also want to track the SequenceEvents active at the playhead time (e.g. notes). Also I need to add functionality for a "step region" which is a time segment (say, 1 measure), similar to the playhead but not a single moment in time, that components will similarly need to track. I've been stumped as to how to represent such objects in my application without introducing tighter coupling. The current approach where components listen for events does not seem a good fit. Right now, the Sequencer component emits a "beat" event which subscribers can use to update their playheads. Enhancing this event to include SequenceEvent data for notes, etc. smells bad as events typically are meant to be transient and consumed as they occur, not so that event consumers can update private state. Especially when that private state would be identical in each consumer. Also, other events than "beat" could signal a change of the playhead, e.g. the user clicks on another part of the score. If not events, any other approach seems to have multiple components dependent on some new "playhead" component, with bidirectional binding (that is, several components could both detect changes to the playhead and set its state). Even using dependency injection to reduce the dependencies for the sake of testing, this feels wrong to me. In case even more context helps illustrate the problem, read on... The app currently has several immutable data types that larger components may be dependent on (or may use without knowing their type): Timecode, SequenceEvent, Meter, Tempo, Stret (string/fret object), Pitch. Larger components which do NOT have construction-time dependencies include:   * Sequence: Represents a score, can be queried to iterate or random access sequence events.   * Sequencer: Handles playback and timing, currently emits the "beat" and "note" events.    * ScoreView: Renders a sequence as tablature (sheet music), and visually shows the playhead.    * NeckView: Shows a guitar neck with actively playing notes.    * GUI: This contains a number of simpler controls, including clock displays that update with the playhead. This component also instantiates ScoreView and NeckView components, but does not wire them to each other in any way.  All run-time "wiring" is internal to components, via PubSub.subscribe('eventName', handler). PubSub has pros and cons, but this has worked well to a point. However some cases where this approach breaks down are: 1) The guitar neck should show "static" markers for currently "selected" notes, in addition to playing active markers that animate when notes are played. This requires tracking state of which notes (strets) have start times at the current playhead. 2) Clicking on the guitar neck should toggle (add/remove) notes from the active sequence at the current playhead position. This would also be updated in the score view. 3) A new feature allows a "step region", which allows stepping through the score in increments like whole measures. So the current step could be larger than a single time point, and the neck and score views should be able to display static markers for all notes within the step region. This seems to be a duplicate of the same problem that applies to the playhead. Yet another approach that smells bad is to have these new entities all managed/owned by the Sequencer component, and have it publish events specifically like "playheadUpdated" and "stepRegionUpdated" that contain all the necessary data. This seems bad again because of the misuse of events to update redundant state in several components. This might be mitigated if the event referenced an immutable (or at least, not subject to change) object (e.g. for "playhead state"), maybe it would be less bad. But this approach still has the problem that other components cannot change the playhead or step region without publishing a request for the Sequencer to handle this change. Seems very wrong. Maybe others have solved this exact type of problem more elegantly than I'm thinking. Any pointers are appreciated.


Why do higher level languages have neither xor nor nand short-circuit operators?

While many higher level languages have bitwise (exclusive or) and bitwise (exclusive and), for instance C, C++, Java, etc. I'm curious why the ( _vastly more useful_ ) logical short-circuit operators don't have this functionality? Is it simply due to the capacity of being able to concatenate logic through use of "not"? This question is mainly to do with the language design considerations....


Should I leave href empty when implementing click events via jQuery?

Is it preferable to have `#` in a link's `href` attribute when I am implementing the `click` event via jQuery, or is it ok to leave `href` empty? i.e.                     vs                     When I'm doing               $("#myLink").on('click', function() {        // do ajaxy stuff     });      Although I understand the click event could be on a span or other such element I'm interested in this case for particular best practices when using an `a` tag.


What is the name of book that offers guidance on when to use each verb for a method call? For example, I might use GetApples() to return a list of Apple instances; or I might use BindApples(IControl control) if I want to bind these apples to a dropdown list. What book would suggest when you use Get or Bind as part of a method name?


Data Persistency, patterns and approaches

Data persistency has recently become a really grip for me, especially how long to maintain database connectivity and how many connections are feasible for a given request. I've been using .NET; however, this is a generic question related to any lanaguage. From a .NET perspective, I'm connecting to database using EF4 and for a given website page I might create 6 connection per-request to render a page. The page might consist of news, stock prices, etc, and needs to be constantly updated. I've recently been looking at unit-of-work (i.e. per request) approach. So basically when a request starts, if required a database connection is opened and destroyed upon end of the request. I'm not convinced it's the best approach yet. I'm looking for opinions and experience on it.


How can a Mac or Unix owner fix/develop webpages for IE6/IE7?

I work on Debian and before Debian I was on Ubuntu. In my previous job, we simply ignored IE6, but at my present job a page must work flawlessly for IE6 onwards. The one wayout for me is to set up a Windows VM but that doesn't help every time. Consider this, if I was a freelance consultant and didn't want to or have enough money to buy licenses for every possible Windows version how could I deliver a web page that worked for IE6/IE7?


Would you refactor this and if so, would you charge your client?

I am working on a freelance job at home. The client wants me to write some new functionality for his CMS, but it is taking me a lot of time to figure out what the code is doing, because it is written in a very unreadable style. Below is just an example of what I mean. The previous programmer made extensive use of anonymous functions, of eval(), he uses deeply nested ternary operators, he didn't indent code, didn't use comments, and he uses funny constructions like misusing the behaviour of logical operators || and && for creating if/else conditions (the second condition of && only gets tested if the first one is true, opening the possibility to use && as an if/else construction). All in all it's insane code and it's costing me a lot of time to find out how the current code works.               return ($this->main->context != "ajax" || in_array($this->type, $this->definition->ajax)) ? eval('return method_exists($this,"Show'.ucfirst($this->type).'") ? $this->Show'.ucfirst($this->type).'('.(count($args) ? join(",",array_map(create_function('$a','return (is_numeric($a) || preg_match("/^array/",$a)) ? $a : "\"".$a."\"";'),$args)) : "").') : null;') : '';      Would you refactor this code and how would you handle this sort of thing with your client, I mean financially?


What build tools do not depend on java (or Ruby)?

I'm wondering what generic build tools out there include their binary run- times and do not depend on another environment not shipped with them. For example, ANT requires Java, Rake requires Ruby, etc.. would be great if talking about also target-platform-agnostic tools, where I'd just give whatever command for building, whatever command for testing, etc.. and can then define my artifacts in CI or so. Would see something like that useful for building .NET projects (say, on both Windows .NET and Mono), and Node JS projects especially. I do not want to install Java and / or Ruby if what I want is a .NET build or a Node JS build. This is a bit of general awareness question not an exact problem I'm facing, that's why it's here not on StackOverflow. **Update:** To explain a bit more, what I'm after is the build script that would run MSBuild for compiling for example ( in .NET, and then maybe several Node/NPM commands in Node, etc..), and then have the rest build/test steps, instead of setting these all in MSBuild (again, in .NET case, also, wondering if there is equivalent story in Node). **Update2:** My target is being able to have a developer on a vanilla machine to just clone the code without installing any dependencies except the platform the code targets be it .NET/Mono or Node (not even Java, Ruby, or Python) and still be able to build and run tests.


Print bottom view of a binary tree

For a binary tree we define horizontal distance as follows:                   Horizontal distance(hd) of root = 0         If you go left then hd = hd(of its parent)-1, and          if you go right then hd = hd(of its parent)+1.      The bottom view of a tree then consists of all the nodes of the tree, where there is no node with the same `hd` and a greater level. (There may be multiple such nodes for a given value of `hd`. In this case all of them belong to the bottom view.) I'm looking for an algorithm that outputs the bottom view of a tree. * * * Examples: Suppose the binary tree is:                        1             /  \            2    3           / \  / \          4   5 6  7                 \                  8      Bottom view of the tree is: 4 2 5 6 8 7                   Ok so for the first example,         Horizontal distance of node with value 1: 0, level = 1         Horizontal distance of node with value 2: 0 - 1 = -1, level = 2         Horizontal distance of node with value 3: 0 + 1 = 1, level = 2         Horizontal distance of node with value 4: -1 - 1 = -2, level = 3         Horizontal distance of node with value 5: -1 + 1 = 0, level = 3         Horizontal distance of node with value 6: 1 - 1 = 0, level = 3         Horizontal distance of node with value 7: 1 + 1 = 2, level = 3         Horizontal distance of node with value 8: 0 + 1 = 1, level = 4              So for each vertical line that is for hd=0, print those nodes which appear in the last level of that line.         So for hd = -2, print 4         for hd = -1, print 2         for hd = 0, print 5 and 6 because they both appear in the last level of that vertical line         for hd = 1, print 8         for hd = 2, print 7      One more example for reference :                        1           /     \         2         3        / \       / \       4   5     6     7       / \ / \   / \    / \     8  9 10 11 12 13 14 15           So the output for this will be : 8 4 9 10 12 5 6 11 13 14 7 15               Similarly for this example     hd of node with value 1: 0, , level = 1     hd of node with value 2: -1, level = 2     hd of node with value 3: 1, level = 2     hd of node with value 4: -2, level = 3     hd of node with value 5: 0, , level = 3     hd of node with value 6: 0, level = 3     hd of node with value 7: 2, level = 3     hd of node with value 8: -3, level = 4     hd of node with value 9: -1, level = 4     hd of node with value 10: -1, level = 4     hd of node with value 11: 1, level = 4     hd of node with value 12: -1, level = 4     hd of node with value 13: 1, level = 4     hd of node with value 14: 1, level = 4     hd of node with value 15: 3, level = 4          So, the output will be:     hd = -3, print 8     hd = -2, print 4     hd = -1, print 9 10 12     hd = 0, print 5 6     hd = 1, print 11 13 14     hd = 2, print 7     hd = 3, print 15           So the ouput will be:     8 4 9 10 12 5 6 11 13 14 7 15      * * * I already know a method in which I can do it using a lot of extra space (a map, and a 1-D array for storing the level of the last element in that vertical line) and with time complexity of $O(N \log N)$. And this is the implementation of this method:               #include <iostream>     #include <cstdio>     #include <map>     #include <vector>          using namespace std;          struct Node{            int data;            struct Node *left, *right;     };          Node* newNode(int data)     {         Node *temp = new Node;         temp->data = data;         temp->left = temp->right = NULL;         return temp;     }          int height(Node *node)     {         if(node == NULL)                 return 0;         else{              int lh = height(node->left);              int rh = height(node->right);                   if(lh > rh)                    return (lh+1);              else                    return (rh+1);         }     }          void printBottom(Node *node, int level, int hd, int min, map< int, vector<int> >& visited, int lev[], int l)     {          if(node == NULL)                  return;          if(level == 1){                   if(lev[hd-min] == 0 || lev[hd-min] == l){                           lev[hd-min] = l;                           visited[hd-min].push_back(node->data);                   }          }          else if(level > 1)          {               printBottom(node->left, level-1, hd-1, min, visited, lev, l);               printBottom(node->right, level-1, hd+1, min, visited, lev, l);          }     }          void findMinMax(Node *node, int *min, int *max, int hd)     {          if(node == NULL)                  return;               if(hd < *min)               *min = hd;          else if(hd > *max)               *max = hd;               findMinMax(node->left, min, max, hd-1);          findMinMax(node->right, min, max, hd+1);     }          int main()     {         Node *root = newNode(1);         root->left = newNode(2);         root->right = newNode(3);         root->left->left = newNode(4);         root->left->right = newNode(5);         root->right->left = newNode(6);         root->right->right = newNode(7);         root->left->left->left = newNode(8);         root->left->left->right = newNode(9);         root->left->right->left = newNode(10);         root->left->right->right = newNode(11);         root->right->left->left = newNode(12);         root->right->left->right = newNode(13);         root->right->right->left = newNode(14);         root->right->right->right = newNode(15);              int min = 0, max = 0;              findMinMax(root, &min, &max, 0);              int lev[max-min+1];         map < int, vector<int> > visited;         map< int,vector<int> > :: iterator it;              for(int i = 0; i < max-min+1; i++)                 lev[i] = 0;              int h = height(root);              for (int i=h; i>0; i--){             printBottom(root, i, 0, min, visited, lev, i);         }              for(it = visited.begin() ; it != visited.end() ; it++) {             for(int i=0 ; i < it->second.size() ; i++) {                 cout << it->second[i] << " ";             }         }              return 0;     }      I am seeking help to do this in more optimized way, which used less space or time. Is there any other efficient method for this problem?


Invalid data returned, which HttpCode to return?

My web application calls a third party API. If I successfully call the API but invalid data is returned which cannot be processed by my system what is the most appropriate HttpCode to return to the user calling me?   * 500, I'm not convinced. Although it was an internal error it's due to external factors   * 503, Perhaps, although very vague   * 400, 4XX errors are usually related to the client contacting our server and so could be misleading. Which is the most appropriate response to return to my client?


Is it considered "conveying" if I share modified LGPL v3 code on GitHub?

It is critical to know what constitutes "conveying" under LGPL v3. I am considering creating some software based on LGPL v3. The software will be used to run a web application. Now I wonder whether the "conveying" clauses would get activated if I published the modified code on GitHub to the public. I understand that none of you are lawyers so IANAL is implied. I also understand that I could contact the developers of the LGPL software and ask for a different license.


How do I determine how many numbers are in a floating point number system?

I'm trying to make floating point number systems a bit more intuitive for myself. There are a few things I am confused about, and I think the best way to clear up my confusions would be for someone could guide me through one question: How many numbers are there in a floating point number system (Given the base, precision, max exponent, and min exponent)? This is what I am thinking: I figure that the maximum possible number (realmax) divided by the smallest possible number (realmin) would give all of the possible positive numbers. Part of me also believes I could divide realmax by the smallest increment, machine epsilon (eps), to figure out how many numbers there are. Just looking at the differences in magnitude between eps (10^-16 for IEEE double precision) and realmin (10^-308), however, tells me this isn't true at all. I can't think of an intuition for why! So the problem I am facing is determining the correct formula for realmax and realmin. The answer I get using my textbook's formulas differ radically from the one I got with wikipedia's formula. Help!


IPv4 to IPv6. where is IPv5?

As all of us know that after IPv4 it came IPv6. How this transition happened? I just want to know was there any IPv5 also? or there is any other logic in naming this version of IP as IPv6?


Should I use simple socket programming to communicate between 2 threads?

Is it a good idea to communicate between 2 threads using sockets in Java? What I am trying to achieve is Inter-process communication using socket programming/RPC mechanism.


How to manage a virtual group in a company?

I have worked as a software engineer for more than 6 years. Recently, my boss has asked me to build and manage a virtual team. While I'm glad I can do some management work, I don't think it will be easy to do the management. My team members are only part-time on this project, they come from several teams, and their direct manager is not me. They want to be given technical work but my boss wants us to organize some activities. I'm trying to work out how to balance these two conflicting requirements. Overall, my team manages several parts of an internal BBS which features topics about innovation. Unfortunately, the BBS is not very popular and few colleagues want to spend more than a second on it. They say that they are too busy, but more likely it is an excuse, probably because the BBS is not user- friendly. I don't know why BBS is so important. However, my boss likes the BBS and want my team to make it better. Personally, I don't know why this BBS is so important. Overall, I need some guidance about how to approach this.


How to avoid overhead while still implementing null object pattern?

I am implementing a binary search tree in java. Inside the BST class I have a protected class Node (in case I want to extend to an AVL tree). The code is below. I had a problem, both conceptually and aesthetically, implementing empty nodes as null pointers. So instead I opted for the null object pattern and created an EmptyNode object, the code for which is also below. However, even though this gives me prettier code and something more conceptually pleasing (to me), I now have the problem that when I'm working with a tree of height n, I can have as many as 2^{n+1} - 2^{n} instances of this EmptyNode class floating around, which takes up space for no good reason. How should I fix this code to avoid this overhead while still implementing the null object pattern? I feel like the EmptyNode should be something conceptually similar to a constant field of Node, but I can't implement that. I also feel like there should be only one copy of EmptyNode being referenced anywhere, but I can't figure out how to implement that either. Any help or recommendations are appreciated.               protected class Node<Key,E>{         protected Key key;         protected E value;         protected Node<Key,E> left;         protected Node<Key,E> right;         protected int height;         protected int balanceFactor;         public Node(){}         public Node(Key k, E v){             key = k;             value = v;             left = new EmptyNode<Key,E>();             right = new EmptyNode<Key,E>();             height = 0;             balanceFactor = 0;         }         public Node(Key k, E v, Node<Key,E> l, Node<Key,E> r){             key = k;             value = v;             left = l;             right = r;             height = Math.max(l.height(), r.height())+1;             balanceFactor = l.height() - r.height();         }         public Key getKey(){return key;}         public E getValue(){return value;}         public Node<Key,E> getLeft(){return left;}         public Node<Key,E> getRight(){return right;}         public int height(){return height;}         public int balanceFactor(){return balanceFactor;}         public void setKey(Key k){key = k;}         public void setValue(E v){value = v;}         public void setLeft(Node<Key,E> l){             left = l;             height = Math.max(l.height(), this.right.height())+1;             balanceFactor = left.height() - this.right.height();         }         public void setRight(Node<Key,E> r){             right = r;             height = Math.max(this.left.height(), r.height())+1;             balanceFactor = this.left.height() - right.height();         }         public boolean isEmpty(){return false;}         public boolean isLeaf(){             return (left.isEmpty()) && (right.isEmpty());         }         public boolean hasLeft(){             return !left.isEmpty();         }         public boolean hasRight(){             return !right.isEmpty();         }     }     protected final class EmptyNode<Key,E> extends Node<Key,E>{         public EmptyNode(){             key = null;             value = null;             left = right = null;             height = -1;             balanceFactor = 0;         }         @Override         public void setKey(Key k){}         @Override         public void setValue(E v){}         @Override         public void setLeft(Node<Key,E> l){}         @Override         public void setRight(Node<Key,E> r){}         @Override         public boolean isEmpty(){return true;}         @Override         public boolean isLeaf(){return false;}         @Override         public boolean hasLeft(){return false;}         @Override         public boolean hasRight(){return false;}     }


Why HTML select is not searchable by default?

I was wondering why the default select tag of HTML, for example:               <select name="company_name">         <option value=""></option>         <option value="1">Company 1</option>         <option value="2">Company 2</option>         <option value="3">Company 3</option>         <option value="4">Company 4</option>         <option value="5">Company 5</option>         <option value="6">Company 6</option>     </select>      is not searchable by default. Of course this is a browser feature, but it is just really weird that none browser (as far as I know) doesn't have it. Am I missing something here? Is there any browser that actually have as default a searchable select tag? Is it so complicated to achieve it, or is it just that people doesn't want it? Is this a problem with OS? I know that I can achieve that easily with JavaScript (e.g. Jquery Chosen plugin... e.t.c.) but I was wondering if there is any plan for popular browsers like firefox and chrome to have it as default. The result that I am expecting is like the below image on Windows: ![enter image description here](http://i.stack.imgur.com/wyzpv.png)


What do you consider the 1st principle(s) of programming?

I always liked to ask myself "what's the first principle(s) of this?" after I learned the basic stuff of something (e.g. programming). It's an inspiring question, IMO, that can force you to think about the most important principle(s) behind something, especially a skill such as programming. So, what do you think is the first principle(s) of programming? I'll give my answer below a little later.


Frustrated where I am, but not sure where to go with my career

I work (3 years now) as a lead developer for a team developing internal tools and websites for a customer account within large outsourcing company. I'm a self taught programmer and my previous incarnation was a 3rd line support guy, so I have a solid infrastructure knowledge. We use VB.Net/MSSQL/SSIS/SSRS ASP.NET (nTier) in house and I have about 8 years coding experience. Without going into too much detail, my boss is very ambitious and uses our team as his footing to get up the ladder. I've been in the team from the start and the only new dev's we have brought in have been people with a bit of VBA/VBScript experience, much to my chagrin, to bolster his empire. It's been a lot of hard work to bring them up to a standard, but there's still a lot for them to learn. This makes my life stressful as I always get the high profile/complex project work to do as other's simply cannot do it, or it'd take them twice/three times longer to do it. My boss is always seeking stuff for us to build for people who haven't asked for it, which usually get's thrown to me as I have the most experience and can pick new API's (etc) up quicker. He doesn't give us proper requirements, we don't get time to design properly before we code, he wants us to throw something (quick and dirty as he calls it) together so we can get it out ASAP. I take pride in my work so I like to do it properly, make my code clean, maintainable etc, and I train the other guys in the team to do the same. But, we always fall on our faces. The customer we drop the apps on say it doesn't do what they need (due to few requirements), or my boss doesn't like it/changes the spec, so we have to rework it, it get's drawn out, and it makes us and me look and feel like fools. We then get accused by boss of not being reactive enough to change. I've had enough. In order to get my skills and knowledge gap's filled, I've been reading Code Complete 2nd Ed (McConnell) and the Head First Design Patterns books. I'm forcing myself to move into C# from VB at home to broaden my horizons. I'm not sure where to go from here. I don't want to code all my life as I'd like to move into a higher level design/architects role at some point in time (I'm 35). Where do I/can I go from here?


How to construct a cubie representation of a rubik's cube, given an array

Just to get this out of the way, I have seen this, and it is not what I'm looking for. So, let's say you are programming a Rubik's Cube. (I know, very unoriginal, but bored programmers have to do something..) This Rubik's Cube is defined by an array of six 2-D arrays (one for each face,) and these 2-D arrays' sizes vary, based on the size of the cube. For instance, if I had a 3x3x3 cube, the array would be 6x3x3. That is, it would have 6 3x3 arrays. Now, let's say I wanted to get an array of the cubies which make up this cube. Each cubie is defined by two things (I think..): the colors of it and its location on the cube. For example, if you had a solved cube, one of the cubies would be the red, green, and yellow cubie, and, assuming yours is sitting in the same orientation as mine, that cubie would be the front, right, up cubie. However, none of this answers my question: how do I go about defining a set of these cubies, given an array of variable sizes. I know, for instance, that the cubie previously mentioned could be defined as cube[0][0][dimension-1], cube[2][0][0], cube[4][dimension-1][dimension-1]. (For a bit of reference, the order in which I define my faces is front, back, right, left, up, down. Hence the 0, 2, and 4, making front, right, and up.) Anyway, with that said, I'd rather not hard-code all of this and was wondering if there was a simpler way. So, what's the best way to do something like what I was just describing? **Edit:** For clarification, I am trying to get the separate, individual, smaller cubes which make up the Rubik's Cube as a whole. For instance, the piece with the red, green, and white stickers on it.


Java style classes in c++

I came across this article proposing a style of coding in c++ that looks a bit weird at first. But after reading it over and pondering for a bit I'm really considering giving it a try. The most appealing benefit is the ease of refactoring methods. I find myself constantly changing method names, parameters and so on while writing a new class and in c++ it's quite annoying having to change a method name in two files (.h, .cpp). I tried to find something wrong with this style but apart from the fact that the code will look and feel **really** strange to seasoned c++ programmers I can't spot any major flaw. But since I am quite a inexperienced c++ programmer I hope that someone here might alert me to any potential dangers. So my question is: **Are there any serious drawbacks of using this style of coding?**


Encapsulate bitmap (*.bmp) as C++ class

How would you implement / design a class which has to represent a bitmap? I'm stuck at handling the different possible color modes and I keep thinking that this should be somehow implementable using templates / design patterns in an elegant AND efficient way: Suppose you have a file.bmp. You then want to open that file to use it in your application:               Bitmap myBitmap();     myBitmap.open("file.bmp");      The bitmap you just opened could have RGB colors, or it could be a grayscale image, or even a 1 bit per pixel image (i.e. black and white). In my application, I want to operate on the image (pixel) data. For example, I need some sort of brightness filter where I black out pixels whose (Red + Blue + Green) / 3 is below some filter value (i.e. 100). So I need access to the pixels:               Pixel somePixel = myBitmap.pixelAt(10,30);      But now I face the problem of NOT knowing what type of pixel this is. Of course, I could provide subclasses of `Pixel` (which then is an abstract base class) which ALL implement methods like `getRGB()`, `getGrayScale()`, ... where each subclass gives a way of converting between those colormodes (i.e. RGB to grayscale) But this feels ... hm, "wrong". Do you know some good way to implement this? A nice feature I was thinking about is something like:               myBitmap.getMode(); // A RGBMode object, RGBMode being a subclass of Mode     myBitmap.setMode(new BlackWhiteMode()); // Converts the bitmap to a 1bpp image      Any ideas, recommendations, improvements? * * * So the really hard part is to represent the different color modes, like RGB (8bit and 4bit), HSV, Grayscale, BlackWhite, ... without messing the applications code.


Emacs vs. vim -- what is the difference?

I've been programming for years now, mainly in VBA (the _horror_ ), Python, Javascript (Node.js mainly), HTML, and SQL. Most of these languages came with environments that made sense: for VBA I used the built-in editor for Microsoft Office, HTML I could use whatever and debugged with Chrome Dev Tools, and SQL doesn't really require anything fancy. However, for Python and Javascript, I switched around a bunch between editors. History of my usage: Python - IDLE, nano, Notepad++, Sublime Text 2, JetBrains PyCharm   Javascript - Notepad++, Sublime Text 2, Node interpreter, JetBrains WebStorm Languages I plan to learn (eventually): [Clojure | Common Lisp | Scheme], [C | C++ | Objective C], Ruby, Haskell, Assembly As I'm getting more serious into programming, I'm starting to look into the most famous editors--emacs and vim. I have some idea of what they do and don't have over IDEs. I'm a really quick typer so I like the idea of not having to use the mouse. I also love the functions that Sublime Text 2 has for quick switching for funcitons and across open files, and also the multiline select. However, despite lots of research, I'm having trouble figuring out the difference between emacs and vim, and I'd like to have a good understanding of them before deciding which one to commit lots of time to. ## TL;DR **Question:** What are the key differences between emacs and vim? What are the advantages and disadvantages of each for a developer? **Please note: I am _not_ asking which is better, which is higher quality, which is more useful--I'm not trying to restart a famous debate. I just want to know what is distinct about each in terms of functionality and user interface, so I can decide based on my own needs.**


What factors should I consider when logging a (JSF) web-app?

I've recently read the article The Problem with logging and was wondering about my current logging strategy.   Usualy I use Log4J in my projects and just have to decide _which line/attributes_ I would like to log.   This strategy worked well for me in the past for all my projects without user- interaction. Now I want to set up logging for a WebApp with user-interaction like login, session-management, personalized user pages, etc. and was wondering what would be best practice. To clarify:   I don't ask you to help me decide **what** informations I have to log because that I know for myself (or find information in articles on this site or google).   I'm asking about the things connected with this topic:   * should I bind every log message to the corresponding user for traceability   * should I open up a new log file for every session   * are there other good libraries especially for logging webapps   * should I only log fatal errors in file and handle minor errors inside the view (e.g. show user)      * and how chatty should I be in those messages shown to the user I also know that this is a broad topic and that this question can easily be answered by "it's personal flavor" or "it depends" but I would highly appreciate anyone who's willing to give me some useful hints. Thanks in advance


Can I license a program under Apache License 2.0, if it is using/including Eclipse Link (EPL or EDL)?

Can I license a program under Apache License 2.0, if it is using/including EclipseLink? (EclipseLink under Eclipse Public License or Eclipse Distribution License) I did not change anything in EclipseLink. I would realy like to distribute a Version that includes the needed EclipseLink jars, so that it is working "out of the box".


Magic square check for N×N matrix with minimum complexity

Is there any algorithm that works better than `O(n²)` to verify whether a square matrix is a magic one (e.g. such as sum of all the rows, cols and diagonally are equal to each other)? I did see someone mention a `O(n)` time on a website a few days ago but could not figure out how.


Selective mutual exclusion in Dining Philosophers and Readers and Writers problem

I've been reading about selective mutual exclusion (SME). The idea I got is that if a process competes for its resources against a subset of all the other process instead of competing with all the other processes then I'm facing a SME problem. 1) Can you confirm my definition is right? Now, the dining philosophers problem is a classic example of this (SME by proximity) 2) In the distributed solution (in which each philosopher competes for both forks against two other philosophers), if instead of 5 philosophers, there were 3 of them, would it still be a SME problem? (I think not, because each philosopher will be competing with all of the others) 3) And in the centralized "conductor" solution, having 5 philosophers, would it still be a SME problem? (I think it would, because although all processes are competing to get to the waiter, each philosopher is only competing with two of the other to get both specified forks) Finally, in the readers and writers problem (SME by process type) 4) If only 1 reader and 1 writer were allowed, would it still be a SME problem? (I think not, because actually every process will be competing with all the others)


How to model two similar tasks with the Use-case diagram

I am trying to draw a use-case diagram for a software project. Two requirements for the software I am trying to model in use-case diagram are:   1. A customer (i.e. `Client`) should be able to cancel its previous request. In this case, the client must select the relevant request from their list of request.   2. A `travel agent` should be able to cancel a request. in this case, the agent must the client from the list of clients and the request from the list of request issued by that client. How should I model this two requirements in a UML user-case diagram? I've ended up to something like this: ![My use-case diagram](http://i.stack.imgur.com/VjW4B.png)


Branch twice for unique condition

Consider an application that displays only Foobars belonging to themselves to normal users, and all Foobars to admins:               -- Normal users:     SELECT * FROM Foobar WHERE user_id=:user_id;          -- Admins:     SELECT * FROM Foobar;      Currently, this how the queries are represented in the codebase:               $sql = "SELECT * FROM Foobar";          if ( $user['type']!='admin' ) {         $sql.= ' WHERE user_id=:user_id';     }          $stmt = $pdo->prepare($sql);          if ( $user['type']!='admin' ) {         $stmt->bindValue(':user_id', $user['id']);     }      I do not like this dual-branching approach from a maintainability standpoint. For instance, a bug like typing `$user['type']=='admin'` instead of `$user['type']!='admin'` would have to be found and fixed in two places instead of one. However, I also don't like the idea of separate functions for each case: admins and regular users. A third approach would be to branch once and there create the SQL to add and the values to bind:               $sql_to_add = '';     $array_to_bind = array();          if ( $user['type']!='admin' ) {         $sql_to_add = ' WHERE user_id=:user_id';         $array_to_bind = array( ':user_id'=>$user['id'] );     }          $sql = "SELECT * FROM Foobar {$sql_to_add}";     $stmt = $pdo->prepare($sql);          foreach ( $array_to_bind as $k=>$v ) {         $stmt->bindValue($k, $v);     }      However I find this approach cumbersome. **Is there a design pattern for this situation?** What is the canonical way to handle situations where the code must branch in two separate locations on the same `if` condition?


Further writings by Rob Pike on software complexity and design

in "Notes on Programming in C", in section "Complexity", Rob Pike writes: > Most programs are too complicated - that is, more complex than they need to > be to solve their problems efficiently. Why? Mostly it's because of bad > design, but I will skip that issue here because it's a big one. .../... Does anyone know whether Rob Pike has written more about software design and how to avoid complexity, and where this might be found?


Chained ruleset parsing and evaluation code: recommendations?

So I have to write a filtering system, which may apply preprocessed ruleset to data - and trigger some actions defined in the ruleset while continuing its evaluation.               <ruleset name="1">      <rule>       <conditions>        <and>         <or>          <match image="aceofspades" level="70" />          <match image="aceofdiamonds" level="66" />         </or>         <not>          <match image="aceofclubs" level="60" />         </not>        </and>       <action name="apply_ruleset" ruleset="2">      </rule>      <rule>       ...      </rule>     </ruleset>     <ruleset name="2">     </ruleset>      (Good example of what it feels to be alike: sendmail configs; some Apache configs; IPTables ruleset, with multiple tables, JOIN/ACCEPT/DROP, etc). What bothers me with every current design I can think of:   * keeping state of and-or nodes   * being able to jump between main and sub- rulesets easily   * tracking circular references   * keeping a vast set of possible conditions   * runtime speed: parsing/hashing may take time, but each data packet must be passed through dataset as fast as possible. What should I read/think of to be sure that my parser will be nice enough to work with large sets and don't mess the speed/flexibility too much? _(Not to mention iptables code)_. * * * Target language is C++ (however would like to implement a similar system in Perl later..), was reading through this \- but still not see a good solution for switching rulesets / keeping with boolean logics within rules.


Why doesn't CSS natively support variables and hierarchy?

I am new to UI development, but I feel very uncomfortable with how CSS works. My use case is that I wanted to apply some specific styles inside a particular `div` on a page. **CSS attempt:**               div.class1 {         font: normal 12px arial, helvetica, sans-serif;         font-color: #f30;     }     div.class1 div.class2 {         border: 1px solid #f30;     }      **LESS attempt:**               @red: #f30;     @font-family: arial, helvetica, sans-serif;     div.class1 {         font: normal 12px @font-family;         font-color: @red;         div.class2 {             border: 1px solid @red;         }      The CSS version can induce bugs, since it forces you to repeat `#f30` & `div.class2` every time you try to achieve hierarchy and variable re-use. **My questions:**   * Why is that CSS makes things difficult?   * LESS does nothing special - just makes obvious improvements and translates to CSS?   * What is that CSS wants to motivate in users because of which it promotes such a redundant coding style? I strongly believe CSS should be what LESS is. Definitely I am overlooking some obvious advantage of why things are done that way in CSS. I thought it was a legacy problem, but I was surprised when I saw no attempts to solve this with CSS3. Please help me understand how should I approach CSS?


How does const storage work? (Item 2, Scott Myers Effective C++)

In Item2 on page 16, (Prefer consts, enums, and inlines to #defines), Scott says: > Also, though good compilers won't set aside storage for const objects of > integer types... I don't understand this. If I define a const object, eg               const int myval = 5;      then surely the compiler must set aside some memory (of int size) to store the value 5? Or is const data stored in some special way? This is more a question of computer storage I suppose. Basically, how does the computer store const objects so that no storage is set aside?


What makes a successful architecture team?

I was recently appointed as the leader of a newly formed architecture team (most similar to systems or enterprise architecture, not explicitly software architecture). My company is medium sized, and there are ~8 different engineering groups each with their own stacks, and their own culture. As part of this re-org, many of those groups are going to be consolidated and part of my team's job is to figure out how to bring their stacks into alignment. In thinking about the new team's charter, we've struggled with:   1. How should the architecture team engage and interact with the engineering teams without stepping on toes, while remaining effective? When should architecture stand back and let engineering do its thing?   2. (related to the above) When is it appropriate for the architecture team to build something versus when should the architecture team provide guidance, and allow the engineering team to build it themselves?    3. How can an organization measure the success of an architecture group? None of the goals of architecture seem easily quantifiable. **As an example:** Should the architecture team be involved with setting coding standards? Theoretically, this is something that the engineers use day to day, and could be set by engineering leadership, but it could also be tied to architectural needs. For example, if architecture defines the directory structure of a standard project, and how the build should be set up to fit within the CI that they've mandated, shouldn't they also have a say in the documentation and coding standards in order to be consistent with their directory structure. Maybe this is an inelegant example, but I think it illustrates our line of thinking. **Another example:** It is determined that we need a new key/value store to support the needs of a particular project, but it is not clear that the requirements of that project will ever be felt in future projects -- everyone else has a k/v store that works just fine. Clearly architecture will be involved in the decision of which technology to use (and vet whether a new technology is, in fact, _really_ needed), but should the architecture team be charged with building the infrastructure for the new tech? If it is not likely (we all know that means VERY LIKELY) that it will be re-used in different projects, it seems like the answer should be "no", but given the parenthetical above, I'm inclined towards "yes". Should architecture be involved in project- level tech decisions, and to what level should they be involved? **My initial thoughts:**   * The architecture team prototypes the new technologies/systems that it espouses and then transitions to relevant teams.    * By and large, architecture tries to avoid getting involved with project-level problems (it isn't "you should use this new charting package that we think is cool", it is "we are trying to get everyone onto this uniform front-end framework, you need to use it").   * Form an architecture committee that includes engineers and business leaders to make sure engineers are part of the decision making process.    * Architecture must stay tightly linked to business needs and goals without stepping on Product's toes. A core responsibility of architecture is to inform the business of un(der)utilized tech that offers potential upside.   * Architecture should ultimately make the lives of engineers better. Our main goal should be to solve problems once, so that they don't get solved many times, which means that engineers will have more time to work on 'the fun stuff'. Sorry to be so long winded. I'd love any feedback, especially from those who have worked at organizations with impactful and effective architecture teams.


Tasks incorrectly categorized with online text classifiers

**Context: Finding company to do the job** The use case of an application I want to write is that a user will describe a task to be performed by some company, e.g., > I want to move 10 boxes (30x40x50cm) of books and clothes from London to > Bristol next week. How much would that cost? and the application will find candidate companies that could do the task. In this case it would need to categorize the task as for _removal/transportation_ companies. **Problem: incorrect categorization** I tried a number of online services for text categorization but results are discouraging. uClassify classified my text as "Home", "Games", and "Arts"; Textimate.me \--- as "Science & Environment"; Textwise returned "Business/Consumer_Goods", "Services/Clothing", and "Arts/Design/Fashion". The possible reasons for incorrect categorization:   * task description is very short and there is no evident characteristics in the text to differentiate what is more important for the user: boxes, clothes or maybe moving them,   * classifiers trained on other types of texts,   * classifiers trained with respect to a different taxonomy. How would you tackle such a problem? **Potential solution: harvest domain-specific corpus** Since the problem is quite specific to my domain I think about using supervised machine learning algorithm, that would learn with respect to already categorized corpus of such tasks. The corpus can be harvested from sites with tasks already categorized by customers (variation of e-bay). I could also pre-process text before machine learning: extract only verbs ("move") and nouns originating from verbs ("translation"), as they denote what has to be done. This requires quite a lof of work, so I'm curious whether this is the right direction.


Algorithm for perfect non-binary graph layout

I have a complex non-binary graph model.   Each tree node can have multiple children&parents (a node can also have a connection to it's "brother"). A node is represented as square on screen with lines to the connected nodes.   For that I want to use Draw2D and GEF libraries. The problem I am facing is the graph layout. I need a nice algorithm that can reposition the square nodes and the connections with minimum intersections and also make it symmetric as possible.


PHP and performance

I always hear that PHP is for medium and small websites whereas .NET and Java for enterprise applications. My question is about PHP. Why is PHP not a good option for enterprise web applications? Is it because if the web application becomes bigger then PHP will be slower as it is an interpreted language? I know that corporate world will choose .NET or J2EE because of the integration with their products and because of back end services, etc. However, if we just have PHP for building sites and web applications then how can we use it to perform well with big sites? In short, Is there a relationship between the performance of PHP and the size of the website? What are the factors that make PHP not appropriate option for big sites?


Shouldn't the lazy evaluation/execution be syntactically differentiated from eager evaluation/execution in C#?

We know about the deferred execution or lazy evaluation features introduced in C#. But at times, people become confused with them. Because there is no significant difference. You can only know if you know the internals. Shouldn't there be a syntactical difference between them to remove confusion? I think the keyword `let` of F# can be imported to C# to specify the lazy evaluations. Like-               let selectedItems = Items.Where(i => i.Count < 5);      What do you guys think? Update:   In reply to the first answer, I am not proposing that the `let` keyword is to be used in the places where the lazy evaluation is already happening according to the present compiling model. Then it will be of no use actually. I am proposing that the `let` keyword should define the type of execution. To be clear-               var selectedItems = Items.Where(i => i.Count < 5).ToList();      will be executed eagerly by present model. But my proposal is, if we use               let selectedItems = Items.Where(i => i.Count < 5).ToList();      it will be executed later, just when required. Though this is not desirable as it will return different lists of same items each time. The 'thing' defined with `let` keyword can be thought of a constant 'expression' like F#. Update 2:   Linking this SO answer as a proof of people's annoyance with deferred execution- http://stackoverflow.com/questions/215548/whats-the-hardest-or-most- misunderstood-aspect-of-linq/215562#215562


How to do lazy loading in a SOA fashion?

For example, I've got a root object exposed in a SOA service, say `Invoice` (`Invoice` has line items as children). Sometimes, I need to retrieve its detail line items. I'm thinking to make it lazy loading, because it's a traffic overhead to transfer line items every time `Invoice` is required. But in SOA fashion, it seems unlikely. Because all it can expose are `Invoice` POCOs, with contain no logic. Thus I cannot attach my lazy loading logic to `Invoice` to instruct it to load lines items when needed.


Am I competing with a client? is it fair?

I've been working as part of my service company for a client (ClientA) for a year now on building a platform. A few weeks ago another client (clientB) asked me for a quote for building a similar product. I said to clientB that we have been working on a similar product for a client and that we have a mature platform that they may use without all the hassles of doing it from scratch. So I sugested that they partner with my other client to use his platform instead. Unfortunately, the negotiation didn't went well because of many factors:   1. ClientA don't want to have a partnership with ClientB but instead want to keep owing the platform and provide it to clientB as a SAAS service: which I can understand because of the investment already made.   2. The platform doesn't have all the features that ClientB wants, so they need to invest money in developing those. However they are reluctant to invest such money in a platform they don't own. They are planning to sell it to thousands of their own clients, so basing their whole business on a product they don't have control over is not a good move for them. I've done my best to make them agree, but seems like they can't because of each one wanting to have control on the platform. Now clientB wants, as he already wanted at first, my company to build a similar platform and wants my company to partner in this. We'll share any ROI with them. It is a tough decision for me to take because I understand that we can't as a company keep working on those two platforms at the same time. The first version of the platform was obtained from a freelance website under the "work for hire" clause, so the code belongs to clientA. So we cannot reuse any part of that work. As a company manager, I'm in a dilemma because I suspect that clientA will take that move as an unfair one. What are your thoughts on that matter? Edit: There is no signed NDA and anyway would not have signed an NDA with a non competing clause.