问:
What is the name of this array transformation?
Start with an array of arrays; in this case, they are different lengths in order to demonstrate the technique, but they do not have to be.

```<code>[[1,2,3,4], [5,6,7], [8,9,10], [11,12,13,14,15]]
</code>```

At the other end of the transformation, you have an array of arrays where the first array contains the first element from each of the original arrays, the second array contains the second element from each of the original arrays, and so on.

```<code>[[1,5,8,11], [2,6,9,12], [3,7,10,13], [4,14], [15]]
</code>```

Is there a mathematical or CS term for this operation?

答:
It's called transposing except for the deal with the flaggedness of the arrays

In linear algebra, the transpose of a matrix A is another matrix AT... created by any one of the following equivalent actions:

reflect A over its main diagonal (which runs from top-left to bottom-right) to obtain AT

write the rows of A as the columns of AT

write the columns of A as the rows of AT


问:
How can I  really master a programming language?
I know that learning a language, you can simply buy a book, follow the examples, and whenever possible try the exercises. But what I'm really looking is how to master the language once you've learned it.

Now I know that experience is one major factor, but what about learning the internals of the language, what is the underlying structure, etc.

There are articles out there saying read this book, read that book, make this game and that game.
But to me this doesn't mean to master a language. I want to be able to read other people's code and understand it, no matter how hard that is. To understand when to use a function and when another, etc etc.

The list could go on and on but I believe I've made the point. :)

And finally, take whatever language as an example if needed, though best would be if C was taken as an example.

答: You cant learn a language from the book. All you need is practice and practice . Don't think You can learn a language from that particular book or that particular source .Just think programming language is same as human language .You cant simply learn English or French by reading a particular book.All you need is using it in day to day life. Code from scratch , extend its functionality try to build something that will make you little bit satisfied.And if you are thinking mastering a language as knowing whole language and using each element of programming language in practical coding ..YOU CAN'T. Or even if you can it might take 10-15 years. </p>

ContentLicense: CC BY-SA 3.0


问:
Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim?
In What would you choose for your project between .NET and Java at this point in time? I say that I would consider the "Will you always deploy to Windows?" the single most important technical decision to make up front in a new web project, and if the answer is "no", I would recommend Java instead of .NET.

A very common counter-argument is that "If we ever want to run on Linux/OS X/Whatever, we'll just run Mono"1, which is a very compelling argument on the surface, but I don't agree for several reasons.

OpenJDK and all the vendor supplied JVM's have passed the official Sun TCK ensuring things work correctly.  I am not aware of Mono passing a Microsoft TCK.

Mono trails the .NET releases.  What .NET-level is currently fully supported?

Does all GUI elements (WinForms?) work correctly in Mono?

Businesses may not want to depend on Open Source frameworks as the official plan B.

I am aware that with the new governance of Java by Oracle, the future is unsafe, but e.g. IBM provides JDK's for many platforms, including Linux.  They are just not open sourced.

So, under which circumstances is Mono a valid business strategy for .NET-applications?

1Mark H summarized it as: "If the claim is that "I have a windows application written in .NET, it should run on mono", then not, it's not a valid claim - but Mono has made efforts to make porting such applications simpler."

答:
As a target, the .NET/mono universe moves very fast.

Every few years, Microsoft comes out with some compelling changes and innovations regarding the language, runtime, and infrastructure surrounding .NET. For example: Generics, LINQ, DLR, Entity Framework -- with every new revision of Visual Studio, there's generally a pretty significant increase in the feature set and usefulness of the framework it targets.

While the constant improvement in the framework is welcome, it's also problematic if you want compatibility across multiple platforms. Long-term-support platforms like Red Hat Enterprise Linux move glacially slow with regards to adopting new technology, and at any given point, there's going to be significant improvements in the Mono platform that have happened just within the last few months. So if you want to run the stuff that the cool kids are building, you're going to have to compile Mono from scratch and manage your own patches and updates. That's not cool.

Java, on the other hand, is as stagnant as a kiddie pool. Especially now that it's own by a company that just wanted Java for the patent lawsuits, you can be fairly certain that there will be no detectable changes in the language or runtime in the foreseeable future. Java is as stable a platform as FORTRAN. That's not so good if you were hoping for any sort of improvements, but not so bad if you're trying to deploy an enterprise application.


问:
Why do some opensouce libraries lack comments?
I don't know if this happens to most Opensource libraries, but many of I know and use (for example OpenSSL, Webkit, ...) they all lack comments, or contain very few comments.

Not to mention their very few documents, it is hard to read their source code. We can hardly understand what a member variable means, or what this function does. This seems to be against coding standard practice

Why is that? How can people collaborate to these opensource with very few comments?

答:
How can people collaborate to these opensource with very few comments

Assumed you meant "How can people collaborate to these opensource code which is hard to read" - well, I guess an open source project with bad code will simply have fewer contributors than it could have had with good code. But don't forget that the readability of code lies always in the eye of the beholder, and most open source code is not that bad that you cannot understand at least a a bit or the intentions of some functions and classes.

Often, when you want to contribute something to an open source project, you don't need to understand the whole thing, only the parts where you want to add a specific feature. So if a dev has a need for a missing feature, he will most probably bite the bullet, identify the parts he needs to change, "decode" that parts mentally and add the new features there. If he is a good one, he will also try to review and refactor the "decoded" parts, but I guess in practice this will happen too seldom.


答:
Writing source code is fun.

Writing documentation and commenting code is less fun.

When a developer works in a company which enforces good comments and documentation, there is no choice: either this developer writes those, or he's at risk of being fired.

When a developer contributes to an open source project, he's doing it for free, and especially for fun. There is nobody to force this developer to do things he's not willing to do, like writing documentation and comments.

That's why many open source projects lack extensive documentation and comments.

How people can still contribute to open source projects with no documentation or comments?

If the source code is high quality, comments are not needed too much. The comments of public interfaces and the documentation are especially useful for the project consumers, i.e. developers who simply use libraries, not contribute to them.

There is no productivity factor involved. I'm working in a company where the actual codebase has no unit tests, no documentation, and no comments. I spend lots of time figuring out what a 600-LOC method is doing or coding things which are already done, but not discoverable because of the lack of documentation, so most of the time, I'm simply wasting company's money instead of doing something valuable.

On the other hand, for an open source project, it doesn't matter if one of the contributors wasted one week because of the lack of documentation or proper comments. The worst thing which can happen is that this contributor will leave the project.

Discovering code without comments or documentation may even be challenging, i.e. attract some contributors, instead of discouraging them.

In enterprise projects, it is not unusual for a developer to be forced to work on every aspect of a product, and, few years later, having to know nearly the whole system. On an open source project, nobody forces you to know the whole thing. You can simply contribute to a tiny part of it, and have an excellent knowledge of this part, without any need for documentation.

Title: Why do some opensouce libraries lack comments?

Body:
I don't know if this happens to most Opensource libraries, but many of I know and use (for example OpenSSL, Webkit, ...) they all lack comments, or contain very few comments.

Not to mention their very few documents, it is hard to read their source code. We can hardly understand what a member variable means, or what this function does. This seems to be against coding standard practice

Why is that? How can people collaborate to these opensource with very few comments?


问:
How to convince boss to buy Visual Studio 2012 Professional
The main advantage is the use of ReSharper and other add-ons but we need to make a convincing argument for the purchase of Visual Studio 2012 Professional. We are currently using Visual Studio 2012 Express for Windows. It is quite good but is hard to switch from using the full Professional version in the past.

So far the team has compiled the following list:

Extract Interface function missing. Very useful for clean SOLID code.

No add-on support. Can’t install StyleCop or productivity tools. AnkhSvn, Spell checker, Productivity PowerTools, GhostDoc, Regex
  Editor, PowerCommands.

The exception assistant is limited in Express edition. This is a big annoyance. See
  http://www.lifehacker.com.au/2013/01/ive-given-up-on-visual-studio-express-2012-for-windows-desktop-heres-why/

Different tools provided by MS like certificate generation.

Possibility of create a Test project based on source code.

We do server development in C# so any web add-ons or anything else is useless.

The reason I am asking is I am sure that people have been in the same position. What approach did you use and can you think of additions or ammends to the above list?

Thanks,

答:
Calculate how much hours you save with this per week.

Multiply the amount with your workweeks per year.

Multiply this with the amount of money they pay you per hour.

Subtract the price of VS2012 Prof. from the result.


答:
Several reasons.

Writing documentation isn't fun, and for many projects, the user base is the programming team; everyone knows what the code is about, so documentation isn't really seen as an important aspect of the project.

