问:
Partitioning set into subsets with respect to equality of sum among subsets
Let's say I have {3, 1, 1, 2, 2, 1, 5, 2, 7} set of numbers, I need to split the numbers such that sum of subset1 should be equal to sum of subset2 {3,2,7} {1,1,2,1,5,2}. First we should identify whether we can split number(one way might be dividable by 2 without any remainder) and if we can, we should write our algorithm two create s1 and s2 out of s.

How to proceed with this approach? I read partition problem in wiki and even in some articles but I am not able to get anything. Can someone help me to find the right algorithm and its explanation in simple English?

答:
As @wmeyer noticed, this problem can be stated quite nicely using Constraint Programming. And this simple problem instance is easily solved.

First, here is a high level model written in MiniZinc which is basically this code, without the output section. (See http://www.hakank.org/minizinc/partition_into_subset_of_equal_values.mzn for the full model.)

```
% problem instance and its length
array[1..n] of int: s = [3, 1, 1, 2, 2, 1, 5, 2, 7];
int: n = 9;

% number of subsets
int: num_subsets = 2;

% the decision variables
% to which subset does x[i] belong?
array[1..n] of var 1..num_subsets: x;

solve satisfy; % we want all solutions

% Constraints

% Ensure that the sum of the subsets are the same
constraint
   forall(p in 1..num_subsets-1) (
      sum([s[i]*bool2int(x[i] == p) | i in 1..n]) ==
      sum([s[i]*bool2int(x[i] == p+1) | i in 1..n])
   )
;

% symmetry breaking: assign the first number to subset 1
constraint x[1] = 1;

```

Since the question is tagged "C#", here's model using the C# interface of Google or-tools (with a little different approach than the MiniZinc model): http://www.hakank.org/google_or_tools/partition_into_subsets_of_equal_values.cs

Note:
For the given numbers - and using the symmetry breaking of assigning the first number to subset 1 - there are 19 different partitions (solutions) with 2 subsets, and 42 different partitions when using 3 subsets. For 4 subset there is no solution.

Body:
As @wmeyer noticed, this problem can be stated quite nicely using Constraint Programming. And this simple problem instance is easily solved.

First, here is a high level model written in MiniZinc which is basically this code, without the output section. (See http://www.hakank.org/minizinc/partition_into_subset_of_equal_values.mzn for the full model.)

% problem instance and its length
array[1..n] of int: s = [3, 1, 1, 2, 2, 1, 5, 2, 7];
int: n = 9;

% number of subsets
int: num_subsets = 2;

% the decision variables
% to which subset does x[i] belong?
array[1..n] of var 1..num_subsets: x;

solve satisfy; % we want all solutions

% Constraints

% Ensure that the sum of the subsets are the same
constraint
   forall(p in 1..num_subsets-1) (
      sum([s[i]*bool2int(x[i] == p) | i in 1..n]) ==
      sum([s[i]*bool2int(x[i] == p+1) | i in 1..n])
   )
;

% symmetry breaking: assign the first number to subset 1
constraint x[1] = 1;

Since the question is tagged "C#", here's model using the C# interface of Google or-tools (with a little different approach than the MiniZinc model): http://www.hakank.org/google_or_tools/partition_into_subsets_of_equal_values.cs

Note:
For the given numbers - and using the symmetry breaking of assigning the first number to subset 1 - there are 19 different partitions (solutions) with 2 subsets, and 42 different partitions when using 3 subsets. For 4 subset there is no solution.


问:
HTML, JS, CSS Engines
I am just messing around, trying to figure out how stuff works and right now I have a couple questions about HTML, JS and CSS engines.

I know there are two major JavaScript engines out there - V8 and JavaScriptCore (WebKit's JS engine as far as I know). Is that correct? And what are the main HTML + CSS renderers out there? Let's say I want to build a web browser using V8 (I saw it has some documentation and stuff + I like the way it works), what are the best options for me?

Partially another question. Is there any bare browser that uses V8 and runs on Ubuntu at least?

P.S. I am a Ubuntu user and prefer C++.

答:
JS engines [1, 2]:

v8

JavaScriptCore/SquirrelFish

SpiderMonkey (Mozilla, C++)

Rhino (Mozilla, Java)

Tamarin (Flash)

Chakra (IE9; not open source)

Rendering Engines:

Webkit

Gecko (Mozilla)

Presto (Opera, not open source, not usable standalone)

Trident (IE9)

A quite simple option would be to use Webkit as a rendering engine as it quite
widely used in many different projects. Chrome/chromium is using v8 and runs on Ubuntu.

[1] http://en.wikipedia.org/wiki/JavaScript_engine

[2] http://en.wikipedia.org/wiki/List_of_ECMAScript_engines

ContentLicense: CC BY-SA 3.0

Title: HTML, JS, CSS Engines


问:
Moving dozens of existing standalone retail sites to one central inventory database: what should I know going in?
This will be the first project of this scale that I have attempted, and the first time I have run a website at all (much less dozens) using an off-site database. In particular, I'd like to know:

what sort of optimizations I should read up on to make this run as smoothly as possible?

any pitfalls/gotchas wiser, more experienced folk are aware of I should be on the lookout for, and

what damage-control and preventative measures I should take against the nightmare scenario of the main server (hosting the database) having an outage, grinding over 100 websites to a halt (because they have no access to the product data).

答:
You want the DB schema to be mostly normalized and avoid pessimizations like the n+1 query problem or multiple redundant queries during a single operation. And that will be hard enough to do.

It would probably be better to have an app server layer with a well-defined API on top of the DB rather than having every site access the DB directly. And you definitely need automated tests both for performance and functionality right from the beginning.

Redundancy, of course. If both the app server layer and the DB are clustered, single-server outages won't be a problem and it will help performance as well. Clustered DBs tend to be pretty hard to do and expensive, but this doesn't sound like a project with a tight budget. Make sure to host in a facility that has redundant power supplies and network connections. If outages must be prevented at any cost, consider redundant locations.


问:
Sorting Algorithm : output
I faced this problem on a website and I quite can't understand the output, please help me understand it :-

Bogosort, is a dumb algorithm which shuffles the sequence randomly until it is sorted. But here we have tweaked it a little, so that if after the last shuffle several first elements end up in the right places we will fix them and don't shuffle those elements furthermore. We will do the same for the last elements if they are in the right places. For example, if the initial sequence is (3, 5, 1, 6, 4, 2) and after one shuffle we get (1, 2, 5, 4, 3, 6) we will keep 1, 2 and 6 and proceed with sorting (5, 4, 3) using the same algorithm. Calculate the expected amount of shuffles for the improved algorithm to sort the sequence of the first n natural numbers given that no elements are in the right places initially.

Input:

```<code>2
6
10
</code>```

Output:

```<code>2
1826/189
877318/35343
</code>```

For each test case output the expected amount of shuffles needed for the improved algorithm to sort the sequence of first n natural numbers in the form of irreducible fractions. I just can't understand the output.

答:
You're working with a stochastic algorithm, the requested output is the expected value E[X] of the number of shuffles X needed to sort the vector (which is random at any given try).

Given an input vector of size N with no numbers in their place (they don't give you the vector because it can be shown that E[X] is the same for all vectors of N numbers with this property), which can be "Bogosorted" in k different ways, each way with Si shuffles and with the probability of appearance Pi, then E[X] = sum(Pi * Si)/sum(Pi) where the sum is taken over all possible ways the vector can be sorted this way (obviously, sum(Pi) = 1 so it's actually E[X] = sum(Pi * Si)).

Bring the E[X] fraction down to irreducible, and there's your output.

Title: Sorting Algorithm : output


问:
Go/Obj-C style interfaces with ability to extend compiled objects after initial release
I have a conceptual model for an object system which involves combining Go/Obj-C interfaces/protocols with being able to add virtual methods from any unit, not just the one which defines a class. The idea of this is to allow Ruby-ish open classes so you can take a minimalist approach to library development, and attach on small pieces of functionality as is actually needed by the whole program.

Implementation of this involves a table of methods marked virtual in an RTTI table, which system functions are allowed to add to during module initialization. Upon typecasting an object to an interface, a Go-style lookup is done to create a vtable for that particular mapping and pass it off so you can have comparable performance to C/C++. In this case, methods may be added /afterwards/ which were not previously known and these new methods allow newer interfaces to be satisfied; while I like this idea because it seems like it would be very flexible (disregarding the potential for spaghetti code, which can happen with just about any model you use regardless).

By wrapping the system calls for binding methods up in a set of clean C-compatible calls, one would also be able to integrate code with shared libraries and retain a decent amount of performance (Go does not do shared linking, and Objective-C does a dynamic lookup on each call.)

Is there a valid use-case for this model that would make it worth the extra background plumbing? As much as this Dylan-style extensibility would be nice to have access to, I can't quite bring myself to a use case that would justify the overhead other than "it could make some kinds of code more extensible in future scenarios."

答:
The most important use case that I can think of is making two independent libraries/modules work together with minimal glue.

This is quite common in the Haskell world (Haskell allows making a type (roughly equivalent to a class in traditional OOP) a member of a typeclass (roughly equivalent to an interface) independent from the definition of both the type and the typeclass: you can take a type T from module A, a typeclass C from module B, and declare T to be an instance of C in module X. For example, let's assume you have a library that implements a document model type DocumentNode, and another library that provides functions to traverse trees, and exposes a typeclass TreeTraversable to define what objects it can consume. Neither library knows about the other, but you can provide an instance declaration that maps methods from the typeclass (e.g. isLeaf, childNodes) to functions on the type. As a result, the libraries do not need to depend on each other: only the module that glues them together depends on both. This mechanism is very helpul in keeping dependencies between modules and libraries low, and it makes for great extensibility at the module level. The mechanism isn't even restricted to user types: you can make any built-in type (e.g. Int) a member of any typeclass you want, and you can make any type implement any built-in typeclass (such as Ord, which makes a type sortable).

Another example would be mix-ins, which allow the programmer to dynamically inject methods into objects; this is pretty common in many dynamic languages, including Python and Javascript. Unlike the Haskell example, these languages don't provide any type safety though - a class is basically just a bag of properties, and a method is just a property that happens to be a function. The advantage is that this is relatively easy to implement, and gives the programmer full flexibility (any method can be glued onto any object), but obviously, you won't get the benefits of a static type system (but then, if you're using a dynamic language, you have already decided to let go of static type checking).


问:
Patterns for Handling Changing Property Sets in C++
I have a bunch "Property Sets" (which are simple structs containing POD members). I'd like to modify these property sets (eg: add a new member) at run time so that the definition of the property sets can be externalized and the code itself can be re-used with multiple versions/types of property sets with minimal/no changes.

For example, a property set could look like this:

```<code>struct PropSetA
{
    bool activeFlag;
    int processingCount;
    /* snip few other such fields*/
};
</code>```

But instead of setting its definition in stone at compile time, I'd like to create it dynamically at run time. Something like:

```<code>class PropSet propSetA;
propSetA("activeFlag",true);  //overloading the function call operator
propSetA("processingCount",0);
</code>```

And the code dependent on the property sets (possibly in some other library) will use the data like so:

```<code> bool actvFlag = propSet["activeFlag"];
 if(actvFlag  == true)
 {
   //Do Stuff
 }
</code>```

The current implementation behind all of this is as follows:

```<code>class PropValue
{
 public:
    // Variant like class for holding multiple data-types
    // overloaded Conversion operator. Eg:
    operator bool()
    {
      return (baseType == BOOLEAN) ? this->ToBoolean() : false;
    }
    // And a method to create PropValues various base datatypes
    static FromBool(bool baseValue);
};

class PropSet
{

 public:
  // overloaded[] operator for adding properties
  void operator()(std::string propName, bool propVal)
  {
    propMap.insert(std::make_pair(propName, PropVal::FromBool(propVal)));
  }

 protected:
   // the property map
   std::map<std::string, PropValue> propMap;
};
</code>```

This problem at hand is similar to this question on SO and the current approach (described above) is based on this answer. But as noted over at SO this is more of a hack than a proper solution. The fundamental issues that I have with this approach are as follows:

Extending this for supporting new types will require significant code change. At the bare minimum overloaded operators need to be extended to support the new type.

Supporting complex properties (eg: struct containing struct) is tricky.

Supporting a reference mechanism (needed for an optimization of not duplicating identical property sets) is tricky. This also applies to supporting pointers and multi-dimensional arrays in general.

Are there any known patterns for dealing with this scenario? Essentially, I'm looking for the equivalent of the visitor pattern, but for extending class properties rather than methods.

Edit: Modified problem statement for clarity and added some more code from current implementation.

答: You need to get a real dynamic language, such as Lua or Python, to handle this kind of workload.</p>


问:
What is the difference between class level attributes, Class constants and singleton methods?
What the difference given they all exist 'once per class'.

When should I use one over another, i.e. for what purpose?

I use Ruby.

答:
The differences are well-defined, and you can look them up easily. Here's a quick (language-agnostic) summary:

Class constants are constant, you cannot change them at run-time at all. They are made part of the class because they belong to it, conceptually speaking, and also often (but not always) to limit their scope and/or avoid naming clashes.

Class-level attributes (static fields) are just global variabls in disguise - they are scoped inside the class, but other than that, they are global. In contrast with class constants, they are read/write, so their value can change at run-time.

Singleton methods are, in fact, regular methods, but the instance they belong to (the singleton) has been enforced to be the only one of its type within a particular context (what that context is differs between languages, platforms, and implementations).

As to which one to choose: My advice is to avoid class-level attributes and singletons as much as possible. Both are globals in disguise, and although there might be appropriate uses for them, most real-world applications are in fact inappropriate, introduced for "convenience" at one point, and a source of major headaches later on. In most situations, a better alternative is to create a regular type to describe the state that you would otherwise put in a class attribute or singleton, and just pass it around. This way, you can control exactly who gets to modify the state (and who doesn't), and should you ever decide that you do need more than one instance, you can just create one. The hassle of carrying the state object around is minimal in comparison.

Class constants, by contrast, are fine - they are constants, so there is no risk of unexpected changes. They are just values that you can access from anywhere, and there is nothing wrong with that (as long as the code that uses them doesn't break if you change the value).


问:
CamelCase issue (PList or Plist)
Ok, I understand what CamelCase is. This question is relating to how to CamelCase the shortened version of Property List (PList). I am asking this because I am working on a PList parser in C# and knowing how everything in .NET is CamelCase, I am wondering, should it be PList or Plist (also why)?

答:
The rules for Pascal Casing in .NET are about as follows:

acronyms and abbreviations of one or two letters are all-uppercase (XPath, ACCurrent, VWBeetle)

full words and abbreviations of three or more letters have one uppercase letter and the rest lowercase (XmlDocument, AspLover, BmwDriver)

note that two-letter words that are not abbreviations are first-uppercase, not all-uppercase: StopAndGo, not StopAndGO

also note that the original capitalization of a word (even a brand name) is never honored unless it coincides with the above rules: IPhone, not iPhone, Asp, not ASP, DotNet, not DotNET.

Since the 'P' is short for 'property', and 'list' is a full word, the correct capitalization is PList. Plist would suggest that 'plist' were one word, which it isn't. (And the reader knows it has to be P-list, not PL-ist, because if 'ist' were a full word, it would have to be PLIst.)

Title: CamelCase issue (PList or Plist)


问:
How to store multiple requirements with OR and AND?
Well I'm working on a personal project that needs to check if a user has met certain requirements, and they come in a form of

Requirement: [c1 OR c2] AND [d1 OR d2]

Requirement: [c1 AND c2] OR [d1 AND d2]

Requirement: c1 AND any dn(n can be any integer)

I'm just not sure how to store these sorts of requirements, I'm thinking of using another object to hold c1,c2,d1,d2....dn and OR, but that seems like a roundabout way of doing things. Is there a better method?

答:
Think of [c1 OR c2] AND [d1 OR d2] as a single requirement. Consider c1, c2, d1, d2 as requirements, say sub requirements or atomic requirements. Now they all have one thing in common. They can be checked if they are met. So let's introduce an interface for that:

```<code>public interface Requirement {
    public boolean isMet();
}
</code>```

Now atomic requirements can be implemented like

```<code>public class AtomicRequirement implements Requirement {
    private final boolean met;

    public AtomicRequirement(boolean isMet) {
        this.met = isMet;
    }

    public boolean isMet() {
        return true;
    }
}
</code>```

You can add compound requirements and build upon the Requirement interface.

```<code>public class AndRequirement implements Requirement {
    private final Requirement r1, r2;

    public AndRequirement(Requirement r1, Requirement r2) {
        this.r1 = r1;
        this.r2 = r2;
    }

    public boolean isMet() {
        return r1.isMet() && r2.isMet();
    }
}
</code>```

Same goes for OR. You can do it with more complex combinators

```<code>public class AnyOfTheseRequirement implements Requirement {
    private final List<Requirement> anyOfThese;

    public AnyOfTheseRequirement(List<Requirement> anyOfThese) {
        this.anyOfThese = anyOfThese;
    }

    public boolean isMet() {
        for (Requirement r : anyofThese) {
            if (r.isMet()) return true;
        }
        return false;
    }

}
</code>```

and of course

```<code>public class MakseeRequirement implements Requirement {
    private final AndRequirement r;

    public MakseeRequirement(Requirement c1, List<Requirement> dns) {
        AnyOfTheseRequirement d = new AnyOfTheseRequirement(dns);
        this.r = new AndRequirement(c1, d);
    }

    public boolean isMet() {
        return r.isMet();
    }

}
</code>```

This approach is quite extendable but you can trim it down to the three actual types of requirements you got.

Body:
Think of [c1 OR c2] AND [d1 OR d2] as a single requirement. Consider c1, c2, d1, d2 as requirements, say sub requirements or atomic requirements. Now they all have one thing in common. They can be checked if they are met. So let's introduce an interface for that:

public interface Requirement {
    public boolean isMet();
}

Now atomic requirements can be implemented like

public class AtomicRequirement implements Requirement {
    private final boolean met;

    public AtomicRequirement(boolean isMet) {
        this.met = isMet;
    }

    public boolean isMet() {
        return true;
    }
}

You can add compound requirements and build upon the Requirement interface.

public class AndRequirement implements Requirement {
    private final Requirement r1, r2;

    public AndRequirement(Requirement r1, Requirement r2) {
        this.r1 = r1;
        this.r2 = r2;
    }

    public boolean isMet() {
        return r1.isMet() && r2.isMet();
    }
}

Same goes for OR. You can do it with more complex combinators

public class AnyOfTheseRequirement implements Requirement {
    private final List<Requirement> anyOfThese;

    public AnyOfTheseRequirement(List<Requirement> anyOfThese) {
        this.anyOfThese = anyOfThese;
    }

    public boolean isMet() {
        for (Requirement r : anyofThese) {
            if (r.isMet()) return true;
        }
        return false;
    }

}

and of course

public class MakseeRequirement implements Requirement {
    private final AndRequirement r;

    public MakseeRequirement(Requirement c1, List<Requirement> dns) {
        AnyOfTheseRequirement d = new AnyOfTheseRequirement(dns);
        this.r = new AndRequirement(c1, d);
    }

    public boolean isMet() {
        return r.isMet();
    }

}

This approach is quite extendable but you can trim it down to the three actual types of requirements you got.


问:
Factors to be Considered for Software Risk Management
What are the risk factors that we need to consider while planning for a software project.</p>

答:
I would add to @Graham's list:

Are some of the requirements out of your control (eg the laws about calculating sales tax) and might they change?

Are you using a tool for the first time and how confident are you the tool will work for you? (It might be brand new, eg Azure, or just new to your team)

Are you relying on a general acceptance by your users of another product (eg writing an iPhone app means you expect your users to have iPhones, writing a BlackBerry app means you expect your users to have BlackBerries etc.)

Can you restore/recreate any lost or wrongly-changed work (not just source control but version control for documents, emails from clients, etc)

Do you have tools and process that enable you to understand progress, lack of progress, and regressions? Does management understand the milestones (I've had projects where at 10% complete the management saw UI prototypes and believed the work was "almost done" then pressured to hurry hurry hurry from then on.)

Do you have testing (automated or not) to demonstrate that a particular set of changes has not broken some other part of the application? Without such tests, could you ever make significant changes such as porting to another language or platform?

ContentLicense: CC BY-SA 2.5


答: You know something's wrong when you worry over such trivialities. Choose whichever one suits you best and get back to worrying over making the code work.</p>

Title: CamelCase issue (PList or Plist)

Body: Ok, I understand what CamelCase is. This question is relating to how to CamelCase the shortened version of Property List (PList). I am asking this because I am working on a PList parser in C# and knowing how everything in .NET is CamelCase, I am wondering, should it be PList or Plist (also why)?


问:
How many juniors should a senior mentor?
Our shop's size increases dynamically, so we are planning to hire a few new junior developers but we would not like to overwhelm the seniors with too much mentoring and training. How many (usually fresh out of college) junior developers could (and should) a senior developer mentor while the senior is still being able to do his or her tasks effectively?</p>

答:
Mentoring is less formal than managing. Mentors are not directly involved in the hiring, firing, reviewing and discipline. The environment will be a major factor.
Here are the factors to consider:

quality of sr. and jr. devs

how well the company is run/treats programmers (this will compound the other problems)

sr. dev current work load

management's expectations on how fast the jr. devs need to become productive

other training resources (instructor aided courses, reference materials, certification requirements)

hiring to fit the team. Many times on this site people have mentioned the importance of the team needed to get a long and be able to function together. Someone with a higher skill level may need more mentoring if they don't fit in.

Mentoring usually involves some level of bonding and I just don't think most people can build any type of interpersonal relationship with more than 3-5 people in a given setting.


问:
Why rails use yaml to config database instead of plain ruby code?
Most of configuration files in ruby such as Gemfile, gemspec, are just ruby code itself. Why database configuration file in rails is the exception?</p>

答:
One bonus is that other languages can read YAML, while you can't read a ruby config file in Python (easily).  </p>

<p>That said I'd use ruby for complex config setups </p>

Body:
One bonus is that other languages can read YAML, while you can't read a ruby config file in Python (easily).

That said I'd use ruby for complex config setups


问:
I'm doing 90% maintenance and 10% development, is this normal?
I have just recently started my career as a web developer for a medium sized company. As soon as I started I got the task of expanding an existing application (badly coded, developed by multiple programmers over the years, handles the same tasks in different ways, zero structure).

So after I had successfully extended this application with the requested functionality, they gave me the task to fully maintain the application. This was of course not a problem, or so I thought. But then I got to hear I wasn't allowed to improve the existing code and to only focus on bug fixes when a bug gets reported.

From then on I have had three more projects just like the above, that I now also have to maintain. And I got four projects where I was allowed to create the application from scratch, and I have to maintain those as well.

At this moment I'm slightly beginning to get crazy from the daily mails of users (read managers) for each application I have to maintain. They expect me to handle these mails directly while also working on two other new projects (and there are already five more projects lined up after those). The sad thing is I have yet to receive a bug report on anything that I have coded myself. For that I have only received the occasional let's-do-things-180-degrees-different change requests.

Anyway, is this normal? In my opinion I'm doing the work equivalent of a whole team of developers.

Was I an idiot when I initially expected things to be different?

I guess this post has turned into a big rant, but please tell me that this is not the same for every developer.

P.S. My salary is almost equal if not lower than that of a cashier at a supermarket.

答:
The only way to break this chain is to develop new infrastructures that are designed for flexibility and are full unit+integration tested.

If you manage to sell this to the management (sign other developers and managers on to the concept in 1:1 meetings), then you can slowly reach a state, where most of the applications' code is in the infrastructure and it is easy to expand and maintain, whereas the actual applications are light weighted and can be written pretty quickly.

The development of the infrastructure may enable at first replacing parts of existing applications and after a while (may take a few years) replacing entire applications.

In the long run it can reduce development time of new applications and maintenance time of future existing applications drastically.

The new development will require at least 80% dedication (preferably more) with a team of  more that one developer (a few minds are better than one). All the developers will need to be able to think creatively and to break existing preconceptions.

Try defining and high-level designing such a new infrastructure, then present the definition to your peers and to management.

As of your working conditions, ask to lead a new infrastructure team that deals with these issues (based on your definitions and design) and bring on new developers to maintain the old stuff while you assist them if necessary (up to 10-20% of the time).
If the management agrees to the idea, you can ask to renegotiate your terms. Be prepare to find another job if they refuse. (Remember, your job requires skills, knowledge and experience, you are not as easy to replace as they are paying you to believe.)


问:
Is 100% code coverage a pipe dream?
Is it feasible to expect 100% code coverage in heavy jquery/backbonejs web applications?  Is it reasonable to fail a sprint due to 100% coverage not being met when actual code coverage hovers around 92%-95% in javascript/jquery? </p>

答:
92% is fine.  I feel that the real questions are:

Is 92% the 'new' norm now?  If the next sprint has 88% testing, will that be ok?  This is frequently the start of test suites being abandoned.

How important is it that the software work and not have bugs.  You have tests for these reasons, not "for the sake of testing"

Is there a plan to go back and fill in the missing tests?

Why are you testing?  It seems like the focus is % of line covered not functionality

Title: Is 100% code coverage a pipe dream?


问:
Using PDO for Data Management
This question is more a design oriented question than a code specific question. I am new to PHP and I am planning to use PDO as a data access layer. Say for instance I have a class called CITY. Now if I need to create an instance of this class, what is the best technique.

Should have a singleton DB access class which is used to write and read data from the db layer.

OR should I delegate it to the individual class object. For example if I invoke city.save() (city is a class), then the city class will handle the saving of that city object's data into the database.

Excuse my ignorance but i have a java background and therefore trying to understand what is the best design principle for data management when using php.

答:
I'm afraid there is no definitive answer, it depends on the project at hand.

I've been pondering the same question as yours for my own project. In search for an answer I've been looking at some PHP books and according to George Schlossnagle in 'Advanced PHP Programming' there are three possible options:

1) Using the Active Record Pattern: the class takes care of saving it's data into the database. Very useful if the class has a simple correspondence with individual table rows, but harder to use if your class depends on data from multiple tables

2) Using the Mapper pattern: One class (the Mapper) deals with the database and the other class for example the User class deals only with the User object itself. Basically the Mapper maps the User class to the database structure.

3) A combination of both, which Schlossnagle calls 'Integrated Mapper'

Personally I would have one class dealing with the mere basics of PDO: connecting with the database and performing a query. Basically making sure you only have to use your DB credentials in one place. All object specific queries I would deal with them in the object's class, since the data of the object is in my view strongly linked with the database structure, so if the class structure changes the database structure probably needs to accommodate those changes as well. And vice versa. So I'm leaning towards using a combination of both Active Record and Mapper pattern.

I hope this helps you in formulating your own solution.

OwnerDisplayName: edorahg

Title: Using PDO for Data Management


答: No, it's not possible and it never will be. If it were possible all of mathematics would fall into finitism. For example, how would you test a function that took two 64 bit integers and multiplied them? This has always been my problem with testing versus proving a program correct. For anything but the most trivial programs, testing is basically useless as it only covers a small number of cases. It's like checking a 1,000 numbers and saying you've proved the Goldbach conjecture.</p>

Title: Is 100% code coverage a pipe dream?

Body: Is it feasible to expect 100% code coverage in heavy jquery/backbonejs web applications?  Is it reasonable to fail a sprint due to 100% coverage not being met when actual code coverage hovers around 92%-95% in javascript/jquery? </p>


答: As somebody commented, this problem is isomorphic to “subset sum”, and so it’s NP-complete. Basically, the naive solutions to this problem are the best solutions and they’re very, very bad. :) I only say this so you don’t look for a more “optimized” version or something.</p>

Title: Partitioning set into subsets with respect to equality of sum among subsets

Body:
Let's say I have {3, 1, 1, 2, 2, 1, 5, 2, 7} set of numbers, I need to split the numbers such that sum of subset1 should be equal to sum of subset2 {3,2,7} {1,1,2,1,5,2}. First we should identify whether we can split number(one way might be dividable by 2 without any remainder) and if we can, we should write our algorithm two create s1 and s2 out of s.

How to proceed with this approach? I read partition problem in wiki and even in some articles but I am not able to get anything. Can someone help me to find the right algorithm and its explanation in simple English?


问:
Programming Language, Turing Completeness and Turing Machine
A programming language is said to be Turing Completeness if it can successfully simulate a universal TM. Let's take functional programming language for example.

In functional programming, function has highest priority over anything. You can pass functions around like any primitives or objects. This is called first class function.

In functional programming, your function does not produce side effect i.e. output strings onto screen, change the state of variables outside of its scope. Each function has a copy of its own objects if the objects are passed from the outside, and the copied objects are returned once the function finishes its job. Each function written purely in functional style is completely independent to anything outside of it. Thus, the complexity of the overall system is reduced. This is referred as referential transparency.

In functional programming, each function can have its local variables kept its values even after the function exits. This is done by the garbage collector. The value can be reused the next time the function is called again. This is called memoization.

A function usually should solve only one thing. It should model only one algorithm to answer a problem. Do you think that a function in a functional language with the above properties simulates a Turing Machine?

Functions (= algorithms = Turing Machines) are able to be passed around as input and returned as output. TM also accepts and simulate other TMs

Memoization models the set of states of a Turing Machine. The memorized variables can be used to determine states of a TM (i.e. which lines to execute, what behavior should it take in a give state ...). Also, you can use memoization to simulate your internal tape storage. In language like C/C++, when a function exits, you lose all of its internal data (unless you store it elsewhere outside of its scope).

The set of symbols are the set of all strings in a programming language, which is the higher level and human-readable version of machine code (opcode)

Start state is the beginning of the function. However, with memoization, start state can be determined by memoization or if you want, switch/if-else statement in imperative programming language. But then, you can't

Final accepting state when the function returns a value, or rejects if an exception happens. Thus, the function (= algorithm = TM) is decidable. Otherwise, it's undecidable. I'm not sure about this. What do you think?

Is my thinking true on all of this?

The reason I bring function in functional programming because I think it's closer to the idea of TM.

What experience with other programming languages do you have which make you feel the idea of TM and the ideas of Computer Science in general? Can you specify how you think?

答:
What experience with other programming languages do you have which make you feel the idea of TM and the ideas of Computer Science in general? Can you specify how you think?

There is the structured program theorem, which ties pretty much any procedural programming language directly to Turing Machines. As you hinted, functional languages are tied to TMs via lambda calculus. And there rather few languages that are Turing-complete and can't be trivially translated into either procedural or functional programming (hi there, Prolog).

For me, the main implication is that independently of technology and programming language, there are very few problems that can't be solved. This makes me hate people who say that something is impossible :)


问:
Best approach to learning web programming
I come from a scientific and embedded programming background, and I have had minimal experience with web programming.  What would be the best approach to take to get up to speed with web programming?  Tools and framework suggestions?

One approach would be to dive into learning a framework, such as Rails. I started doing this with rails tutorial, but I find that the framework abstracts so many important concepts that I should be learning.

To sum up, experienced programmer wants to learn web-app programming.

答:
I agree with Mild-Fuzz with going deep.

From the start you're going to be working with at least 4 different interacting languages: (Html, Css, JavaScript and at least 1 server side language. Likely you're going to have SQL in there as well, possibly some XML. Then you'll likely also be using a framework or two (for JavaScript and your server-side code).

You will have to start with the obvious basics in each. Ie make a simple html page, style it up with css, make it dynamic with some JS, a few basic CRUD operations to get into the server-side stuff. But after you have a basic knowledge of these you need to try and focus developing them roughly concurrently. You'll often find that to improve one you'll need to improve the others as you go, make sure to embrace this rather than fight it by trying to learn one well before diving into the others. Taking the all at once approach will also help you be more flexible when you move on to bigger things.

You will find that most of your problems and the areas with the most value is on the boundaries between each of these, an AJAX call to update a widget for instance will involve all of JS, CSS, HTML DOM, server-side and probably SQL. Passing data through each layer is you're biggest breaking point, if you are really good at one area in particular you might focus there to fix your bug and have a more convoluted solution than if you had looked at your server-side code.


答:
The reason I bring function in functional programming because I think it's closer to the idea of TM.

I'm not sure that I agree with that. It's very easy to overthink the issue and try to apply modern computer science concepts to what is, after all, a foundation. Turing described a stateful, imperative machine. I've always thought that Church's approach was more the genesis of FP.

If you want to get a "feel" for Turing machines, I suggest that you reflect upon complex mechanical automata and, in software, work with state machines.

Title: Programming Language, Turing Completeness and Turing Machine

Body:
A programming language is said to be Turing Completeness if it can successfully simulate a universal TM. Let's take functional programming language for example.

In functional programming, function has highest priority over anything. You can pass functions around like any primitives or objects. This is called first class function.

In functional programming, your function does not produce side effect i.e. output strings onto screen, change the state of variables outside of its scope. Each function has a copy of its own objects if the objects are passed from the outside, and the copied objects are returned once the function finishes its job. Each function written purely in functional style is completely independent to anything outside of it. Thus, the complexity of the overall system is reduced. This is referred as referential transparency.

In functional programming, each function can have its local variables kept its values even after the function exits. This is done by the garbage collector. The value can be reused the next time the function is called again. This is called memoization.

A function usually should solve only one thing. It should model only one algorithm to answer a problem. Do you think that a function in a functional language with the above properties simulates a Turing Machine?

Functions (= algorithms = Turing Machines) are able to be passed around as input and returned as output. TM also accepts and simulate other TMs

Memoization models the set of states of a Turing Machine. The memorized variables can be used to determine states of a TM (i.e. which lines to execute, what behavior should it take in a give state ...). Also, you can use memoization to simulate your internal tape storage. In language like C/C++, when a function exits, you lose all of its internal data (unless you store it elsewhere outside of its scope).

The set of symbols are the set of all strings in a programming language, which is the higher level and human-readable version of machine code (opcode)

Start state is the beginning of the function. However, with memoization, start state can be determined by memoization or if you want, switch/if-else statement in imperative programming language. But then, you can't

Final accepting state when the function returns a value, or rejects if an exception happens. Thus, the function (= algorithm = TM) is decidable. Otherwise, it's undecidable. I'm not sure about this. What do you think?

Is my thinking true on all of this?

The reason I bring function in functional programming because I think it's closer to the idea of TM.

What experience with other programming languages do you have which make you feel the idea of TM and the ideas of Computer Science in general? Can you specify how you think?


问:
Is WCF suitable for writing an application which is shared among applications?
I have developed and deployed few ASP.NET applications. Sometimes I want to stop the users from either inserting or updating a record when:

Maintenance is going on.

Stop operations due to payment delay.

In one of my recent application I have implemented this feature to first check the database operations for locked status. If any of the above condition fulfils, database operations like insert and update are not carried out.

I now need this feature in all the old applications and the future applications I build. I want to know whether WCF is suitable in this scenario as I want to share methods or an independent locking application among various other applications.

Is WCF appropriate for this type of scenario?

答:
I should begin by saying that WCF is the goto solution. What you mentioned above fits very well in the SOA (Service Oriented Architecture) definition, and WCF deals very well with SOA.

Implementing a single locking service application, which can then be then integrated in all your components would be ideal because:

When you update your locking and payment checking methods, you do it one place only. So it gives you maintainability.

You implement the code only once, which gives you reusability.

In the central app you can always add new services, with new logic which can be coupled or decoupled of your existing model, from existing services. So you have scalability.

It also gives you coolness, for all the reasons I mentioned above.

If anything else, then please ask.


答:
You could insert a file on your webserver and protect it by placing it in a safe folder and make it only editable by admin user. In that file you could specify a string to indicate the system status. Accessing this file can be performed in any way you like. The reason for choosing a file is to be able to access it even if the database is down. This is a a very simple solution that serves the objective you described.

Eidt: Also, instead of a separate file, you could use a configuration item to server the same purpose.

Title: Is WCF suitable for writing an application which is shared among applications?

Body:
I have developed and deployed few ASP.NET applications. Sometimes I want to stop the users from either inserting or updating a record when:

Maintenance is going on.

Stop operations due to payment delay.

In one of my recent application I have implemented this feature to first check the database operations for locked status. If any of the above condition fulfils, database operations like insert and update are not carried out.

I now need this feature in all the old applications and the future applications I build. I want to know whether WCF is suitable in this scenario as I want to share methods or an independent locking application among various other applications.

Is WCF appropriate for this type of scenario?


问:
I've failed at PHP several times. Is Ruby the Cure?
Extremely, extremely subjective question here, but its something I've been struggling with for quite a while. I've seriously tried to become a reasonable PHP coder for the past several years. But I've really failed every time. I hate to describe myself as a beginner, b/c I've been designing websites (using WordPress, Drupal, etc) for years, but still I just can't seem get better at programming.

Could it be that I have some kind of allergy to PHP? I went through Chris Pine's awesome into to Ruby about a week ago (for about the fifth time), and though it did all all seem much clearer to me than PHP, I wondered if I was just switching languages to find an easy way out?

The things I struggle with in PHP all seem elementary—when to use a function, how to return database queries in foreach/while statements, when to turn those queries into reusable functions, adding arguments to functions, etc, etc. And all the OOP stuff that I keep seeing these days just files over my head.

I guess my question(s) are:  Am I going about learning how to program in the wrong way?  Do I have some aversion to PHP that's preventing me from catch on? If I keep pushing at Ruby/Rails, will it just eventually 'click'.  Or, the one I fear, am I just unlikely to ever be a programmer?

答:
I like the answer you accepted and also @back2dos's answer.

IMHO, I believe you would do quite well to take a community college or University class on Intro to C/C++ Programming. I was a lab assistant for that course a few years ago and I feel C translates well to php. The structure is about the same and I actually like php's flexibility and syntax more.

To go on a little about my recommendation, try to avoid classes that go on too much about theory or computer science. You need a nuts and bolts "get stuff done" class like that one.


问:
Reporting in Visual Studio 2010 Express
I want to download Visual Studio 2010 Express Edition to learn all that is new in it. I find it insufficient as there is no Crystal Reports integration in it. Apart from that I want to learn other enterprise features that are bundled with the Professional Edition.

If I download the VS 2010 Professional Edition, it is just limited to 90 days. Is there any other alternative for learners?

Also, is there any FREE alternative for reporting in Express Edition.

答:
You can't do reporting with Express. There isn't some trick to turn the free product into the paid product, and there isn't some obligation on Microsoft that they should have all the same features in the free and paid product. As you are saying, there's great value in those reporting features, and that's why people buy the versions that cost money. Just because Microsoft says you're allowed to sell the products you make with Express, they're not saying you can have any and all features in Express that you might use to make a product you will sell.

That said, you can probably get the versions that cost money for free. If you're writing software you intend to sell, if you make web sites for customers, or if you're a student (high school or college/university) then there are programs from Microsoft that give you free licenses of non-Express editions.

See Can a developer get a discount for Microsoft products? which has several answers that have nothing to do with "volume discounts" because they actually explain how to get the full featured product for free.

Title: Reporting in Visual Studio 2010 Express


答:
If you wanted a locking solution, a web service is not necessarily the way to go - the overhead involved is very great. So just to check "can I do some writes now" will require a lot of calls, and a webservice call is very slow (relatively speaking).

A more optimised solution would be to keep with your database calls, but to move the sql to a stored procedure that can also check the locked status as part of the query. Alternatively, keep the lock check as local as possible, checking whether a file exists is quick (as the OS tends to cache such files if they're accessed often) and easy, especially if you're reading your applications' code from files or writing to logs anyway.


问:
Are there any statistics that show the popularity of Git versus SVN?
I'm writing an essay, and would like to have some empiric evidence, perhaps longitudinal data where the popularity of these technologies is compared over a period of some years.

Are there any statistics that show the popularity of Git versus SVN?

答:
Further to my previous answer, there are some websites out there that track demand for skills among employers. These are a useful metric because they show exactly where things are at in corporate/enterprise settings, while disregarding the open source/hobbyist market (which can be pretty fanboyish at the best of times).

One example is http://www.itjobswatch.co.uk/. Their statistics are as follows as of 18 June 2013 as compared with 18 June 2012:

Subversion: 2,844 jobs (down from 3,377 on 18 June 2012)

Git: 2,107 jobs (up from 1,208)

Team Foundation Server: 1,772 jobs (up from 1,593)

Visual SourceSafe: 298 jobs (down from 459)

ClearCase: 197 jobs (down from 389)

Mercurial: 187 jobs (up from 172)

Perforce: 142 jobs (down from 204)

Borland StarTeam: 29 jobs (up from 22)

AccuRev: 5 jobs (down from 27)

Bazaar: 5 jobs (no stats for 2012)

(I wasn't able to find statistics for any other system e.g. CVS, SourceGear Vault etc.)

It appears that demand for Git is doubling approximately every 12-18 months and if present trends continue it will overtake Subversion round about the end of 2013 to become the most widely used source control software in corporate settings. Subversion apparently peaked about a year ago and is now gradually declining.


问:
Structuring database for multi-object "activity" and "following" functionalities
I am working on a web application which operate with different types of objects such as user, profiles, pages etc. All objects have unique object_id.

When objects interact it may produce "activity", such as user posting on the page or profile. Activity may be related to multiple objects through their object_id.

Users may also follow "objects" and they need to be able to see stream of relevant activity.

Could you provide me with some data structure suggestions which would be efficient and scalable? My goal is to show activity limited to the objects which user is following I am not limited by relational databases.

Update

As I'm getting advices on ORM and how index things, I'd like to again, stress my question. According to my current design model the database structure looks like this:

As you can see - it's quite easy to implement database like that. Activity and Follower tables do contain much larger amount of records than the upper level but it's tolerable.

But when it comes for me to create a "timeline" table, it becomes a nightmare. For every user I need to reference all the object activities which he follows. In terms of records it easily gets out of control.

Please suggest me how to change this structure to avoid timeline creation and also be abel to quickly retrieve activity for any given user. Thanks.

答:
You wrote that you are not limited to relational databases. You could consider using a graph database, like neo4j. Graph databases are particularly well-suited for situations like yours where relations are more important than, say, averages and sums.

You can find an introduction here and a working example here.

A more complex, but more efficient structure that you could use is graphity.


答:
Denormalization is going to be your friend here -- have you considered just making a static timeline table that you can SELECT from easily?

I would also strongly consider non-relational data stores here -- they tend to fit this sort of problem well.

Title: Structuring database for multi-object "activity" and "following" functionalities

Body:
I am working on a web application which operate with different types of objects such as user, profiles, pages etc. All objects have unique object_id.

When objects interact it may produce "activity", such as user posting on the page or profile. Activity may be related to multiple objects through their object_id.

Users may also follow "objects" and they need to be able to see stream of relevant activity.

Could you provide me with some data structure suggestions which would be efficient and scalable? My goal is to show activity limited to the objects which user is following I am not limited by relational databases.

Update

As I'm getting advices on ORM and how index things, I'd like to again, stress my question. According to my current design model the database structure looks like this:

As you can see - it's quite easy to implement database like that. Activity and Follower tables do contain much larger amount of records than the upper level but it's tolerable.

But when it comes for me to create a "timeline" table, it becomes a nightmare. For every user I need to reference all the object activities which he follows. In terms of records it easily gets out of control.

Please suggest me how to change this structure to avoid timeline creation and also be abel to quickly retrieve activity for any given user. Thanks.


问:
What operating systems are used in airplanes, and what programming languages are they developed in?
I was wondering if anyone knows what is the operating system used in commercial airplanes (say Boeing or Airbus).

Also, what is the (preferred) real-time programing language? I heard that Ada is used in Boeing, so my question is - why Ada? what are the criteria the Boeing-guys had to choose this language? (I guess Java wouldn't be a great choice if exactly on lift-off the garbage collector wakes up).

答:
Avionics

For aircraft control systems, we don't speak of operating systems but of avionics, integrated avionics or computer airborne systems in general. And they are actually a combination of a multitude of independent or inter-dependent systems, for different functions (flight control, collision avoidance, weather, communications, blackboxes...).

Each controller is usually an independent module (hardware and software) for obvious security and safety reasons: they are critical control and monitoring systems and if one of them were to fail or get damaged, it's a rather big "inconvenience" for the people which are depending on the aircraft. Dependability takes all its meaning when you are in the flying machine. So usually it's

custom built for the purpose of their mission,

built to work independently and interface with other systems,

built to be fault-tolerant to its own failures AND to failures of the other systems it's interfaced to (because you don't want the pilot's sound system taking down the engine controls, for instance).

It's not a big computer running everything. If you think of it from the perspective of a military aircraft rather than a commercial one (though it's similar in this respect, the image might help): if a part gets shot at, you'd rather at least have some other parts be able to keep going (the part controlling the communications and safety systems might be interesting to keep alive...). Hence also the big bunch of buttons you see in jetliners, to keep track of the status of different systems.

They are usually either built as custom components operating their own system, or they are run and scheduled by a micro-kernel (in most cases, with support for real-time capabilities).

It depends across vendors and countries, obviously, but they usually at least need to follow rather strict sets of regulations, design requirements and protocol specifics, which allow for:

the control of their strict-compliance to security and safety standards,

the inter-communication with other systems (much better if that airplane you took off with in Reykjavik can "talk" to that ground-control equipment in Tokyo...)

Standardization Efforts

The DO-178B (revised in 1992) and its successor the DO-178C (revised in 2012) (and a bunch of associated documents) are an example of reference certifications for such compliance levels, and are recognized by the FAA (US), the EASA (EU), and Transport Canada, amongst others. Multiple other organizations are involved in the creation of such documents, like the EUROCAE.

Such airborne systems are usually bespoke software, but the following systems are known to be used in some airplanes:

WindRiver's VxWorks (see Aerospace & Defense uses),

QNX (actually not sure if QNX is used in airplanes, but it's used in ground control systems)

To give you a vague idea of elements built into an avionics system, this list of avionics acronyms points to some of them (with some overlap).

Notable Languages used in Commercial and Military Avionics

Apart from the usual suspects we know in the "mainstream" programming world, you'll come up some often referenced names like Ada, and some less known languages like the (dated and now "retired" since 2010) JOVIAL.

Related StackExchange Questions:

Which operating system is used for airplane computers?

ContentLicense: CC BY-SA 4.0


答:
Most modern aircraft use a general purpose RTOS (realtime operating system) pretty much the same thing that is used in factory automation, power stations, ships etc

Airbus use a few, including INTEGRITY from Northrop-grumman and program it in C/C++, Boeing use VxWorks among others

Title: What operating systems are used in airplanes, and what programming languages are they developed in?

Body:
I was wondering if anyone knows what is the operating system used in commercial airplanes (say Boeing or Airbus).

Also, what is the (preferred) real-time programing language? I heard that Ada is used in Boeing, so my question is - why Ada? what are the criteria the Boeing-guys had to choose this language? (I guess Java wouldn't be a great choice if exactly on lift-off the garbage collector wakes up).


问:
Architectural patterns for interaction beyond MVC?
We all know the venerable Model-View-Controller pattern used to design interaction [mostly] with human users. It is the de-facto standard in OOP environment.

What are some other architectural patterns of interaction worth mentioning? Non-OOP (functional, logical, etc) approaches welcome, too.

答:
You see a lot of MVC/MVP examples, but they always seem to skip the part about inter-controller communication.

Event Bus is a good way of handling that:

https://stackoverflow.com/questions/6030202/how-to-use-the-gwt-eventbus

Also:

Navigation [see MS Prism Navigation]:

A view is in a region.

The user clicks a button to navigate to a new view.

The navigator asks the existing view to confirm the navigation (as it may have unsaved data)

The view confirms the navigation, is destroyed, and is replaced with the new view

Presentation [see iPhone navigation controller]:

A view is in a region.

The user clicks a button to open a new view that will return info to the prior view.

The new view is added on top of the old view with modified navigation buttons.

The user enters info on the new view and hits "done".

The new view notifies the prior view that it is done (via event or callback).

The prior view gets the new info and destroys the new view.


答:
I'd add the following:

Do you know your customer's needs.  If not, has your requirements gathering team adequately determined what it is that the customer wants in the past and been responsive enough to ensure that changes are propagated as quickly as possible to the development team?  Are they adding in gold-plating to the requirements?

Is there an existing product you are competing with and have you determined prior to design just how you will compete with this product?  This is critical as existing products often come out with "I want that feature too" aspects which could make you deviate from original plans.  Is your team/management/target customer able to be side tracked by such an occurrence and do you have contingency plans set-up to handle such an issue?

Is the proposed design of your product relevant to the market?  Halfway through you don't want to discover that while it satisfies your customer's needs it lacks critical aspects to compete in the "new" world.

Title: Factors to be Considered for Software Risk Management

Body: What are the risk factors that we need to consider while planning for a software project.</p>


问:
When to use mixins in Ruby
I am wondering when to use mixins? I have read about them. Many authors compare them to interfaces, abstract classes, etc.

Mixins are modules that are mixed-in and modules are a way to group similar methods, constants and classes together.

I have seen examples where a module for math functions is created. It makes sense to group and reuse such functions but should I only mix these in a class if I am faced with an inheritance situation? Should I mix these in anytime I want to use them in a class?

Should they be used exactly like interfaces in other languages or are there other subtleties?

答:
IMHO I'd suggest that they are more like abstract classes in Java than interfaces since they include executable code. Having said that, it is more about reuse through composition than inheritance.

The advantage of a mixins is that they don't require you to inherit. This means that you can include functionality without affecting object hierarchy. It also means that unrelated classes can have common code.

For example using Mongoid doesn't require you to inherit from its class:

```<code>class Band
  include Mongoid::Document
end
</code>```

This makes the class able to be stored and found in MongoDB but you're still able to have your own inheritance.

Perhaps take a read of http://www.rubycentral.com/pickaxe/tut_modules.html and it should become a little clearer.

Title: When to use mixins in Ruby

Body:
IMHO I'd suggest that they are more like abstract classes in Java than interfaces since they include executable code. Having said that, it is more about reuse through composition than inheritance.

The advantage of a mixins is that they don't require you to inherit. This means that you can include functionality without affecting object hierarchy. It also means that unrelated classes can have common code.

For example using Mongoid doesn't require you to inherit from its class:

class Band
  include Mongoid::Document
end

This makes the class able to be stored and found in MongoDB but you're still able to have your own inheritance.

Perhaps take a read of http://www.rubycentral.com/pickaxe/tut_modules.html and it should become a little clearer.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答: My preference is to start with the design to get an overview of project and try to understand some of its key features and/or structure before drilling into the details.</p>


问:
Using git correctly in a small team
What would be the easiest way to use git correctly in a small team of about 5 developers, with one server running the live application?</p>

答: You must have one master repository on integration server and each developer must clone it. After it just do pull and push. Develop new big features in separate branch. No rocket science here. On live server - you also must clone master repository. And it's good practice to have branch like "live" for it. </p>

Title: Using git correctly in a small team


问:
Database structure for various items
I'm building a sqlite database for an android app which will hold a list of items, each of which have different characteristics.

Some of the characteristics are available for all objects, some are only relevant for a subset of objects.

For example, all my items have a name, a description, an image. Some items will also have an expiration date, others wont. Some will have a size, some wont. Etc...

How should I build my Database, as I don't know how many characteristics may be added in the future, and knowing I should be able to filter the list by any characteristic ?

答:
You must consider the particular pressures that apply to your situation and decide based on that. The general truths are:

If you put every possible attribute into your definition of 'item' as a field, many items will have redundant fields, which might waste space if you are very constrained on space.

Also, introducing a new attribute will require a database schema update rather than just an update of application code.

On the other hand, if you put attributes into their own table, you don't have these problems, but you will have to employ a JOIN every time you filter items. This could take longer than retrieving and filtering things from just one table.

Therefore, without knowing more about your situation, we can only tell you that you are looking at a time/space tradeoff, and possibly an ease-of-deployment tradeoff. But only you can know whether which of these considerations has more weight for your concrete project.

Title: Database structure for various items


答:
I suggest you to create some branch:

production

master

local

Production branch is "live" branch. Is the application in use right now.

When an update is needed, a developer can pull master branch into local branch. Than, can start to code. At the end, just pull and push from developer local branch to master. A Project manager can take a look in master branch. Test it. And when ready, can merge production with master. And now you'll have new software.

Title: Using git correctly in a small team

Body: What would be the easiest way to use git correctly in a small team of about 5 developers, with one server running the live application?</p>


答:
Few years back I asked this question to myself!

This is what I find easy and organized way to start web programming, you can skip steps which you have already know

To learn web programming, first you have to know

What is a website

What are the main role players

[Webserver, Mark-up languages, Client side scripting, Server side scripting, Protocols (http), Browsers

Trace complete server round trip i.e. from typing google.com in browser and to loading the complete page.

Why http is stateless? Role of session to overcome this?

Start learning html & little JavaScript

Basic tags

Marquee :-)

Alert, change color page background color via javascript etc

Have some fun playing around with html, javscript and css

Server side scripting

Start with php

Use all necessary input – type elements and create forms

Validate form with plain javascript

Retrieve submitted form data and display it via php

I think you can complete 1 to 5 quickly.  Its interesting part for all novice web programmers, because of the visual excitement they get while using html and css first time/

Then move to serious stuff!!!

At this time, you know fundamental things of web programming and working of website.

Now, it’s your responsibility to choose most appropriate language, platform and framework.

No one here can’t help you with this; You have to consider your personal interests and future plans to decide.

My recommendation is to go with php, since you learned it in initial stages.

Next, is databases
a.  Learn how to connect database
b.  Basic sql queries. Select, insert, update and delete
c.  Manipulate user inputs using database

Now, start creating a personal website; or any simple website

Download any open source website and learn from it.

Here are few references, which may help you

 1. W3 Schools – for learning basics of html, css, JavaScript, asp, database queries

 2. Php.net– for everything about php

 3. For exploring open source projects

  - http://bitbucket.org/

  - http://github.com/

  - http://www.codeplex.com/

  - http://sourceforge.net/

Always remember that there are several peoples here for help you; if anything happen, post it in stackoverflow.

Find someone with some amount of web programming experience to guide you; it’s always easy to learn from experienced programmers.

Do not forget to find some books too… for a starter you can checkout dummies

All the best!!!

Title: Best approach to learning web programming

Body:
I come from a scientific and embedded programming background, and I have had minimal experience with web programming.  What would be the best approach to take to get up to speed with web programming?  Tools and framework suggestions?

One approach would be to dive into learning a framework, such as Rails. I started doing this with rails tutorial, but I find that the framework abstracts so many important concepts that I should be learning.

To sum up, experienced programmer wants to learn web-app programming.


答: We've got a similar situation -- except we have dozens of web apps not one. We've been successfully using A successful Git branching model  for the last year or so with no significant complaints.</p>

Title: Using git correctly in a small team


问:
Should I swap from WCF to NserviceBus
We have a central server that sends and recieves messages from a number of PCs that are located on client networks in various locations. To facilitate this, currently I'm using WCF with TCPNetBindings, using duplex communication secured with certificates.

Now, we have a number of issues with this - mainly that we are being asked to support "disconnected mode" (we need to be fault tolerant). From what I know, there is no simple way to do this using the WCF stack - we'd need to implement something and perhaps use msmq. I've been looking at NServiceBus lately, and from I can see it seems to fit the bill well - fault tolerance, messages can be sent over the internet via a simple http gateway, etc. I know it's well respected in the community, and I can see why from looking into it.

So, my question is...Does employing NServiceBus sound like a sensible idea, or does anyone have any other suggestions / real world experience that relate to this? I guess I'm worried of introducing a new tech that I know relatively little about, and facing problems with things like securing it, setting everything up in a reliable way, gotchas along the way.. I'm also wary of "gold-plating" the architecture, and choosing something shiny that will end up bogging me down in implementation versus sticking with WCF and just making it work for me..

Thanks!

答:
They aren't a 1 for 1 replacement -- many times you'll use NServiceBus to feed messages into or take messages from a WCF endpoint.

In any case, handling disconnected mode scenarios like this is where message queues really, really shine. NServiceBus is a good place to start. There are a number of other options out there. I'll note many of them do actually wrap MSMQ at the end of the day -- MSMQ is a very solid back end and is probably worth using when it is made accessible.

Title: Should I swap from WCF to NserviceBus


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答:
Depends on the sort of company you work for.

Many companies don't value talented, experienced developers as highly as managers, and will never reward them to the same level <- This is not the sort of company people like you should be working for.

Other (usually more tech-focused) companies will value their developers more, and staying in technology should not limit your career in terms of reward and status <- you probably want to work for this sort of company.

If you have a bit of entrepreneurial spirit you could also start your own company - then you'd be the boss.


答:
Start simple and build up to a more complex workflow as and when you need to.

Whatever you do, don't let A successful Git branching model be the first thing people see, it will only confuse and overwhelm them. Look at this later when you have more experience.

I would suggest that you start with a central git repository and have everyone, including your production and test builds clone from that.

Within your git repository, create a production branch and a test branch.

Developers should work in their own local or remote feature branches until they are completed and merged into master. From here they can be merged into the test branch for deployment into the test environment and when they pass the tests they can be merged into the production branch.

That way you can always see what is new and untested, what is tested but not yet deployed into production and what is actually in production.

Title: Using git correctly in a small team


问:
Cairo Rotate Text : Transformation Matrix
http://www.cairographics.org/manual/cairo-Transformations.html

I have been using Cairo Vector Graphics Library for some work, and I can't quite understand some parts:

What is the default value of the transformation matrix?

When do I need the transformation matrix anyway?

Suppose I don't want to rotate text, will I still need to set it, will it still be set?

答:
As far as I can tell from the documentation, you have an structure "Cairo_t", this "Cairo T" is what the transformations get placed into. Each "Cairo Matrix" is a "Transformation Matrix" regardless of whether or not it is "doing stuff" to the text. The initial structure has no values, it's just a block of memory assigned to a rendering device.

In order to make that do anything and thus pass the changes to the rendering device you have to perform actions on the structure by assigning transformations to it. These transformations include getting and setting matrices and transforming them.

The fact that it is called "Cairo Transformation Matrix" is due to the fact that it can be transformed not that it will be. Although one could argue that all actions on the structure in question are transforms.


答: For what it's worth: For spacecraft (satellites and interplanetary ones) C and C++ is still dominant (and with very strict compliance to ISO standards), generally running VxWorks. Labs will generally stick with either C or C++ based on developer familiarity, confidence in the compiler toolchain, and internal coding standards. There are compelling reasons for both languages for real-time flight software, but each organization tends to stick with one or the other. Ancillary instruments, on the other hand, are commonly programmed in Forth, C, and increasingly modern scripting languages like Lua.</p>


答:
First, see the wikipedia page on transformation matrices. That should help with the terminology. Next, understand that there are two matrices involved at any given time.

The "prime" matrix

The "item" matrix

The prime matrix usually starts out as a bunch of zeros and a one:

```<code>[0 0 0]
[0 0 0]
[0 0 1]
</code>```

This means do nothing. Next the item's matrix is determined. Once it's time to start laying things onto the device, then these two matrices are combined with an affine transformation.

This transformation gives you a point off of the starting position to draw your item, with any appropriate scaling or rotation.

Since the prime matrix is used across all of the items, we can adjust it to have some universal effect. Say we want to shift everything "left" 50 points. You're lucky in that you wouldn't have to manually set your matrix to do this, just call cairo_translate(cr, -50, 0) or something similar.

Now every new item rendered will be modified.

Title: Cairo Rotate Text : Transformation Matrix

Body:
http://www.cairographics.org/manual/cairo-Transformations.html

I have been using Cairo Vector Graphics Library for some work, and I can't quite understand some parts:

What is the default value of the transformation matrix?

When do I need the transformation matrix anyway?

Suppose I don't want to rotate text, will I still need to set it, will it still be set?

Body:
First, see the wikipedia page on transformation matrices. That should help with the terminology. Next, understand that there are two matrices involved at any given time.

The "prime" matrix

The "item" matrix

The prime matrix usually starts out as a bunch of zeros and a one:

[0 0 0]
[0 0 0]
[0 0 1]

This means do nothing. Next the item's matrix is determined. Once it's time to start laying things onto the device, then these two matrices are combined with an affine transformation.

This transformation gives you a point off of the starting position to draw your item, with any appropriate scaling or rotation.

Since the prime matrix is used across all of the items, we can adjust it to have some universal effect. Say we want to shift everything "left" 50 points. You're lucky in that you wouldn't have to manually set your matrix to do this, just call cairo_translate(cr, -50, 0) or something similar.

Now every new item rendered will be modified.


问:
When/why is it easier to beg forgiveness than ask permission?
The saying "It's easier to beg forgiveness than ask permission" seems pretty popular among programmers and IIRC was attributed to Grace Hopper.  In what situations is this typically true, and why do you believe that such a counterintuitive proposition would hold?</p>

答:
When you ask permission, the person you are asking must imagine the consequences that COULD happen if you are allowed to do it. This could include terrible things like the company going bankrupt. A risk averse person (or one with a lurid imagination) will tell you no. They may not be swayed by the possible benefit of your plan. When you just go on ahead and do it without asking, if you get the benefit then you are unlikely to be punished or reprimanded. If you get a small consequence, you will get a small punishment. Of course, if you bankrupt your employer, it's all over.

I can't employ someone who needs to check with me on every email, every line of code, constantly wanting permission to do their regular job. But someone who thought it was ok to risk the entire company on a ridiculous gamble (a company that isn't theirs to risk, since I own it not them) would not still work for me even if the gamble paid off. You need to be in a fairly big and deep pocketed organization (the US military for example) to take this attitude - and you need to understand the risks very well.


问:
How many juniors should a senior mentor?
Our shop's size increases dynamically, so we are planning to hire a few new junior developers but we would not like to overwhelm the seniors with too much mentoring and training. How many (usually fresh out of college) junior developers could (and should) a senior developer mentor while the senior is still being able to do his or her tasks effectively?</p>

答: Ideally a junior works with a mentor on a project.  In this way the senior can assign sub tasks and work with them towards completing a project.  The more juniors the Senior has to manage the less work the senior will be able to complete of their own.  I would not want more than 1 or 2 junior working with a senior at any one time.  Though the senior can continue to mentor other programmers after 2 or 3 months a decent programmer should need far less time from the senior than they did originally.  So a senior could conceivably have 20 or more people he is mentor for but really only 2 or 3 that really require much of their time.</p>


问:
Is it correct to fix bugs without adding new features when releasing software for system testing?
This question is to experienced testers or test leads.
This is a scenario from a software project:

Say the dev team have completed the first iteration of 10 features and released it to system testing. The test team has created test cases for these 10 features and estimated 5 days for testing. The dev team of course cannot sit idle for 5 days and they start creating 10 new features for next iteration. During this time the test team found defects and raised some bugs. The bugs are prioritised and some of them have to be fixed before next iteration. The catch is that they would not accept the new release with any new features or changes to existing features until all those bugs fixed. The test team says that's how can we guarantee a stable release for testing if we also introduce new features along with the bug fix. They also cannot do regression tests of all their test cases each iteration. Apparently this is proper testing process according to ISQTB.

This means the dev team has to create a branch of code solely for bug fixing and another branch where they continue development. There is more merging overhead specially with refactoring and architectural changes.

Can you agree if this is a common testing principle. Is the test team's concern valid. Have you encountered this in practice in your project.

答:
If the bugs that you describe are actual defects and not design optimizations, then yes you should really try to fix them before beginning work on new features.

If you build new features on top of known bugs, you are creating a house of cards.  You may likely develop brittle, unpredictable software.  Depending on the level of isolation between the buggy code and your new features, the bugs could impact your new features as well.  If so, how would you know if your new features work correctly?

If you fix your bugs first, you will have a stronger foundation for any new features that you add.

Certainly, there are times when external forces pressure you to go against your better judgement.  Try to help decision makers reach an informed decision where they are aware of consequences of either course of action (i.e. unresolved defects versus missed feature delivery dates) and allow them to exercise their judgement.  There are sometimes legal and financial reasons where a course of action, while not preferable, is necessary.

Always try to fix bugs before adding new features!


问:
Are there Negative Impact of opensource on commercial environment?
My company has a very broad range of products and there are a few that are not strategic to us so I wanted to open source them (so we can focus on what makes us unique and open source the products that every firm has).

Our industry(hedgefund) does not open source(we would be the first firm to try this) and the feedback I'm getting from my management team is either 1) we'll destroy the industry or 2) all competitive commercial firms will unite against us and we'll be wiped out either way.  It's a big battle in my firm right now between the IT people who have seen the positive effects of sharing and the business people who think we'll be giving up everything (they prefer we sell parts we want to opensource, but in their defense this is standard when divesting something).

So what are your thoughts? Does open sourcing apply generally or is it only really applicable to software? Is it overall good for people in the industry and outside? I'm actually more interested in the negativeness effects(although positive are welcomed as well)

Update: Long story short, although code is involved this is not so much about code as it is more about the idea of open sourcing.

We are a mid sized quant hedge fund.  We have some unique strategies but also have the standard long/short, arbitrage, global macro, etc.. funds.

We are keeping the unique funds we have but the other stuff that everyone else has we are considering open sourcing (We have put in years of work & millions of dollars into. Our funds is pretty popular and our performance is either in first or second quartile so I suspect there will be interest from firms in or thinking of getting into the industry but I don't know to what extent).

The goal is not to get a community to work for us, the goal is to let anyone who wants to tinker with it do so and create anything they want (it will not be part of our product line although I may unofficially allocate some our of staff's time to assist any community that grows).  Although the code base is quite large, the value in this is the industry knowledge and approaches we have acquired (there are many books on artificial intelligence and quant trading but they are often years behind what's really going on as most firms forbid their staff from discussing what they are doing). Long story short, there maybe value here for people or not but I'm approaching open sourcing as a way to benefit the general public while we divest a product line up. But the flip side, is this is a core product to many other firms and they won't be happy(I think about linux/windows, wikipedia/britannica, google maps/commercial map firms, and so on).  I'm fine with people disliking me but I'd rather it not be for unindented consequences and this question is to try to understand what those consequences generally are on industries that get core areas open sourced. For example, its hard to judge what part of the OS market grew because of Linux or was naturally growing on its own and so on. Technology has such fast grow and I'm struggling to understand how open sourced impacted it(and if it was positive or not. I.e. one of our large competitors has very large grants to top universities which obviously helps the schools, would open source limit the need for things like that?).

I understand this can seem very specific to me but I'm trying to understand general impact of open sourcing and software seemed like a good place to learn.

答:
I think it's probably a bad idea to open-source anything that gives you a competitive edge. What would the advantage be to open-sourcing your code? You seem to say that the advantage would be:

so we can focus on what makes us unique and open source the products that every firm has.

It sounds like you're not planning to open-source your flagship product, but maybe some small utilities that ship with it, with the hope that the community will pick up the maintenance slack so your company can focus on the core product. That seems risky, if the community you hope for never materialises. Are these potential targets of open-sourcing potentially useful to other industries and users from other backgrounds? Do you really think it likely that random hackers will pick them up and improve them?

In response to your update: It sounds like the code you might open-source is very niche. How will you generate interest in it? How will you get people to tinker with it? If you just dump it on github or sourceforge and say "have fun!" who will find it, and how will they find it and why will they download it? The marketing side of this idea I think needs some work.

Maybe you should open-source some of it and market it to the students you want to hire later. Send some demo kits to professors so they can have their class use your software for their projects.

This will involve work though, someone will have to put together the kits for students, build the community website, monitor forums and answer questions, etc... Does your company have any interest in paying for all that? It could be a big benefit, but then again, maybe not...


问:
When writing tests for a WordPress plugin, should i run them inside WordPress or in a normal browser?
I have started using BDD for a WordPress plugin i'm working on and i'm rewriting the js codebase to do tests. I've encountered a few problems but i'm going steady now, i was wondering if i had the right approach, because i'm writing test that should pass in a normal browser environment and not inside WordPress.

I choose to do this because i want my plugin to be totally independent from the WordPress environment, i'm using requirejs in a way that i don't expose any globals and i'm loading my version of jQuery that doesn't override the one that ships with WordPress. In this way my plugin would work the same on every WordPress version and my code would not break if they change the jQuery version or someone use my plugin on an old WordPress version.
I wonder if this is the right approach or if i should always test inside the environment i'm working in. Since WordPress implies some globals i had to write some function purely for testing purpose, like

```<code>"get_ajax_url": function() {
    if( typeof window.ajaxurl === "undefined" ) {
        return "http://localhost/wordpress/wp-admin/admin-ajax.php";
    } else {
        return window.ajaxurl;
    }
},
</code>```

but apart from that i got everything working right. What do you think?

答:
I think you're on the right track, including your methodology.

As an enhancement, you could create additional tests that run within the wordpress application environment.  You might want to do this if you needed to generate additional diagnostic information when a failure occurs.  Another situation is if you needed advanced triggers to be fired that can only occur within the application / plugin and aren't triggered by user interaction.

At a more abstract level, what you're doing is creating test sets based upon how the user will interact with your application / plugin.  For the beginning and intermediate stages of test design, this is an excellent place to start.  It presents the most value / reward for your effort and it gives you a degree of assurance that your users will get what you expected.

Guaranteeing the UI experience will go a long way towards keeping your user base happy.


答: I start with code. Separate design documents, if there are any, are as likely to be wrong or misconceived as not. So, i start by trying to trace some simple flow through the code; if it's a webapp, it could be a request or a sequence of requests, for instance. Once i've done that, i have a sort of skeleton to hang more understanding on. Then, i might go back and read designs or other documentation, but at that point, i have something concrete to relate them to, and to validate them with, so i can detect duff information. Or i might just carry on reading code, or test cases, etc.</p>

Title: What do you look at first: the code or the design?

Body:
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?


问:
Is it bad form to stage a function's steps in intermediate variables (let bindings)?
I find I tend to need intermediate variables. In Clojure that's in the form of let bindings, like cmp-result-1 and cmp-result-2 in the following function.

```<code>(defn str-cmp
    "Takes two strings and compares them. Returns the string if a match; and nil if not."
    [str-1 str-2 start-pos substr-len]

    (let [cmp-result-1 (subs str-1 start-pos substr-len)
          cmp-result-2 (subs str-2 start-pos substr-len)]
        (compare cmp-result-1 cmp-result-2)))
</code>```

I could re-write this function without them, but to me, the function's purpose looks clearer. I tend to do this quite in a bit in my main, and that is primarily for debugging purposes, so I can pass a variable to print out intermediate output.

Is this bad form, and, if so, why?

Thanks.

答:
Side note: It's a shame that there isn't any Clojure highlighting here.

I would consider this purely a matter of preference. Never would I have considered it bad form. It doesn't always promote readability, but rarely does it harm it.

However, I have no idea what rc means, so if you're going to use auxiliary variables, they might as well promote readability by revealing some intent with a better choice of words.


答: Nah. For arbitrary functions composed of N intermediary variables, the maximum complexity is exponential in N, if not higher. Intermediate variables most definitely allow for highly complex functions to be expressed cleanly.</p>

Title: Is it bad form to stage a function's steps in intermediate variables (let bindings)?

Body:
I find I tend to need intermediate variables. In Clojure that's in the form of let bindings, like cmp-result-1 and cmp-result-2 in the following function.

```<code>(defn str-cmp
    "Takes two strings and compares them. Returns the string if a match; and nil if not."
    [str-1 str-2 start-pos substr-len]

    (let [cmp-result-1 (subs str-1 start-pos substr-len)
          cmp-result-2 (subs str-2 start-pos substr-len)]
        (compare cmp-result-1 cmp-result-2)))
</code>```

I could re-write this function without them, but to me, the function's purpose looks clearer. I tend to do this quite in a bit in my main, and that is primarily for debugging purposes, so I can pass a variable to print out intermediate output.

Is this bad form, and, if so, why?

Thanks.


问:
Is a new build required everytime I make a change to the code?
I am working on a project that has around a hundred different files (.cpp & .h), and it requires around an hour to build the entire project on MSVC 2008, suppose that I now make a change to any one file, do I need to build the entire project once again, right from the beginning, or is there a way out ?

I know it is very very noob like, but I am wasting a lot of time, hence I was wondering

答:
The short answer: It depends.

The long answer: It depends on your source code dependencies.

For example, if every class knows about every other class in the project, then every time you make a change to one, you probably have to recompile the other.

It also depends on linkage. If you link everything into one binary file, it's also likely to compile everything again. A better way would be to separate to different shared libraries (DLLs), or at the very least into separate object (.o) files.

But then (in the latter case) you might need to tinker with it to see that it doesn't recompile all object files when you just need to recompile one and link them all together again.

But then again, maybe the linking process takes a while too. You basically need to experiment with that.

On a final note... An hour for building ~100 files? That's way, way too much, unless you're running on a really old machine. Or unless each file contains tens of thousands of lines.


问:
Is it ok to replace optimized code with readable code?
Sometimes you run into a situation where you have to extend/improve some existing code. You see that the old code is very lean, but it's also difficult to extend, and takes time to read.

Is it a good idea to replace it with modern code?

Some time ago I liked the lean approach, but now, it seems to me that it's better to sacrifice a lot of optimizations in favor of higher abstractions, better interfaces and more readable, extendable code.

The compilers seem to be getting better as well, so things like struct abc = {} are silently turned into memsets, shared_ptrs are pretty much producing the same code as raw pointer twiddling, templates are working super good because they produce super lean code, and so on.

But still, sometimes you see stack based arrays and old C functions with some obscure logic, and usually they are not on the critical path.

Is it a good idea to change such code if you have to touch a small piece of it either way?

答:
IMHO readability is more important than optimised code because in most cases micro-optimisation does not worth it.

Article about non-sense micro-optimizations:

As most of us, I am tired to read blog posts about non-sense
  micro-optimizations like replacing print by echo, ++$i by $i++, or
  double quotes by single quotes. Why? Because 99.999999% of the time,
  it is irrelevant.

"print" uses one more opcode than "echo" because it actually returns
  something. We can conclude that echo is faster than print. But one
  opcode costs nothing, really nothing.

I have tried on a fresh WordPress installation. The script halts
  before it ends with a "Bus Error" on my laptop, but the number of
  opcodes was already at more than 2.3 millions. Enough said.