Documentation can (and will) become outdated, and outdated documentation is worse than none at all. This means that documentation is an extra liability, and may impact the flexibility of your codebase (more documentation means for any change you'll have to update the code and the documentation). Especially for very specific open-source projects, this is actually a valid argument to aim for minimal documentation, and write readable code instead.

The economics of open source software are different. While it is good to have contributors on your project, many projects are scratch-an-itch type projects which the author has written to solve a particular problem and then just threw out in the open, as-is. Since you're basically eating someone else's breadcrumbs, the attitude is that you are in no position to demand anything, let alone documentation.


问:
Is a function plotter a legitimate use of eval() in JavaScript?
From PHP development I know that eval is evil and I've recently read What constitutes “Proper use” of the javascript Eval feature? and Don't be eval. The only proper use of eval I've read is Ajax.

I'm currently developing a visualization tool that lets users see how polynomials can interpolate functions:

Example

Code on GitHub

I use eval for evaluation of arbitrary functions. Is this a legitimate use of eval? How could I get rid of eval?

I want the user to be able to execute any function of the following forms:

a x^i with a,i in R

sin, cos, tan

b^x with b in R

any combination that you can get by

adding (e.g. x^2 + x^3 + sin(x)),

multiplying (e.g. sin(x)*x^2) or

inserting (e.g. sin(x^2))

答:
I see nothing not "legitimate", eval isn't evil per se and it has been precisely designed to evaluate arbitrary code. It lets you here make a fast, complete expression evaluator without resorting to complex libraries and it gives your user the power of JavaScript.

But right now you're evaluating the input for each x. This is very slow.

I would do this so that it can be used more efficiently :

```<code>var f = Function('x','return '+input);
</code>```

When input is Math.sin(x), this builds a function you can simply call as

```<code>var x = 3;
var y = f(x);
</code>```

Proof : jsperf

If what you want is to let the user enter function with a more classical mathematical language (like x^y), then you'd better start importing a mathematical expression parser.

An example of such a library : Silent Mat's evaluator

Body:
I see nothing not "legitimate", eval isn't evil per se and it has been precisely designed to evaluate arbitrary code. It lets you here make a fast, complete expression evaluator without resorting to complex libraries and it gives your user the power of JavaScript.

But right now you're evaluating the input for each x. This is very slow.

I would do this so that it can be used more efficiently :

var f = Function('x','return '+input);

When input is Math.sin(x), this builds a function you can simply call as

var x = 3;
var y = f(x);

Proof : jsperf

If what you want is to let the user enter function with a more classical mathematical language (like x^y), then you'd better start importing a mathematical expression parser.

An example of such a library : Silent Mat's evaluator


答:
You don't want to evaluate Javascript functions. You want to evaluate some subset of the computable functions from the reals to the reals. So eval doesn't do what you want, although in principle you may be able to abuse it for that.
Apart from this philosophical objection, if you want to use ^ for exponentiation, you can't use eval because it uses Javascript syntax where ^ is binary xor.

If you just want to be done quickly and leave this project, you can use eval (especially since this apparently runs on the client site, so the potential for abuse is limited). But the right thing(tm) to do would be using an expression parser specifically for the kind of syntax you want to allow, coupled with an evaluation routine for the parsing output.

It's not that hard to write such a thing yourself, and quite fun. I'd use either the shunting-yard algorithm or a top down operator precedence parser. Alternatively, use an existing library as recommended in the comments.

Title: Is a function plotter a legitimate use of eval() in JavaScript?

Body:
From PHP development I know that eval is evil and I've recently read What constitutes “Proper use” of the javascript Eval feature? and Don't be eval. The only proper use of eval I've read is Ajax.

I'm currently developing a visualization tool that lets users see how polynomials can interpolate functions:

Example

Code on GitHub

I use eval for evaluation of arbitrary functions. Is this a legitimate use of eval? How could I get rid of eval?

I want the user to be able to execute any function of the following forms:

a x^i with a,i in R

sin, cos, tan

b^x with b in R

any combination that you can get by

adding (e.g. x^2 + x^3 + sin(x)),

multiplying (e.g. sin(x)*x^2) or

inserting (e.g. sin(x^2))


问:
How does the ? make a quantifier lazy in regex
I've been looking into regex lately and figured that the ? operator makes the *,+, or ? lazy. My question is how does it do that?

Is it that *? for example is a special operator, or does the ? have an effect on the *? In other words, does regex recognize *? as one operator in itself, or does regex recognize *? as the two separate operators * and ??

If it is the case that *? is being recognized as two separate operators, how does the ? affect the * to make it lazy. If ? means that the * is optional, shouldn't this mean that the * doesn't have to exists at all. If so, then in a statement .*? wouldn't regex just match separate letters and the whole string instead of the shorter string?

Please explain, I'm desperate to understand.

答:
The *? is definitely one operator and not the normal * with a modifying meta-operator. It is commonly named similar to * for mnemonic purposes only.

The effect that *? has in contrast to * is subtle, but it goes deep enough into the expression engine that it has to be treated in a different way at the "transmission" level (deciding whether to backtrack or not), and that can't be done by something applied to the result of a normal *. (For much, much more information, read chapter 4 of Mastering Regular Expressions.)


问:
Better solution then simple factory method when concrete implementations have different attributes
```<code>abstract class Animal {
  function eat() {..}
  function sleep() {..}
  function isSmart()
}

class Dog extends Animal {
  public $blnCanBark;
  function isSmart() {
    return $this->blnCanBark;
  }
}

class Cat extends Animal {
  public $blnCanJumpHigh;
  function isSmart() {
    return $this->blnCanJumpHigh;
  }
}

.. and so on up to 10-20 animals.
</code>```

Now I created a factory using simple factory method and try to create instances like this:

```<code>class AnimalFactory {
  public static function create($strName) {
       switch($strName) {
          case 'Dog':
            return new Dog();
          case 'Cat':
            return new Cat();
          default:
            break;
       }
  }
}
</code>```

The problem is I can't set the specific attributes like blnCanBark, blnCanJumpHigh in an efficient way.

I can send all of them as extra params to create but this will not scale to more then a few classes. Also I can't break the inheritance because a lot of the basic functionality is the same.

Is there a better pattern to solve this?

答:
Why do you have public variables like blnCanBark and blnCanJumpHigh instead of proper set_property functions.

If I simple try to understand the above code then i think there should have been a function set_properties() with unlisted number of parameters or better set_properties(array $properties).

It may not be manageable with simple functions and I would have gone for abstract class and interface for more complex logic.

But if simplicity is desirable then set_properties(array $properties) is the solution.


答:
It depends on why you are using the factory method pattern.

If the main purpose is to be able to return a subclass of Cat instead of a plain Cat, using multiple factory methods might suit the purpose better, with the additional advantage of removing the "magic strings" passed to create:

```<code>class AnimalFactory {
  public static function createCat($canJumpHigh) {
    // in the future, this can be extended to return a HouseCat instead
    return new Cat($canJumpHigh);
  }
  public static function createDog($canBark) {
    return new Dog($canBark);
  }
}
</code>```

Title: Better solution then simple factory method when concrete implementations have different attributes

Body:
```<code>abstract class Animal {
  function eat() {..}
  function sleep() {..}
  function isSmart()
}

class Dog extends Animal {
  public $blnCanBark;
  function isSmart() {
    return $this->blnCanBark;
  }
}

class Cat extends Animal {
  public $blnCanJumpHigh;
  function isSmart() {
    return $this->blnCanJumpHigh;
  }
}

.. and so on up to 10-20 animals.
</code>```

Now I created a factory using simple factory method and try to create instances like this:

```<code>class AnimalFactory {
  public static function create($strName) {
       switch($strName) {
          case 'Dog':
            return new Dog();
          case 'Cat':
            return new Cat();
          default:
            break;
       }
  }
}
</code>```

The problem is I can't set the specific attributes like blnCanBark, blnCanJumpHigh in an efficient way.

I can send all of them as extra params to create but this will not scale to more then a few classes. Also I can't break the inheritance because a lot of the basic functionality is the same.

Is there a better pattern to solve this?

Body:
It depends on why you are using the factory method pattern.

If the main purpose is to be able to return a subclass of Cat instead of a plain Cat, using multiple factory methods might suit the purpose better, with the additional advantage of removing the "magic strings" passed to create:

class AnimalFactory {
  public static function createCat($canJumpHigh) {
    // in the future, this can be extended to return a HouseCat instead
    return new Cat($canJumpHigh);
  }
  public static function createDog($canBark) {
    return new Dog($canBark);
  }
}


问:
Hide or Show singleton?
Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such:

C#:    MyClass.Instance

Java: MyClass.getInstance()

The question is: when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible?

Here are the alternatives for illustrative purposes:

Exposed(C#):

```<code>private static MyClass instance;
public static MyClass Instance
{
    get {
        if (instance == null)
            instance = new MyClass();
        return instance;
    }
}

public void PerformOperation() { ... }
</code>```

Hidden (C#):

```<code>private static MyClass instance;

public static void PerformOperation()
{
    if (instance == null)
    {
        instance = new MyClass();
    }
    ...
}
</code>```

EDIT:
There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario:

My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the Logger class (e.g. Logger.Instance.Warn(...) or Logger.Instance.Error(...) etc. Should I use Logger.Warn(...) or Logger.Warn(...) instead?

If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you :)

答:
I think hiding Singleton is a bad idea. If you don't have a way to get a reference to the created instance via a getInstance() method, how you are going to do it considering that Singleton classes do not have public constructors? There is no way to get that reference. That means that if you decide to "hide" the Signbleton, your only option is to check in every public static method of the Signletone class whether the instance was already instantiated and if not, do it. So your code becomes something like this:

```<code>class BadSingletone {
    private static MyClass instance;

    public static void PerformOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }

        public static void PerformSomeOtherOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }

    public static void PerformYetAnotherOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }
}
</code>```

littered with all those instantiation checks. You can of course encapsulate the check in a separate function but you will again have to call it in every public static function of the class. And what if you accidentially forget to include it in one of the functions? Users of the class will not be too happy about it.

So, to my mind, hiding Singleton does not make sense - it makes you litter your code with unneccessary checks.

Title: Hide or Show singleton?

Body:
I think hiding Singleton is a bad idea. If you don't have a way to get a reference to the created instance via a getInstance() method, how you are going to do it considering that Singleton classes do not have public constructors? There is no way to get that reference. That means that if you decide to "hide" the Signbleton, your only option is to check in every public static method of the Signletone class whether the instance was already instantiated and if not, do it. So your code becomes something like this:

class BadSingletone {
    private static MyClass instance;

    public static void PerformOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }

        public static void PerformSomeOtherOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }

    public static void PerformYetAnotherOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }
}

littered with all those instantiation checks. You can of course encapsulate the check in a separate function but you will again have to call it in every public static function of the class. And what if you accidentially forget to include it in one of the functions? Users of the class will not be too happy about it.

So, to my mind, hiding Singleton does not make sense - it makes you litter your code with unneccessary checks.


问:
Who extends interfaces? And why?
AFAIK, my class extends parent classes and implements interfaces. But I run across a situation, where I can't use implements SomeInterface. It is the declaration of a generic types. For example:

```<code>public interface CallsForGrow {...}

public class GrowingArrayList <T implements CallsForGrow>  // BAD, won't work!
                              extends ArrayList<T>
</code>```

Here using implements is syntactically forbidden. I thought first, that using interface inside <> is forbidden at all, but no. It is possible, I only have to use  extends instead of implements. As a result, I am "extending" an interface. This another example works:

```<code>public interface CallsForGrow {...}

public class GrowingArrayList <T extends CallsForGrow>  // this works!
                              extends ArrayList<T>
</code>```

To me it seems as a syntactical inconsistancy. But maybe I don't understand some finesses of Java 6?  Are there other places where I should extend interfaces? Should the interface, that I mean to extend, have some special features?

答: One needs to understand interface driven programming as next step while understanding an interface. It tell what is actual use of interface. What role it plays in a Java (or any other language) program.</p>

Title: Who extends interfaces? And why?


答: Technically, I don't believe it's still considered a singleton pattern unless you expose the instance to other classes.  It's just a private static member.  That being said, in general the smaller the scope of a variable, the better.  If other classes don't need it, don't share it.  However, in most cases it's going to be much simpler just to instantiate the static member at declaration instead of checking everywhere if it's already been instantiated.</p>

Title: Hide or Show singleton?

Body:
Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such:

C#:    MyClass.Instance

Java: MyClass.getInstance()

The question is: when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible?

Here are the alternatives for illustrative purposes:

Exposed(C#):

```<code>private static MyClass instance;
public static MyClass Instance
{
    get {
        if (instance == null)
            instance = new MyClass();
        return instance;
    }
}

public void PerformOperation() { ... }
</code>```

Hidden (C#):

```<code>private static MyClass instance;

public static void PerformOperation()
{
    if (instance == null)
    {
        instance = new MyClass();
    }
    ...
}
</code>```

EDIT:
There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario:

My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the Logger class (e.g. Logger.Instance.Warn(...) or Logger.Instance.Error(...) etc. Should I use Logger.Warn(...) or Logger.Warn(...) instead?

If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you :)


问:
Is Visual C++ Redistributables backward compatible?
I am including two programs in my software. One of which requires VC10 and the other requires VC11. My question is that if program developed for VC10 will work on VC11 or I have to include both VC10 and VC11</p>

答:
I tried running a software designed for VC10 in a fresh installation of windows 7 in virtual box with only VC11 installed and it doesn't work. It worked later after I installed VC10.

Hence, the short asnswer is:

No


答:
A lot of people who know eval is dangerous on the server side also reflexively shun it on the client side.  There is a huge difference.  It is not a security hole to be able to execute your own arbitrary code on your own computer.  The only time to be concerned about eval security on the client side is if you're using it to execute code from an untrusted third party, for example from email or a twitter feed.

However, there are other factors to consider.  The eval solution is going to be much simpler for basic functionality, but much more difficult to add things like useful error messages.  You may end up implementing your own parser anyway to add those sorts of features.

There are also performance considerations, but I think the difference is likely to be negligible.  eval will probably have higher startup times, but faster execution times.

Personally, I would use eval for a tool for my own use or within my company, for its simplicity of development.  For wider distribution, I would want the polish a custom parser can provide.


问:
License Requirements for Including Dual-Licensed Open-Source Software
How do you opt into one software license and not the other when the distributor gives the consumer more than one choice?

For example I would like to use the DataTables JavaScript library in my web application. According to their web site, "DataTables is dual licensed under the GPL v2 license or a BSD (3-point) license."

Furthermore, the source code of the JavaScript library has this text that calls out both licenses:

```<code>/**
 * @summary     DataTables
 * @description Paginate, search and sort HTML tables
 * @version     1.9.4
 * @file        jquery.dataTables.js
 * @author      Allan Jardine (www.sprymedia.co.uk)
 * @contact     www.sprymedia.co.uk/contact
 *
 * @copyright Copyright 2008-2012 Allan Jardine, all rights reserved.
 *
 * This source file is free software, under either the GPL v2 license or a
 * BSD style license, available at:
 *   http://datatables.net/license_gpl2
 *   http://datatables.net/license_bsd
 *
 * This source file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */
</code>```

Finally, the web pages with the licensing text (e.g. the DataTables BSD license page) has this statement: "DataTables is made available under both the GPL v2 license and a BSD (3-point) style license. You can select which one you wish to use the DataTables code under."

My specific question is "how do you select which one you want to use." In my case, I want to only use the BSD license and I want to make it explicitly clear that I do not opt into the GPL v2 license in any way.

How do you do that and have it hold up to legal challenge?

答:
My specific question is "how do you select which one you want to use." In my case, I want to only use the BSD license and I want to make it explicitly clear that I do not opt into the GPL v2 license in any way.

You just do. Unless you don't change the source-code there, you don't even need to touch the plate. It can be stayed as is, yes, even touching it for no reason might look more suspicious then just leaving it as-is.

The licenses are offered to you btw. Into which one you opt, you can say anytime, you can choose anytime which one. The one day you might like BSD and the other day you might even use GPL. Both is possible. You can even choose both, even if they both would be incompatible to each other. Only based on the fact the original author(s) did dual-license it.

How do you do that and have it hold up to legal challenge?

No-one can predict the future, but keep references of the websites of today, so that you can document that you've taken care and you can back-up your statement that the dual-license is disjunctive (OR) and not conjunctive (AND).

As long as it's clear that you were allowed to use the software under the terms of the BSD license (and you fulfilled the requirements) I see no reason why it shouldn't hold up a legal challenge, I can not even imagine of which kind such a legal challenge would be?


问:
Continuous integration testing server: hosted, own desktop, or own server
For testing, I am planning to run a continuous integration testing. There are mainly two options: hosted, or own desktop/server. I will break it into 3 options I have:

Hosted:

Economical, $10-20/month for a small app

Less setup, the CI company manage all hardware and software

Desktop:

I could just buy a simple, cheap desktop as a test server (about $500).

Used server:

My current office is offloading some old Dell rack server (Probably dual core Xeon, which I can purchase for $50 or less

Please advise me which best serves me for a small team of 2-3 developers. Thanks.

答:
Economical... $20 per month, or $50 total for the Dell... sounds like that's the best option so far, especially when you don't need reliability (ie if it breaks, you buy new bits and rebuild, or re-evaluate your options then).

Personally, I'd reuse an old desktop machine - if it was good enough for development, its good enough for automated testing, and if you're anything like most shops, you'll have loads of old ones lying around from the last time you bought new PCs for the devs.


问:
Concept of bit fields
Whenever I read a code like this:

```<code>  struct node
  {
          int x : 2;
          int p : 4;
   }n;
</code>```

with bit fields involved, I get really confused, as to how they are represented in memory, what is sizeof(n) etc., how does it differ with normal members of structures? I tried referring K&R and http://en.wikipedia.org/wiki/Bit_field but they little to remove my confusion. What concepts of bit fields am I failing to grasp?

答:
Correct, whenever a bit field is used, everyone gets confused. Because bit fields are very poorly specified by the standard and can have pretty much any memory layout imaginable.

what is sizeof(n)

Nobody knows, including the C standard committee.

how does it differ with normal members of structures?

Normal structures have well-defined behavior. Apart from the case of struct padding, you can always predict how a normal structure is stored in memory. For bit fields, all bets are off.

Detailed info here.

The solution is to never use bit fields. It is a superfluous and dangerous part of the C language.

Title: Concept of bit fields


问:
Should testers approve releases, or just report on tests?
Does it make sense to give signoff authority to testers? Should a test team

Just test features, issues, etc, and simply report on a pass/fail basis, leaving it up to others to act on those results, or

Have authority to hold up releases themselves based on those results?

In other words, should testers be required to actually sign off on releases? The testing team I'm working with feels that they do, and we're having an issue with this because of "testing scope creep" -- the refusal to approve releases is sometimes based on issues explicitly not addressed by the release in question.

答:
Giving sign-off authority (i.e. a veto right) for releases to testers makes as much sense as giving that right to developers: none at all.

Testers and developers are primarily technical people, so they are likely to make their decisions mostly technical grounds.
But, the concerns that need to be weighed when making a release are both technical and business concerns. Obviously, the customer won't be happy if you deliver a bug-ridden product, but the customer will be equally unhappy if you keep postponing a release because there are still open issues on the product.

Someone needs to find the right balance between a good product and keeping to the schedule that was promised to the customer. To do that, you should not be involved in the project in a purely technical role, but rather in a more business/management oriented role like project manager or product owner and take your input from the testers and the developers.


答:
Most places I have worked the QA people do have some sort of sign-off step, but do not have final authority on if the release proceeds or not.  Their sign-off represents that they completed the testing expected by the release plan, not that the release is flawless.

Ultimately QA != the business and the business needs to decide if they are OK with deploying the code in the current state or if the benefit outweighs the downside or whatever.  This is often done by clients or stakeholders immediately prior to deploy and is often called User Acceptance.

If your QA is also your User Acceptance group then there is the potential that they do have the authority to define your release candidate as unacceptable, but if you are getting this over issues that are out of scope to the bugfix/iteration/sprint/change request/whatever you bucket your time in, then the Project Manager or the business line stakeholders needs to have a come to Jesus meeting with the QA team.

It is fine to report on preexisting defects or unintended outcomes of new requirements, but if it is out of scope and non-disastrous it is generally not acceptable to label it as a blocking issue. It goes in the backlog for the product owner to prioritize like everything else.

Title: Should testers approve releases, or just report on tests?

Body:
Does it make sense to give signoff authority to testers? Should a test team

Just test features, issues, etc, and simply report on a pass/fail basis, leaving it up to others to act on those results, or

Have authority to hold up releases themselves based on those results?

In other words, should testers be required to actually sign off on releases? The testing team I'm working with feels that they do, and we're having an issue with this because of "testing scope creep" -- the refusal to approve releases is sometimes based on issues explicitly not addressed by the release in question.


答:
I've worked with the same situation of testers over-reaching and inventing ever more creative ways of breaking a system which, when risk assessed, are incredibly unlikely to ever happen in production.

While I understand and commend the test team for not wanting to send out imperfect release, it does require strong product ownership to define what is an "acceptable risk".

In my experience, the test team should be given a veto on releasing software but this veto should be overridable by the product owner but only after discussion with the lead testers.

Software will never be perfect, if you're suffering from test creep then you'll never get anything released until there's a major production issue (which won't be tested correctly) and rushed out.


答:
Someobody needs that authority. Whether it is a tester, the team of testers, the leader of the team of testers, or the leader of the development organization is somewhat irrelevant. Or perhaps more accurately, it depends on the organization.

Ultimately, the choice to release software is a business function. The business has to decide whether the quality is appropriate. Arguably, the director of quality assurance should make that decision, or feed that decision to the appropriate business unit. That all depends on the size of the company, the relative importance of quality, etc.

All that being said, the information used to make the decision starts with the tester. Whether they have the power to stop a release or not, they should feel the responsibility to inform the decision makers when they see something that they think should cause a delay in the release.


问:
What is the middleware pattern?
Here's a Ruby poject that implements the middleware pattern.  From the description, I have no idea what the pattern is, what it's useful for, and why other solutions wouldn't work as well.

What is the middleware pattern, and what are its advantages and drawbacks?

答:
The author of the project you linked describes middleware as a "state engine" for business logic, akin to Windows Communication Foundation.  That's not the usual definition for middleware (software that glues two or more heterogenous applications together), and I don't think the "middleware pattern" is really a thing.

I think the author is playing a bit fast and loose with his terminology.

Title: What is the middleware pattern?

ContentLicense: CC BY-SA 4.0


问:
How are design-by-contract and property-based testing (QuickCheck) related?
Is their only similarity the fact that they are not xUnit (or more precisely, not based on enumerating specific test cases), or is it deeper than that?

Property-based testing (using QuickCheck, ScalaCheck, etc) seem well-suited to a functional programming style where side-effects are avoided. On the other hand, Design by Contract (as implemented in Eiffel) is more suited to OOP languages: you can express post-conditions about the effects of methods, not just their return values.

But both of them involve testing assertions that are true in general (rather than assertions that should be true for a specific test case). And both can be tested using randomly generated inputs (with QuickCheck this is the only way, whereas with Eiffel I believe it is an optional feature of the AutoTest tool).

Is there an umbrella term to encompass both approaches? Or am I imagining a relationship that doesn't really exist.

答: The relationship is that the combination of design by contract and the testing methods are attempting to substitute for a correctness proof, which would be the ultimate goal, if it were feasible. Pre-conditions and post-conditions (for return values) are useful even in methods with no side effects, as they limit input domains and output ranges.</p>


答:
Based on what I can tell from the example, it basically allows an arbitrary set of pre-action and post-action hooks that are chained in a defined way (hence, you build the stack it goes through) on a particular initial state of an input (in this case, nil, but there's no requirement for it to be such).

Their motivation appears to be in the context of HTTP requests where you might alter request/response properties in any given way. I don't think this pattern is overly useful in the general sense (and calling it "middleware" is certainly a misappropriation).

The advantage appears to be separation of concerns - e.g. something handles the generalized system for hooking and chaining operations to an input. Any subscription to this service could easily be deployed in other contexts and plugged right into a sequence of operations. It's also easy to guess the side effects of inserting any particular operation into the chain - as long as it's done statically.

The disadvantage to me would be that the context is completely removed - it's not clear what you're operating on without a strong naming convention or what the impact of any change to the subscribers is without understanding the context. You would have to put both the caller context and what it does into the naming convention in order to have it be understandable from both sides.

To me, it feels like it would be better to represent the operations as a whole concept; e.g. setting all properties in one spot. I can see the need for perhaps some portion of the application to inject properties and it's a much more interesting usage, for example, maybe in the context of an HTTP request you have something that changes the response type to XML while it's spitting out XML.

However, the way this is set up, you'd have to ensure that was the only spot setting the response type, the only one that will for a particular request, or just the last one which would overwrite any that came before it. Otherwise you'd run into issues.

I'm not sure that solving the problem this way is a compelling pattern, but I fully concede that might be because I looked at and thought about it for 30 minutes. I'm guessing somebody put more time than that into making it, so there could be things I'm missing.

Title: What is the middleware pattern?

Body:
Here's a Ruby poject that implements the middleware pattern.  From the description, I have no idea what the pattern is, what it's useful for, and why other solutions wouldn't work as well.

What is the middleware pattern, and what are its advantages and drawbacks?


问:
Vernon's book Implementing DDD and modeling of underlying concepts
Following questions all refer to examples presented in Implementing DDD

In article  we can see from Figure 6 that both BankingAccount and PayeeAccount represent the same underlying concept of Banking Account BA

1. On page 64 author gives an example of a publishing organization, where the life-cycle of a book goes through several stages ( proposing a book, editorial process, translation of the book ... ) and at each of those stages this book has a different definition.

Each stage of the book is defined in a different Bounded Context, but do all these different definitions still represent the same underlying concept of a Book, just like both BankingAccount and PayeeAccount represent the same underlying concept of a BA?

2.

a) I understand why User shouldn't exist in Collaboration Context ( CC ), but instead should be defined within Identity and Access Context IAC ( page 65 ). But still, do User ( IAC ), Moderator ( CC ), Author ( CC ),Owner ( CC ) and Participant ( CC ) all represent different aspects of the same underlying concept?

b) If yes, then this means that CC contains several model elements ( Moderator, Author, Owner and Participant ), each representing different aspect of the same underlying concept ( just like both BankingAccount and PayeeAccount represent the same underlying concept of a BA ).

But isn't this considered a duplication of concepts ( Evan's book, page 339 ), since several model elements in CC represent the same underlying concept?

c) If Moderator, Author ... don't represent the same underlying concept, then what underlying concept does each represent?

3. In an e-commerce system, the term Customer has multiple meanings ( page 49 ): When user is browsing the Catalog, Customer has different meaning than when user is placing an Order.

But do these two different definitions of a Customer represent the same underlying concept, just like both BankingAccount and PayeeAccount represent the same underlying concept of a BA?

UPDATE:

2.

2a) As with the book, they refer to the same identity but express
  different aspects of that identity in a specific context. Sort of like
  a single object implementing multiple interfaces which embody the
  roles that object plays.

a) Does having two model elements ( both within same BC ) , each representing different aspect of the same underlying concept, result in what Evans calls duplicate concepts?

b) I thought terms "representing different aspects of an identity within particular BC" and "representing different aspects of the same underlying concept within particular BC" are interchangeable ( ie they mean the same thing )? If not, how do they differ?

c)

Sort of like a single object implementing multiple interfaces which
  embody the roles that object plays.

I assumed each role represents a particular aspect of the underlying concept, but you're saying it doesn't? What then does role model and how is the thing that role models conceptually different from an aspect of the underlying concept?

2. UPDATE:

2.

a)

Does having two model elements ( both within same BC ) , each
    representing different aspect of the same underlying concept, result
    in what Evans calls duplicate concepts?

I don't recall what Evans called duplicate concepts so not sure.

On page 339 Evans describes Duplicate concepts as being one of the two conceptual splinters that cause the unification of a model to break down. Here's the quote:

Combining elements of distinct models causes two categories of
  problems: duplicate concepts and false cognates. Duplication of
  concepts means that there are two model elements ( and attendant
  implementations ) that actually represent the same concept. Evry time
  this information changes, it has to be updated in two places with
  conversions. Every time new knowledge leads to a change in one of the
  objects, other has to be reanalyzed and changed too. Except the
  reanalysis doesn't happen in reality, so the result is two versions of
  the same concept that follow different rules and even have different
  data.

b) and c)

This may be a linguistic issue. The way I see it, an identity can have
  different concepts associated with it depending on the context.

Again this seems to be a linguistic issue. You use "underlying
  concept" to refer to identity which I think isn't clear enough to
  distinguish from simply "concept" which by itself isn't sufficient.

Perhaps the following will make my questions clearer: By underlying concept I'm referring to an aspect of reality ( ie the thing ) which we try to model.

thanks

答:
1) The models of books in different stages refer to the same book. I wouldn't say that they refer to the same underlying concept because the concepts are different in the different contexts. They do refer to the same book in that the identity of the book is shared among the BCs.

2a) As with the book, they refer to the same identity but express different aspects of that identity in a specific context. Sort of like a single object implementing multiple interfaces which embody the roles that object plays.

2b) It isn't duplication of concepts because the concepts are different, only the identity is shared. Remember, the goal of DDD and programming in general is to create a model of your domain. All models are incomplete, but good models provide utility.

2c) You can say that a Moderator is a role played by a user in a specific context.

3) Same as above. They refer to the same identity, the same person, but different roles.

UPDATE

Does having two model elements ( both within same BC ) , each
  representing different aspect of the same underlying concept, result
  in what Evans calls duplicate concepts?

I don't recall what Evans called duplicate concepts so not sure.

I thought terms "representing different aspects of an identity within
  particular BC" and "representing different aspects of the same
  underlying concept within particular BC" are interchangeable ( ie they
  mean the same thing )? If not, how do they differ?

This may be a linguistic issue. The way I see it, an identity can have different concepts associated with it depending on the context.

I assumed each role represents a particular aspect of the underlying
  concept, but you're saying it doesn't? What then does role model and
  how is the thing that role models conceptually different from an
  aspect of the underlying concept?

Again this seems to be a linguistic issue. You use "underlying concept" to refer to identity which I think isn't clear enough to distinguish from simply "concept" which by itself isn't sufficient.


问:
Is a finite state machine an appropriate solution for this situation?
I was writing some test code as an example where I had a washing machine class. It has a door state that should be open or closed, and also a running state, either on or off. I want to prevent the running state from changing from 'off' to 'on' when the door is 'open', and also prevent the door from being set to 'open' while the machine is 'on'.

I have this functionality rigged up with a bunch of if statements. It feels inelegant and it could quickly turn into spaghetti code if I want to add another state that puts additional conditions on the changes of other states. I wonder, is a finite state machine a solution for this situation? Would it simplify adding states and defining valid transitions?

答:
What you are experiencing is called 'Code Smell' and is a good indicator that you might be doing something wrong. Luckily though, you saw the problem and already came up with a great solution, so there's not much for me to say here. A state machine works perfectly for what you're doing here.

Drawing it out might also help to try and find other states you might not think of (Running, spin cycle, cool down, filling), as well as allowing you to define transition requirements between states (probably don't want to let the door open during the spin cycle, but maybe the filling state allows the door to be opened to add garments).

Obviously you can be as detailed or ambiguous as you want, do as much as fits your needs!


答:
This really depends on which ContinuousIntegration solution you are using, as well as how much you'll be using it.

For example, many CI hosted solutions are very cheap or even free for just a few users, a few jobs, and a single build agent. But their hosting gets much more expensive when you start talking about lots of jobs and lots of build agents.

So, while hosting might be cheaper initially, it could get expensive very quickly. I'd install the CI software on an old desktop machine, and build out your self-hosted solution as needed. But that's just me, for some people the hosting costs are worth the savings in system configuration headaches.

Title: Continuous integration testing server: hosted, own desktop, or own server

Body:
For testing, I am planning to run a continuous integration testing. There are mainly two options: hosted, or own desktop/server. I will break it into 3 options I have:

Hosted:

Economical, $10-20/month for a small app

Less setup, the CI company manage all hardware and software

Desktop:

I could just buy a simple, cheap desktop as a test server (about $500).

Used server:

My current office is offloading some old Dell rack server (Probably dual core Xeon, which I can purchase for $50 or less

Please advise me which best serves me for a small team of 2-3 developers. Thanks.


问:
Why use JSP instead of servlets?
(Rewritten for reopening:)

What are relative advantages of Servlets over JSP, or vice versa?

Might JSP be preferred because it is easy to put code inside JSP, or Servlets because with them code can be separated from view? Are there other considerations?

Any information regarding this will be immensely helpful.

答:
The main advantage of JSP is that it's are easier to code and to read when you are creating a dynamic HTML front-end.

That's because you write mainly HTML and in some places embed Java code.

In a servlet you would have to invert the logic, ie, write java code and print HTML.

That's because in the presentation layer most code is HTML/JS.

On the other hand, business logic is in most part Java code, so in that case it's better to use Servlets or POJOs (plain, old Java objects).

EDIT: there's no performance difference since JSP code, as such, is never run, it's converted to a servlet. Only the first time you run the JSP after it has been changed, it takes a little longer to run because it has to be converted to servlet.

Compare a simple "Hello World" program in JSP vs servlet:

JSP:

```<code><html>
        <head><title>Hello World JSP Page.</title></head>
        <body>
                <font size="10"><%="Hello World!" %></font>
        </body>
</html>
</code>```

Servlet

```<code>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

    public class HelloWorld extends HttpServlet{
      public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException,IOException{
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<html>");
      pw.println("<head><title>Hello World</title></title>");
      pw.println("<body>");
      pw.println("<h1>Hello World</h1>");
      pw.println("</body></html>");
      }
    }
</code>```

Title: Why use JSP instead of servlets?

Body:
The main advantage of JSP is that it's are easier to code and to read when you are creating a dynamic HTML front-end.

That's because you write mainly HTML and in some places embed Java code.

In a servlet you would have to invert the logic, ie, write java code and print HTML.

That's because in the presentation layer most code is HTML/JS.

On the other hand, business logic is in most part Java code, so in that case it's better to use Servlets or POJOs (plain, old Java objects).

EDIT: there's no performance difference since JSP code, as such, is never run, it's converted to a servlet. Only the first time you run the JSP after it has been changed, it takes a little longer to run because it has to be converted to servlet.

Compare a simple "Hello World" program in JSP vs servlet:

JSP:

<html>
        <head><title>Hello World JSP Page.</title></head>
        <body>
                <font size="10"><%="Hello World!" %></font>
        </body>
</html>

Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

    public class HelloWorld extends HttpServlet{
      public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException,IOException{
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<html>");
      pw.println("<head><title>Hello World</title></title>");
      pw.println("<body>");
      pw.println("<h1>Hello World</h1>");
      pw.println("</body></html>");
      }
    }


答:
The decision to 'release' or 'not to release' is at the end of the day a business decision, where a rigorous risk/reward analysis needs to be performed.

It is insane for any organization to ask the test team to take on this responsibility or for the test team to agree to this responsibility.

The role of the test team is to provide an analysis of the quality of the software, its readiness to be released, and any risks identified as an input to the business decision to release or not to release.

As others have noted, _somebody_ (and I believe it is an individual) does need the authority to make the 'release' or 'not to release' decision. That same person can have delegated that decision under specific conditions (i.e. no P1 or P2 Bugs)


问:
Is sticking to one language on a particular project a good practice?
I'm developing a pipeline for processing text that will go into production. The question I keep asking myself is: should I stick to one language for the project when I'm looking for a tool to do a particular task (e.g. NLTK, PDFMiner, CLD, CRFsuite, etc.)?

Or is it OK to mix and match languages on the project?  So I pick the best tool regardless of what language it's written in (e.g. OpenNLP, ParsCit, poppler, CFR++, etc.) and warp (wrap) my code around it?

Note, I am not asking about should a developer stick to just one language for their career.

答:
In a perfect world, we'd all be using the One True Language™.  The reality is somewhat different.

If you insist on a single language, you may be be excluding many tools from your toolbelt, regardless of the language you choose.

Some applications are impossible or impractical to write in a single language.  Web applications are a good example of this; unless you want to write a web server in node.js you're almost certainly going to be using different programming languages for the client and server.

By limiting yourself to one language, you are depriving yourself of paradigms, software patterns and other ideas that are present in other languages, some of which you can apply to your language of choice once you learn them.

In practice, however, there's a lot one can do on a single platform.  Most of the popular programming ecosystems have a wealth of tools available in their native language; choose language interop only when you must have functionality that you can't get any other way.


问:
Is C++ suitable as a first language?
A local college is teaching C++ to first year college students (16 years old) with no prior programming experience.

As first programming language, is C++ suitable?

答:
If "suitable" stands for "possible", yes. If for "good", definitely no.

It's possible to like, even love C++, but for that you better learn several languages and work some decade with teal-life rotten codebases, get experience on "crafting nontrivial software that works actually" -- then C++ will have charm.

Not at start when you are virgin, fiddle with small, simple (but supposedly interesting and fun) problems.

I'd start with python, followed by SICP (scheme), or something similar. Maybe reversed or interleaved. With those you can just go and deal with the problem. Instead of fighting the system, walking in deep mud and learn all kinds of illogical quirks and their historical reasons.

Later, when you already can program your way out of a paper bag, switch to bare metal: learn ways of assembly and several architectures, plus maybe Knuth's Mix. I don't mean memorizing opcodes or do much real stuff, just to understand memory, registers, the ALU, caches, interrupts, and get on read level.

Then with that foundation you can be exposed to other languages, including C++. Maybe a good idea to add some "history and evolution of languages" in between.

ContentLicense: CC BY-SA 2.5

Title: Is C++ suitable as a first language?


问:
RESTful applications logic and cross resource operations
I have an RESTful api that allows my users to receive enquiries about their business e.g. 'I would like to book service x on date y. Is this available?'. The api saves this information as a resource to the following URI

```<code>users/{userId}/enquiries/{enquiryId}
</code>```

The information shown when this resource is retrieved are the standard sort of things you'd expect from an enquiry - email, first_name, last_name, address, message

The api also allows customers to be created for a user. The customer has a login and password and also a profile. The following URIs expose these two resources

```<code>PUT users/{userId}/customers/{customerId}
PUT users/{userId}/customers/{customerId}/profile
</code>```

The problem I am having is that I would like to have the ability to allow users to create a customer from an enquiry. For example, the user is able to offer their service on the date requested and will then want to setup a customer with login details etc to allow them to manage the rest of the process.

The obvious answer would be to use a URI like

```<code> users/{userId}/enquiries/{enquiryId}/convert-to-client
</code>```

The problem with this is is that it somewhat goes against a lot of what I've been reading about how to implement REST (specifically from the book Restful Web Services which suggests that URIs should point to resources not operations on resources).

The other option would be to get the client application (i.e. the code that calls the api) to handle some of this application logic. This doesn't quite feel right to me. I have implemented in my design that the client app is fairly dumb. It knows just enough to display the results from the API, and does not contain any application logic.

Would be great to hear what others views are on the best way of setting this up

Am I wrong to have no application logic in the client app? How would I perform this operation purely in the REST api?

答:
The problem with this is is that it somewhat goes against a lot of what I've been reading about how to implement REST (specifically from the book Restful Web Services which suggests that URIs should point to resources not operations on resources).

This is correct because the following operation that you suggested in your question would only be appropriate for a SOAP service.  REST encourages that you not declare the service as an action of a resource in any way.  The HTTP protocol defines the operation on the resource with GET, POST, PUT, DELETE, etc...

To be REST you perform an HTTP operation on a resource, and the result of this returns a Representation of said Resource (Get it?  Representational State Transfer).  If the client would like to GET an enquiry, they must change the representation of that resource and send that data back to the server.  While you may be concerned about implementing this modification of data on the client, this is inherently not counter to any constraints defined by REST.

Source: Wikipedia: Representational State Transfer - Constraints

Code on demand (optional)
  Servers can temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.

It is perfectly acceptable then to assume that a JSON object implemented in a proper Object-Oriented way will have defined script behavior about how to transform its data in a state that can be posted back to the server in order to convert it into a client.  This functionality may not need to be complex, perhaps it is even just a property of the JSON object itself that when it POSTs back that the server understands it is to be converted.

The catch really is that the representation of this resource will change and this must be communicated or documented clearly to the clients of the service.


问:
Why, in WPF, do we set an object to Stretch via its Alignment properties instead of Width/Height?
In WPF's XAML, we can tell an element to fill its container like this:

<Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
```

Why is it that when we set an element to Stretch, we do it via the HorizontalAlignment and VerticalAlignment properties? Why did the WPF design team decide to take this approach over having Width="Stretch" and Height="Stretch"? I presume it was a calculated decision, and I'm curious about the reasoning.

CSS, among other technologies, follows the convention that stretching is done via the width and height properties, and that alignment affects positioning exclusively. This seems intuitive enough: stretching the element is manipulating its width and height, after all! Using the corresponding alignment property to stretch an element seems counter-intuitive and unusual in comparison. This makes me think they didn't just pick this option for no reason: they made a calculated decision and had reasons behind it.

Width and Height use the double data type, which would ordinarily mean assigning it a string would be silly. However, WPF's Window objects can take Width="Auto", which gets treated as double.NaN. Couldn't Width="Stretch" be stored as double.PositiveInfinity or some other value?

答:
Because double.NaN and double.PositiveInfinity already have very specific meanings. It's pretty bad practice to repurpose special values like that in a completely different context, where it would have significantly different meaning. Just because an element cannot be NaN or PositiveInfinity (or for that matter -1) units wide doesn't mean you should reuse that value arbitrarily to mean something else. Suppose you calculated the with of an element dynamically, NaN or PositiveInfinity would still represent a division by zero and means something is wrong with the calculation, not that element should stretch.

It's true that WPF allows you to specify Width="Auto" which gets stored internally as NaN, however I would argue that this is indeed bad design (or at least not very good design—at least "Auto" is indeed not a number), for the reasons listed above. I can't say why the WPF team chose to allow one special value, and not the other, except that perhaps it was simply the best option to keep their layout algorithms simple and flexible. NaN has the added benefit that any arithmetic operations performed on it remain NaN, while many operations on PositiveInfinity result in NaN. This may make NaN more suitable for storing special values than PostitiveInfinity.

A much better solution can found in GridLength structure, which represents discreet measurements and special values (such as * and auto) appropriately. The designers of WPF could have used a similar structure to represent the width / height of all framework elements, but that would likely have made most of even the most basic layout algorithms much more difficult.


问:
Why do we use networking libraries instead of plain NSURLRequests and NSURLConnection ?
in iOS development, I have often seen people creating a networking module to interact with their APIs.

This module generally sits on top of a networking framework  like MKNetWorkKit or AFNetWorking.

In most of the cases, It's all about sending GET,POST request and parsing the response which is in most cases JSON.

What extra practical benefits that these libraries provide that an iOS developer should be leveraging which the plain Cocoa Networking APIs lack ?

I can understand RESTKit as one exception where it takes care of the conversion of JSON to native objects and also interfaces with Core Data but what about others ?

答:
One of the goals may be to abstract the way the network data is accessed.

Such abstraction can be very abstract:

```<code>public loadProducts(currentCategory) returns list of Product {
    var productsFactory = dataAccess.factory.createProductsFactory();
    var productsOfCategory = productsFactory.loadProducts(currentCategory);
    return productsOfCategory;
}
</code>```

Here, the caller don't know if products are loaded from a database, an XML file, a REST request or something completely different. It makes it very easy to replace one data source by another, for example migrate all data from a REST service to a database.

Or the abstraction may be more transparent:

```<code>public doPostRequest(parameters) returns Stream {
    ... // Use library A to do the request. if you need to switch to library B later, this
        // is not an issue.
}
</code>```

Here, the caller knows that the library is using a network resource. While being transparent, such library can still be useful when migrating from one way to do HTTP requests to another.

In .NET Framework, for example, there are at least three ways to do HTTP requests, not counting all the third party libraries one can use. Picking one way and sticking with it is a solution, but later, migrating to another implementation would be painful. Another solution is to create your own layer, abstracting the actual implementation: if a new version of .NET Framework will be released and you want to use a new way of doing HTTP requests, you change the code in one place.

Body:
One of the goals may be to abstract the way the network data is accessed.

Such abstraction can be very abstract:

public loadProducts(currentCategory) returns list of Product {
    var productsFactory = dataAccess.factory.createProductsFactory();
    var productsOfCategory = productsFactory.loadProducts(currentCategory);
    return productsOfCategory;
}

Here, the caller don't know if products are loaded from a database, an XML file, a REST request or something completely different. It makes it very easy to replace one data source by another, for example migrate all data from a REST service to a database.

Or the abstraction may be more transparent:

public doPostRequest(parameters) returns Stream {
    ... // Use library A to do the request. if you need to switch to library B later, this
        // is not an issue.
}

Here, the caller knows that the library is using a network resource. While being transparent, such library can still be useful when migrating from one way to do HTTP requests to another.

In .NET Framework, for example, there are at least three ways to do HTTP requests, not counting all the third party libraries one can use. Picking one way and sticking with it is a solution, but later, migrating to another implementation would be painful. Another solution is to create your own layer, abstracting the actual implementation: if a new version of .NET Framework will be released and you want to use a new way of doing HTTP requests, you change the code in one place.


答:
What extra practical benefits that these libraries provide that an iOS
  developer should be leveraging which the plain Cocoa Networking APIs
  lack ?

Error handling, ease of use, simplified code, etc. NSURLConnection is a great class and very flexible, but if you take a look at NSURLConnectionDelegate you'll see that there are quite a few different network states that have to be handled. A good networking library takes care of much of that routine work.

Title: Why do we use networking libraries instead of plain NSURLRequests and NSURLConnection ?

Body:
in iOS development, I have often seen people creating a networking module to interact with their APIs.

This module generally sits on top of a networking framework  like MKNetWorkKit or AFNetWorking.

In most of the cases, It's all about sending GET,POST request and parsing the response which is in most cases JSON.

What extra practical benefits that these libraries provide that an iOS developer should be leveraging which the plain Cocoa Networking APIs lack ?

I can understand RESTKit as one exception where it takes care of the conversion of JSON to native objects and also interfaces with Core Data but what about others ?


答:
I highly recommend reading RESTful Webservices, especially the chapters on the difference between RESTful and RPC style web programming; and the chapters on resource discovery and how to deal with the apparent need for "verbs" (they are usually a different resource in disguise).

Converting an enquiry to a customer does not need a "convert" verb. You wouldn't delete the enquiry just because you create a customer and thus you are simply creating a customer with the information from the enquiry as input.

```<code>POST /users/{userId}/customers?enquiry={EnguiryId}
</code>```

or simply

```<code>POST /users/{userId}/customers
</code>```

with the enquiry information in the request body.

By the way, I use POST on customers because that is the way to do it if the server application is in control of the identifier generation. Only use PUT to create resources if the caller is the one determining the identifiers.

On a side note: have you considered the security and privacy issues relating to including /users/{UserId} in your URI's? Anybody can now start trying different userid's to get at information of different users of your application. You really should consider leaving them off your URI's and having them determined by the authentication information that should be send with each request (and possibly refreshed with each response).

Title: RESTful applications logic and cross resource operations

Body:
I have an RESTful api that allows my users to receive enquiries about their business e.g. 'I would like to book service x on date y. Is this available?'. The api saves this information as a resource to the following URI

```<code>users/{userId}/enquiries/{enquiryId}
</code>```

The information shown when this resource is retrieved are the standard sort of things you'd expect from an enquiry - email, first_name, last_name, address, message

The api also allows customers to be created for a user. The customer has a login and password and also a profile. The following URIs expose these two resources

```<code>PUT users/{userId}/customers/{customerId}
PUT users/{userId}/customers/{customerId}/profile
</code>```

The problem I am having is that I would like to have the ability to allow users to create a customer from an enquiry. For example, the user is able to offer their service on the date requested and will then want to setup a customer with login details etc to allow them to manage the rest of the process.

The obvious answer would be to use a URI like

```<code> users/{userId}/enquiries/{enquiryId}/convert-to-client
</code>```

The problem with this is is that it somewhat goes against a lot of what I've been reading about how to implement REST (specifically from the book Restful Web Services which suggests that URIs should point to resources not operations on resources).

The other option would be to get the client application (i.e. the code that calls the api) to handle some of this application logic. This doesn't quite feel right to me. I have implemented in my design that the client app is fairly dumb. It knows just enough to display the results from the API, and does not contain any application logic.

Would be great to hear what others views are on the best way of setting this up

Am I wrong to have no application logic in the client app? How would I perform this operation purely in the REST api?

Body:
I highly recommend reading RESTful Webservices, especially the chapters on the difference between RESTful and RPC style web programming; and the chapters on resource discovery and how to deal with the apparent need for "verbs" (they are usually a different resource in disguise).

Converting an enquiry to a customer does not need a "convert" verb. You wouldn't delete the enquiry just because you create a customer and thus you are simply creating a customer with the information from the enquiry as input.

POST /users/{userId}/customers?enquiry={EnguiryId}

or simply

POST /users/{userId}/customers

with the enquiry information in the request body.

By the way, I use POST on customers because that is the way to do it if the server application is in control of the identifier generation. Only use PUT to create resources if the caller is the one determining the identifiers.

On a side note: have you considered the security and privacy issues relating to including /users/{UserId} in your URI's? Anybody can now start trying different userid's to get at information of different users of your application. You really should consider leaving them off your URI's and having them determined by the authentication information that should be send with each request (and possibly refreshed with each response).


答:
Taking into consideration the example you give I have a totally different look on it. The other answers are correct but I think this comes from a wrong starting point.

In fact an enquiry is a coming from a customer. A customer can maybe have multiple enquiries?

When you start to get the need of having a conversion step that means many times you have 2 resources which are about equal.

Why not have only the resource Customer at first. That resource contains all information about the client: email, first_name, last_name, address.

Status now: A Customer without enquiries. So that's a lead (you could add a boolean field for that status).

Then you could define 2 things: You could give the Customer a field with the message (first contact or something could that field be called).

Status now: You have a Customer with a message so you can filter them out and start answering them

Alternatively you create and enquiry for the Customer. So first create customer then enquiry. This could be done by the client, you make ClientId required to create an enquiry.

You could also make these 2 steps in one by allowing to create a new enquiry with optional fields (the customer address fields). That can take both steps at once. I don't particularly like it because it is less simple and in the end you get more complexity for almost no advantages.

Status now: You have a Customer with a related enquiry.

Now you have more Customers in your database then you might like. There you can filter them so you get the right list of clients. It's the same data so I believe it belongs in the same resource.


问:
How to familiarize myself with Python
I'm a Python beginner. I started programming with Python 1.5 months back.

I downloaded the Python docs and read some parts of the tutorial. I have been programming on codechef.com and solving problems of projecteuler. I am thinking of reading Introduction to algorithms and following this course on MIT opencourse ware as I haven't improved much in programming and I am wasting a lot of time thinking just what should I do when faced with any programming problem.

But I think that I still don't know the correct way to learn the language itself. Should I start with the library reference or continue with the Python tutorial? Is learning algorithms useful for languages such as C and not so much for Python as it has "batteries included"?

Are there some other resources for familiarization with the language and in general for learning to solve programming problems? Or do I need to just devote some more time?

答:
I am in a very similar position to you except with C#. I started a job a few weeks ago and I knew I'd be using it so I started reading a lot and doing tutorial, sample projects, etc. Then I was given my first "real" task. I had been struggling but when you have something you have to do or you have a goal that would help outside of just learning it makes it easier.

See if there is a simple thing that you waste a lot of time doing or something you think is a problem that could be solved on your computer; why not see if you could write a little script to do it? You'll learn by doing and I guarantee you'll stumble across some key concepts while doing it and become much more familiar but in a more productive context.

Good luck.

Title: How to familiarize myself with Python


问:
Are the technologies used in an application part of the architecture, or do they represent implementation/detailed design details?
When designing and writing documentation for a project an architecture needs to be clearly defined: what are the high-level modules of the system, what are their responsibilities, how do they communicate with each other, what protocols are used etc. But in this list, should the concrete technologies be specified or this is actually an implementation detail and need to be specified at a lower level?

For example, consider a distributed application that has two modules which communicate asynchronously via AMQP protocol, mediated by a message broker. The fact that these modules use the Spring AMQP library for sending and receiving messages is a fact that needs to be specified in the architecture or is a lower-level detailed design/implementation detail?

答:
Well, it depends.

There are clearly architectural technologies that go directly in an architecture documentation, like CORBA or .NET or a MessageQueue.

If you can have an abstract form of it, e.g. only the interface that multiple implementations support, keep it at the abstract level. If you have it, specify those in the implementation documentation. If you do not have an implementation documentation,
you can specify it in the overall architecture.

On the other hand, there are technologies that probably never go into an architecture documentation, like a certain JSON parser or that like.

On very complex systems, you would have a system specification anyways, which is
more of an overall architecture.

So, on short, I would say:

Architecure: abstract System and concrete component level
Implementation: abstract Component and concrete module level


答:
I started Python a couple of years ago coming from a C background (C/C++/C#). I had the exact same thoughts you do. Although I am no expert I can tell you what helped me arrive where I currently am - feeling quite comfortable with the language while still getting real fun out of it using it for day to day work and feeling like I am learning tons of stuff every day.
Here's what I did:

Read good books on programming fundamentals. There's a lot of them. The one's I particulary remember enjoying while learning Python were Think Python for being a great introductory book, Dive Into Python for pragmatic engineering-aware aproach and the real life examples like Web Services.

Use the Python documentation as a reference for the problems and questions you encounter but always investigate to the fullest. Don't just look something up and fix your code - follow the links and try to understand the full scope of what you are doing.

Read non-python books and material. It is invaluable to understand the language is the finger pointing at the moon. Looking at the finger you will not see the moon ;) I read Algorithms with a Python mindset. I also recommend what I am currently reading - Think like a programmer. It's examples use C++ but if you choose Python for exercising you can't go wrong. It is kind of basic but very valuable.

Read and try to understand the source code of the packages and modules you use. This is the thing I love Python for and think it's THE language designed for learning. All the internals are there for you.

MOST IMPORTANT - try a real life problem. A small webapp for a friend or customer, maybe participate in an open source project. Anything that fulfills a real necessity and you feel that you not only WANT TO but also NEED TO do it.

Keep at it and have fun. That's why I got dedicated to learning Python. It does the job and is fun and educational all the way.

Title: How to familiarize myself with Python

Body:
I'm a Python beginner. I started programming with Python 1.5 months back.

I downloaded the Python docs and read some parts of the tutorial. I have been programming on codechef.com and solving problems of projecteuler. I am thinking of reading Introduction to algorithms and following this course on MIT opencourse ware as I haven't improved much in programming and I am wasting a lot of time thinking just what should I do when faced with any programming problem.

But I think that I still don't know the correct way to learn the language itself. Should I start with the library reference or continue with the Python tutorial? Is learning algorithms useful for languages such as C and not so much for Python as it has "batteries included"?

Are there some other resources for familiarization with the language and in general for learning to solve programming problems? Or do I need to just devote some more time?


问:
How do I know when should I package my classes in Ruby?
In Ruby, I'm creating a small game development framework. Just some personal project - a very small group of friends helping.

Now I am in need of handling geometric concepts. Rectangles, Circles, Polygons, Vectors, Lines, etc. So I made a class for each of these.

I'm stuck deciding whether I should package such classes in a module, such as Geometry. So I'd access them like Geometry::Rectangle, or just Rectangle if I include the module.

Now then, my question isn't about this specific scenario. I'd like to know, when is it suitable to package similar classes into one module in Ruby? What factors should I consider? Amount of classes? Usage frequency? Complexity?

答:
Semantics.

That's the deciding factor you should consider. Your packages must be semantic. If they're all about game logic, regroup them under the GameLogic package. If they're all about geometry, regroup them under the Geometry package.

It's kind of related to the amount of classes/complexity, because if a package becomes too big, it means it's doing too much. So it's time to refactor it.

Nobody can tell you what packages you should make. This is an architectural design decision.

What's the maximum size of a package? Nobody can tell you either. Lot of projects have differing views about this, so just go with what you feel like is the most maintainable. Too small packages means going a lot through files to find your code, too big packages means maintenance headache.


答:
As a software architect, you will have to make decisions what components/technologies are essential for your architecture, and which are "implementation details". For example

is a specific database system part of the high-level architecture? For some applications this may be true, for others it is important to keep the programs independent from the database vendor. Tools like ORMs can help you here, but then you may have to make the architectural decision of choosing a specific ORM.

are the programming language(s) for your system part of the high-level architecture? Well, in most cases you cannot easily switch the language afterwards when you have already written several thousand lines of code, so this will be normally a high-level architectural decision. Of course, I know examples where libraries are written in a DSL  and automatically translated into different programming languages, but that is not the typical case.

should the use of Spring AMQP part of your architecture or an implementation detail? Well, AFAIK AMQP is a standard protocol, and there exist different implementations / libraries supporting it. If you want to keep the option of changing the AMQP library later, you probably want it to be declared as an implementation detail.

In fact, some technologies are easier to be kept "as an implementation detail" as others, and it is often a trade-off between higher flexibility and an increased development effort where to draw the line.

Title: Are the technologies used in an application part of the architecture, or do they represent implementation/detailed design details?

Body:
When designing and writing documentation for a project an architecture needs to be clearly defined: what are the high-level modules of the system, what are their responsibilities, how do they communicate with each other, what protocols are used etc. But in this list, should the concrete technologies be specified or this is actually an implementation detail and need to be specified at a lower level?

For example, consider a distributed application that has two modules which communicate asynchronously via AMQP protocol, mediated by a message broker. The fact that these modules use the Spring AMQP library for sending and receiving messages is a fact that needs to be specified in the architecture or is a lower-level detailed design/implementation detail?


问:
Do logged in users need to browse a site over https?
I've never thought it was necessary, but a client has requested that all webpages served to logged in users be delivered over HTTPS.

Aside from the implementation standpoint, which I don't think I'm going to pursue is there any real reason for this request ?

For clarity, the login / logout process, account settings, registration preferences and all user related scripts are served over https. but I can't see the point in my news articles, press releases, events etc... being served in this manner? Am I missing something ?

答:
This is basic security. Since HTTP is stateless, even if a user is logged in, the browser still needs to effectively re-authenticate for every single page load (otherwise the server has no way of knowing that this particular user is logged in).

The usual ways to do this are via a special cookie, or by including some token in each rendered page (e.g. as a parameter of all links).

No matter how it's implemented, the key point is: Every time the browser requests a page it will have to send some secret session key or similar.

So unless you serve everything over HTTPS, the session of a logged-in user can be hijacked through a man-in-the-middle attack.

More information on Security SE: Can a session be hijacked if the user is redirected from HTTPS to HTTP after login?


问:
Implementing MVC pattern in SWT application
I am developing an SWT application (it's basically an Eclipse plugin, so I need to use SWT). Currently my design is as follows:

Model: In model, I have POJOs which represents the actual fields in views.

View: It is a dumb layer, it contains just UI and contains no logic (not even event handlers)

Controller: It acts as a mediator b/w those two layers. Also it is responsible for creating view layer, handling events etc.

Basically I have created all of the controls in view as a static like this public static Button btnLogin and in controller I have a code like this:

```<code>public void createLoginView(Composite comp) {
    LoginFormView.createView(comp);  //This createView method is in view layer ie LoginFormView
    LoginFormView.btnLogin.addSelectionListener(new SelectionListener() {
        //Code goes here
    });
}
</code>```

Similalrly I have done for other views and controls. So that in main class and other classes I am calling just createLoginView of controller. I am doing similar thing for other views.

So my question, is what I am doing is correct? Is this design good? Or I should have followed any other approach. Since I am new to SWT and Eclipse plugin development (basically I am Java EE developer having 4+ years of exp). Any tips/pointers would be appreciated.

答: I assume you have the eclipse plugin development guide at hand, it does not mention any specific design you should/could follow so I guess as long it it gets the job done. it's good.</p>


问:
Unit test SHA256 wrapper queries
I have the following SHA256 wrapper.

```<code>    public static string SHA256(string plainText)
    {
        StringBuilder sb = new StringBuilder();

        SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider();
        var hashedBytes = provider.ComputeHash(Encoding.UTF8.GetBytes(plainText));

        for (int i = 0; i < hashedBytes.Length; i++)
        {
            sb.Append(hashedBytes[i].ToString("x2").ToLower());
        }

        return sb.ToString();
    }
</code>```

Do I want to be testing it? If so, what do you recommend?

My thought process is as follows:

What logic is there here.

The answer is my for loop and ToString("x2") so from my understanding I want to be testing this part?

I can assume Encoding.UTF8.GetBytes(plainText) works. Correct assumption?
I can assume SHA256CryptoServiceProvider.ComputeHash() works. Correct assumption?

I want to be only testing my logic. In this case is limited to the printing of hex encoded hash. Correct?

Thanks.

EDIT:

Update method based on MainMa's excellent answer:

```<code>    /// <summary>
    /// Returns a SHA256 hash of the plain text.
    /// </summary>
    /// <param name="plainText">The pain text.</param>
    /// <returns>The hash.</returns>
    public static string SHA256(string plainText)
    {
        if (string.IsNullOrWhiteSpace(plainText)) throw new ArgumentNullException("The plain text cannot be empty.");

        StringBuilder sb = new StringBuilder();

        Byte[] hashedBytes;
        using (SHA256CryptoServiceProvider sha256Provider = new SHA256CryptoServiceProvider())
        {
            hashedBytes = sha256Provider.ComputeHash(Encoding.UTF8.GetBytes(plainText));
        }

        foreach(Byte b in hashedBytes)
        {
            sb.Append(b.ToString("x2").ToLower(CultureInfo.InvariantCulture));
        }

        return sb.ToString();
    }
</code>```

答:
In a simple function like this there aren't many tests as unit tests are defined by what output are you expecting the function to return.

You can assume that the built in functions work, but could any of those functions throw an exception based on the input you provide - is that something your function needs to handle?

Tests you might consider - is the resulting string the correct length (if someone comes along and switches SHA256 for another scheme?  Are there failure states and how should the function respond to or report them?

Title: Unit test SHA256 wrapper queries