问:
Distributing PC software without a website
I am trying to distribute a small PC program, but have run into a few problems. I first tried to upload it to cNet, and then to softonic, but the problem with these sites, and all that I have seen like them is that they require a direct link(which I can't get, see below).

After running into that problem, I simply uploaded my software to a file sharing site, but in reality, very few of my current users(from a mobile version)installed my software because once downloaded was listed as dangerous by the anti-virus due to the website that it was downloaded from.

So then I set about trying to find a download website that would give me a direct link, but unsurprisingly, I can't find that. I can't host the file myself, because I don't have a webpage.

Even though I haven't found any, I would be fine with a site that hosts my software and doesn't require a direct download link to use.  Or I would be fine with a site that would give me a direct download link.

I'm interested in an answer to the general problem - distributing software without a website.  I assume that not everyone who has ever released software has their own webpage, what is the best way to get around this?

答:
If it's an open source project intended for developers, GitHub or Codeplex are good places to host your product with the ability to download it.

If it's a library, then most ecosystems have some sort of package managers. For example, Node.js has npm, and .NET Framework has NuGet.

If it's a software application intended for end users, then create a website; there are plenty of companies which provide free or extremely cheap hosting. I can see several benefits in having your own website:

It's hugely extensive.

One day, you want to add a feedback feature? You can do it. Later, you want to publish your source code? You can. Later, you want to track your visitors? No problem. Want to add a YouTube video presenting the product? Do it.

If you stick with any service which does some of those features for you, one day you'll need just another fancy feature the service won't provide.

It's a way to do marketing.

Just a download link? Well, what if I want to discover a bit more about your software and you before downloading it? I don't want my PC be filled by crap written by Mister Anonymous. Knowing that a given person have written the app, seing the screenshots, seeing the video which shows the lead developer explaining why the software is so great would convince me much more.

It's a way to learn.

You're not a web developer, right? Otherwise, probably, you wouldn't have asked this question. Then creating your own website may teach you new things which are damn useful for any developer nowadays. I'm not saying that everyone should know HTML and CSS and SQL and JavaScript, but discovering all those technologies and languages won't hurt anybody.


问:
HasMany RESTfull Implementation
So I've been reading a lot on RESTfull design - specifically dealing with resources.

Taking the canonical example of Users, Posts, and Comments, with relationships as:

Users ---(hasMany)---> Post ---(hasMany)---> Comment

One may initially think to expose something like:

```<code>GET /users               GET /posts               GET /comments
POST /users              POST /posts              POST /comments
GET /users/id            GET /posts/id            GET /comments/id
PUT /users/id            PUT /posts/id            PUT /comments/id
DELETE /users/id         DELETE /posts/id         DELETE /comments/id
</code>```

But then, say I want all Comments of a certain Post made by a particular User. I'd need to do something like:

```<code>GET /users/id
   > someUser
   > var postIds = someUser.posts()
GET /posts?id=<postIds[0]>&id=<postIds[1]>&...
   > somePosts
   >  **application user inspects posts to see which one they care about**
   > var postOfInterest = somePosts[x];
   > var postId = postOfInterest.id;
GET /comments?id=postId
   > someComments (finally)
</code>```

Suppose though I only care about a Post or Comment in the context of it's owner. Suppose a different resource structuring which may (or may not?) be more natural:

```<code>GET /users
POST /users
GET /users/id
PUT /users/id
DELETE /users/id

GET /users/id/posts
POST /users/id/posts
GET /users/id/posts/id
PUT /users/id/posts/id
DELETE /users/id/posts/id

GET /users/id/posts/id/comments
POST /users/id/posts/id/comments
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
</code>```

Which to me, is probably a better representation of what the resources are. Then all I need is:

```<code>GET /users/id/posts
   > somePosts
   > **application user inspects posts to see which one they care about**
   > var postOfInterest = somePosts[x];
   > var postId = postOfInterest.id;
GET /users/id/posts/postId/comments
   > someComments
</code>```

This just seems more like navigating a file system than the previous method - but I don't know if its RESTfull at all (perhaps this is what REST was trying to get rid of) because in order to access a Comments resource, I need to know which User and which Post it belongs to. But the former requires 3 requests, while the latter requires just 2.

Thoughts?

答:
As far as I know what you're describing, essentially nested resources, is perfectly RESTful. You might want to keep the resources such as '/posts/id' and '/comments/id' in-case you want to get post/s or comment/s without knowing which user you're looking at, but there's nothing wrong with also nesting them inside each other for getting the posts for a particular user or comments for a particular post.

Rails in particular allows you to easily nest resources in this manner by doing something like the following in your routes configuration:

```<code>resources :users do
  resources :posts do
    resources :comments
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Title: HasMany RESTfull Implementation

Body:
As far as I know what you're describing, essentially nested resources, is perfectly RESTful. You might want to keep the resources such as '/posts/id' and '/comments/id' in-case you want to get post/s or comment/s without knowing which user you're looking at, but there's nothing wrong with also nesting them inside each other for getting the posts for a particular user or comments for a particular post.

Rails in particular allows you to easily nest resources in this manner by doing something like the following in your routes configuration:

resources :users do
  resources :posts do
    resources :comments
  end
end


问:
Providing popups in an asp.net web application that contain server controls
What is the best way to provide popups that contain asp.net server controls? I am working on a  .net site. I have search functionality where if someone presses a button a panel appears where they can input the search information. I would like this to be a popup instead. Normal JavaScript won't work because the controls operate server side. So how do I go about creating a popup that is interacted with via server side?</p>

答: You can use a PopUpControlExtender, which is part of the ASP.NET Ajax library. There's a modal popup version as well.</p>


问:
What are the guidelines for either throwing an exception or failing silently for nonvalid arguments?
If you look at XContainer.Add(object content) method you can see that id does not require content to be not null.
 It just does nothing in case of null.

However List.AddRange(IEnumerable collection) requires instance and throws ArgumentNullException otherwise. Here author of the code decided that exception was more appropriate than silence.

They could implement it like:

```<code>bool List<T>.AddRange(IEnumerable<T> collection)
</code>```

and return true only if collection was not empty...But they didn't.

Quite often I ask myself whether to throw or just do nothing in case of bad parameters. The cue available for me is the question: "Can exception help the client of my function to detect logic mistake and unexpected program state?".

If I answer to myself: "Yes, it can in MOST of use cases" then I adhere to throwing.

Nonetheless, sometimes the best way is not very evident to me. It's a bit uncomfortable not to have strong arguments for favoring one approach over the other.

I will appreciate any sound recommendations for selecting between these alternatives.

答:
The cue available for me is the question: "Can exception help the client of my function to detect logic mistake and unexpected program state?".

And for me it's "Is it fine for me to potentially crash my caller's application in the most horrible way possible due to this error?". (After the requisite "Is there any way I can avoid needing to do this check in the first place?")

Different people have different tastes, and even different applications have different needs - hence the variety of behaviors.

In general, I like throwing early and often for things that are clearly errors. Explosive errors are easily spotted, and if the explosion is near the cause it's easy to diagnose. I'd personally be fine with AddRange(null) being a no-op, and will do that sort of thing for scenarios with sane behaviors that are likely caused by laziness rather than accident.


问:
Definition of distribute in relation to the GPLv3
We lease an appliance to our clients (4 physical servers running 12 VMs).

One of the servers exposes a website which in turn uses the other VMs. Clients have no access to the VMs or the software which runs on them. One of the reasons is that we process classified documents (and while security through obscurity is no defence, why make anything easy for an attacker?)

So the appliances are owned and maintained by us but can be accessed across a network by clients.

I'd like to use some functionality which is in a library licensed under the GPLv3. If needs be, I can implement the library myself without needing to refer the the library in question, but I'd obviously prefer to use the existing code (to avoid reinventing wheels).

With the caveat that none of us are lawyers, can someone clarify if, in their experience, this counts as distribution under the definition of the GPLv3?

答:
The application runs on the server. Under the GPLv3, you are distributing the code to the person running the code on the server (yourself) and don't need to go any further.  This is known as the ASP loophole.  See GPLv3 and Software as a Service from the FSF for more on that from GPLv3 perspective.

For completeness and contrast, the AGPL goes a step further to say that the application is distributed to those running the web application.  if the library was licensed under the AGPL instead, one would be required to release the source of the application.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
The Practice of Programming
by Brian W. Kernighan and Rob Pike

I found it unusual in that it promotes thinking, instead a lot of the typical lingo driven self promotionial books.

ContentLicense: CC BY-SA 2.5


问:
How to manage your personal ssh keys?
I understand that ssh keys are a cryptographically secured way of authenticating yourself to a service or to another person, but beyond that I'm frankly at a bit of a loss.

What confuses me is that I see many developers mention their public key on their site, but how does one have just one key? I have a few for different things. And if my computer crashed, I would have to generate new ones. I obviously can't remember the key.

Do people just save it somewhere, the sequence of numbers/letters, like in their email? And then use that one key for everything? How does someone get a personal key?

I just feel like I'm missing something about this whole theater of operations.

I mean, we walked through RSA in university; I understand the principle, but I never used it in practice until I signed up for github and heroku and few months ago and they forced me to generate some keys, something I didn't even realize I could do before then.

答:
When you generated your key pair, you created 2 keys: a private and a public (often id_rsa and id_rsa.pub).

The main point to remember is that nobody should have access to your private key apart from you. If it does fall into the hands of someone else, then you should remove your public key from any system that uses it to identify you. This way, nobody can pretend to be you.

That said, how you organise it is up to you, in my opinion. Some people have one key for everything, and just upload the public key everywhere; others will have separate keys for separate purposes.

It's a good idea to have an encrypted backup of your keys (as with all your important files). That said, even if you do lose a private key, it's usually not that big of a deal, as long as you can get the corresponding public key on all systems that use it changed to a new one.

Title: How to manage your personal ssh keys?


答:
I normally keep my key in the .ssh directory where is was generated.  I have backups of my home directory that included the key.

When password protected, the keys become part of a two factor authentication.  The password is something you know, while the key (or the device that holds it) is something you have.  Without both you cannot authenticate.

The public/private key pairing allows you to freely share the public key without significant risk.  Using the same key in multiple locations make your life simpler as you don't have to manage multiple keys.  If your key and password are compromised, access to all sites using that key may be possible.  Having multiple keys may not improve security much if they are all stored on the same device and have the same password.

Where I do use additional keys, is where I have restricted use keys.  Depending on what they are used for, they may not be password protected, although other security will be in place.

As a protection against key compromise having an alternate key and device allows, the use of an alternate access mechanism to disable access fro the compromised key.  It is possible (likely) that the compromised key could be used to block access to at least one site.

If you do use multiple keys, you can configure ssh to use the appropriate key for each site.  The remote server may allow you to configure what access the key permits.

Title: How to manage your personal ssh keys?

Body:
I understand that ssh keys are a cryptographically secured way of authenticating yourself to a service or to another person, but beyond that I'm frankly at a bit of a loss.

What confuses me is that I see many developers mention their public key on their site, but how does one have just one key? I have a few for different things. And if my computer crashed, I would have to generate new ones. I obviously can't remember the key.

Do people just save it somewhere, the sequence of numbers/letters, like in their email? And then use that one key for everything? How does someone get a personal key?

I just feel like I'm missing something about this whole theater of operations.

I mean, we walked through RSA in university; I understand the principle, but I never used it in practice until I signed up for github and heroku and few months ago and they forced me to generate some keys, something I didn't even realize I could do before then.


问:
What are the disadvantages of using/writting a .Net Custom Membership Provider?
Recently, I posted the following question on SO: https://stackoverflow.com/questions/7197337/using-asp-net-membership-provider-with-an-existing-user-database

As you may notice, I ended up answering my own question stating that it looked like writting/implementing a "Custom Membership Provider" was the way to go.

Literally, a few minutes later, I stumble across this question: https://stackoverflow.com/questions/7222306/simple-login-attempt-counter-using-mvc-3-and-ajax/7222407#7222407

I try to answer and get a comment back that .Net Membership provider is "terrible on many levels". I'll admit, this is the first time I'm using Membership provider but it sure looked slick to me.

I haven't seen anything that backs up the "terrible" claim so before I implement something "terrible", I was hoping to get some feedback from the community.

答:
This question is old but I'm getting badges for it's popularity so I figure it's worth it to provide an updated answer.

Microsoft's "Simple" Membership provider finally got it right in my humble opinion. If you are writting something new or even attaching to a legacy database with a new application. Use the simple membership provider. WAY EASIER and CLEANER to implement. Install a couple of tables and point the provider to your list of users and you are basically done.

This link will get you started or just google it: http://www.mattjcowan.com/funcoding/2012/11/10/simplemembershipprovider-in-mvc4-for-mysql-oracle-and-more-with-llblgen/


问:
Heuristic for consistiently ordering points in a a plane
I have rectangular regions in a plane. I want to consistently order them in a human-friendly way that a typical y-x sort won't work for. Basically I want (0,0), (1,0), and (0,1) to sort the same as (0,0), (1, -0.1), and (-0.1, 1).

Ideas?

From comments:

The obvious answers, y-x and x-y sort, result in different orders for the short example I posted. The things I'm coming up with, now, are clustering approaches where I cluster the y values, sort by cluster y means, then by x.

Question: What are you sorting your rectangles for? Searching? Displaying?

Numbering the regions, and I want two region sets a human would say are nearly identical to get numbered identically.

Question: Is the orientation of the rectangles really important (what is the difference between (0,1) and (-1,0) in the problem domain)? Would primarily sorting by area or diagonal be ok?

I can't tell the orientation of them beyond portrait or landscape, and size doesn't work because a lot might be practically the same.

答:
In principle, a Hilbert curve can do that. It's a fractal that fills a two-dimensional space.

This paper defines a generalization of the Hilbert curve and uses a relationship with reflected binary Gray code to define efficient conversions, with the main application being multi-dimensional database indexes.

The key point is that a fractal can be evaluated to any level of detail. So in principle, if two different points hit the same point on a Hilbert curve at one resolution, you can just evaluate the Hilbert curve at higher and higher resolutions until you find one where the points on the Hilbert curve are different, ordering the two points based on that. Because you're just evaluating the same curve to a higher level of detail, ordering relative to other points (assessed at lower resolution) is unchanged.

That said, this is just a the basic idea - I don't know if it has been done (probably it has, but I don't have a reference) or the detail of how to implement it well.


答:
When exposing a RESTful interface, you also need to examine, what the interface is telling the user.

When examining a post, its more than likely a user doesn't care about who made it and unless post IDs are only unique in the scope of a user (which is unlikely) its just addtional cruft in the URL. While its true that a post has a user, I'm not so sure you can say that in this context it is owned by its user, if the difference is clear.

There is also the abiquity of what happens when user X writes a post, and user Y writes a comment on that post. In this /users/idZ/post/id/comment/id does idZ refer to the user who wrote the post, or the comment? Moreso, why do you need to know the user, if you already have a post or comment ID?

Alternatively, a comment is owned by its post, even if its ID is globally unique.

Lastly, there is a readability difference between users and user, with the latter implying discreteness. Similarly, with posts and post, and comments and comment.

So personally, given this, I'd use these actions (with the appropriate verbs where required):

```<code>ACTION /users
ACTION /user/id

ACTION /user/id/posts    # A user owns these posts
ACTION /post/id          # But the site owns this particular post

ACTION /post/id/comments
ACTION /post/id/comments/id
</code>```

Title: HasMany RESTfull Implementation

Body:
So I've been reading a lot on RESTfull design - specifically dealing with resources.

Taking the canonical example of Users, Posts, and Comments, with relationships as:

Users ---(hasMany)---> Post ---(hasMany)---> Comment

One may initially think to expose something like:

```<code>GET /users               GET /posts               GET /comments
POST /users              POST /posts              POST /comments
GET /users/id            GET /posts/id            GET /comments/id
PUT /users/id            PUT /posts/id            PUT /comments/id
DELETE /users/id         DELETE /posts/id         DELETE /comments/id
</code>```

But then, say I want all Comments of a certain Post made by a particular User. I'd need to do something like:

```<code>GET /users/id
   > someUser
   > var postIds = someUser.posts()
GET /posts?id=<postIds[0]>&id=<postIds[1]>&...
   > somePosts
   >  **application user inspects posts to see which one they care about**
   > var postOfInterest = somePosts[x];
   > var postId = postOfInterest.id;
GET /comments?id=postId
   > someComments (finally)
</code>```

Suppose though I only care about a Post or Comment in the context of it's owner. Suppose a different resource structuring which may (or may not?) be more natural:

```<code>GET /users
POST /users
GET /users/id
PUT /users/id
DELETE /users/id

GET /users/id/posts
POST /users/id/posts
GET /users/id/posts/id
PUT /users/id/posts/id
DELETE /users/id/posts/id

GET /users/id/posts/id/comments
POST /users/id/posts/id/comments
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
</code>```

Which to me, is probably a better representation of what the resources are. Then all I need is:

```<code>GET /users/id/posts
   > somePosts
   > **application user inspects posts to see which one they care about**
   > var postOfInterest = somePosts[x];
   > var postId = postOfInterest.id;
GET /users/id/posts/postId/comments
   > someComments
</code>```

This just seems more like navigating a file system than the previous method - but I don't know if its RESTfull at all (perhaps this is what REST was trying to get rid of) because in order to access a Comments resource, I need to know which User and which Post it belongs to. But the former requires 3 requests, while the latter requires just 2.

Thoughts?

Body:
When exposing a RESTful interface, you also need to examine, what the interface is telling the user.

When examining a post, its more than likely a user doesn't care about who made it and unless post IDs are only unique in the scope of a user (which is unlikely) its just addtional cruft in the URL. While its true that a post has a user, I'm not so sure you can say that in this context it is owned by its user, if the difference is clear.

There is also the abiquity of what happens when user X writes a post, and user Y writes a comment on that post. In this /users/idZ/post/id/comment/id does idZ refer to the user who wrote the post, or the comment? Moreso, why do you need to know the user, if you already have a post or comment ID?

Alternatively, a comment is owned by its post, even if its ID is globally unique.

Lastly, there is a readability difference between users and user, with the latter implying discreteness. Similarly, with posts and post, and comments and comment.

So personally, given this, I'd use these actions (with the appropriate verbs where required):

ACTION /users
ACTION /user/id

ACTION /user/id/posts    # A user owns these posts
ACTION /post/id          # But the site owns this particular post

ACTION /post/id/comments
ACTION /post/id/comments/id


问:
Writing a job requirement for a web application developer
I'm currently writing a job requirement for a software engineer position for my company, in which we are looking for a developer to work on client-side web application work. How should I title the job title / position? I don't necessarily want to call it a "Web Developer", for fear that it might attract more designer-y types. On the other hand, "Software Engineer" doesn't really give the indication that the work, while application based, will be web-based. Is "Web Application Software Engineer" a valid position title?

Also, I'm somewhat torn on what the required skills set should be. I don't necessarily think that the ideal candidate should have x years of experience in say, JavaScript or ActionScript, but rather am just looking for someone who has experience in developing client-side applications, and is willing to learn and develop web applications. My current attempt at this, is that I have a section in which I state:

Experience in the following frameworks
  and technologies are a plus, but not
  necessarily required for the position:

答:
If you're looking for a developer to work on client-side web application work, advertise for a client-side web application developer.

Calling it something else is an endemic problem in the industry that I would try to avoid.  Call a spade a spade.


问:
Extracting lambda expressions from linq queries and readability
Every now and then when I have a complex lambda, I do something like this:

```<code>Func<SomeObject, bool> equals = o =>
    o.ID == someID && o.Name == someName && IsAdd || ...
var myList = MyThings.Where(equals).ToList();
</code>```

Let's assume that the logic in equals can not be simplified. Does extracting the lambda from the linq query improve, or reduce readability?

The alternative being:

```<code>var myList = MyThings.Where(o => o.ID == someID && o.Name == someName && IsAdd || ...).ToList();
</code>```

答:
There is another alternative. If the lambdas are big, I would suggest that you extract one or more methods. Something like this:

```<code>var myList = myThings.Where(MatchesTheCondition).ToList();

private bool MatchesTheCondition(SomeObject o) {
  return o.ID == someID && o.Name == someName && IsAdd || ... ;
}
</code>```

Of course, your method shouldn´t be named "MatchesTheCondition" ;)

Body:
There is another alternative. If the lambdas are big, I would suggest that you extract one or more methods. Something like this:

var myList = myThings.Where(MatchesTheCondition).ToList();

private bool MatchesTheCondition(SomeObject o) {
  return o.ID == someID && o.Name == someName && IsAdd || ... ;
}

Of course, your method shouldn´t be named "MatchesTheCondition" ;)


问:
Why do people pick the MIT license over BSD, if BSD's "non-endorsement clause" is a good idea?
According to this question and it's replies

What is the purpose of the "non-endorsement clause" in the New BSD license?

it seems smarter to pick the BSD license over the MIT, to prevent people using your name in an unwanted way.

If that is the case, why do people still pick the MIT license over BSD license?

答: As you may know, the original BSD license had 4 clauses, one of them being an "advertisement clause". The non-endorsement clause was likely present to accompany the advertising clause and not allow the name of the project be dragged through the mud while being advertised.</p>


问:
What's the most effective way to share code between .NET applications?
In our work, we have several different .net applications that share a lot of base functionality.  We've built these applications using a clean n-tier architecture, but we've hit that moment where we realize that we've re-implemented the same functions several different times.  Obviously this violates DRY, and we would like to correct that.  We're already using Nuget to some success for common glue code (wiring up IoC, logging, settings), but we also would like to share our data and business layers between all our applications.  The idea is that the UI would only deal with the parts of the business layer it actually needs.

This seems like a straight-forward problem at first, but ongoing development could provide some pitfalls and we're not sure how to proceed.  Let's say we make our One Business Layer to Rule Them All.  For brevity, I'll call it "Foundation."  We port our applications to use the Foundation, and everything is runnding great.  The Foundation is distributed to light UI layers via nuget, and we're looking good.  But then we start adding features to our applications, and we run into trouble.

Let's say we're working on Project A and we add a new feature that requires changes to Foundation.  We make the changes to foundation (Foundation-A) and push them out to the nuget feed as an unstable package.  Project A gets the latest nuget package, and all is good.  Meanwhile, another developer is working on Project B.  He gets the latest Foundation from source control, but takes it from a stable branch, so that it doesn't have Project A changes in it.  He makes changes and created Foundation-B.  And all is good.  But then we discover that Foundation-A and Foundation-B implementation functionality that could actually share code, so we combine them.  Meanwhile Foundation-C is floating out there with it's own changes.  Eventually, Foundation-B is ready for production, so we push it out.  But then we need to update Production A, B, & C with the new foundation, so we update the nuget packages and deploy (as long as nothing breaks).

This seems like it could work, but we're worried about working with different database schemas and keeping everything synchronized between the various branches of the Foundation repository as well as the Project A, B, and C repositories.  It seems like it will probably take a lot of manual work, which opens up the possibility for errors.  I would like this as automated as possible.

Here's the stack we're using: C#, TFS with Continuous Integration, Nuget. Our applications are all various types of ASP.NET applications.  We're willing to look at different SCM's if it will make things easier.

I'm looking for ways to keep Nuget sane with our different source code branches.  We don't want to accidentally push development code into production because we reference the wrong Nuget Package.

答:
Refactor your duplicate code into functions that are applicable in a more abstract way, and put them into their own libraries or frameworks.  Make them loosely-coupled and architecture-agnostic, and you should never have any problem.  If you need inspiration, study how the .NET framework abstracts concepts using things like interfaces, generics, and software patterns such as Dispose().

Also, remember that not all duplicate code is really duplicated; some of it is glue code or code that is otherwise necessary for sustaining the architecture, so don't obsess over being too DRY.


问:
What language has integrated "list insertion" as part of code *syntax*?
Many programming languages permit natural manipulation of strings, and some languages permit the manipulations of lists too.

More often then not (always?), these operations are done as procedure calls, or as member functions.

Many programming languages do implement in syntax the fairly typical set {prepend, replace, append} on lists (and/or strings).

I would like to know if there as/was a programming language that has a syntax that minimises/rationalises/orthogonalises the insertion syntax of items into a list by syntax design?

Python - as a simple example - has only: https://stackoverflow.com/questions/18033339/python-insert-operation-on-list

```<code>mylist.insert(10,'5')
</code>```

Note: In python list insertion is implemented as a member function.

But: Python does have some syntactic sugar for removing elements from a list: e.g.

```<code>del mylist[4:7]
</code>```

I like to know of any languages actually try to integrate (or have strategy) for list insertion as part of the syntax?

An example of insertion by construction: Here is some code from a fairly typical "Brand X" language, demonstrating typical prepend/replace/append operations {or operators, vis-à-vis syntatic sugar}, notice there is no obvious syntax for {in place} inserting (or removing) from the middle of a list.  {It has to be done "by construction", or by calling a procedure}

```<code># Demonstration of prefix, replace and append operations to a string {or list} #
string s := "23XX78";
"1"    +=: s;    # Prefix a char "1" to the string "in place" #
s[4:5] := "46";  # In place replace a char at pos 2 in a string #
s      +:= "9!"; # Append a string "9!" char to the string #
#
  Although inserting into a list is intuitive,
  * it is by construction (hence prone to typos/index-flips)
  * it is not "in place"
  e.g. ...
#
s:=s[:4]+"5"+s[5:];

print(s)
</code>```

Output: "123456789!"

Another example for strings:

```<code>s[:4]+="5"
</code>```

答:
Python actually supports insertion of arbitrary sub-lists, as a part of list slice assignment. You just assign to an empty slice before the element where you want to insert a new list:

```<code>list1 = [1, 2, 3]

list1[1:1] = [10, 20, 30] # insert 3 elements at index 1
print list1 # prints [1, 10, 20, 30, 2, 3]
</code>```

Many languages view lists as primarily sequential data structures, thus only allowing manipulation at their ends. This has both implementation-related and logical advantages: e.g. sequentially you can handle lists of unknown arbitrary length.

Often when you find yourself in need to insert an element into the middle of a list, it's a good sign that what's you're doing is a hack due to a poor design. (Python's sys.path[0:0] manipulation is an example.)

Body:
Python actually supports insertion of arbitrary sub-lists, as a part of list slice assignment. You just assign to an empty slice before the element where you want to insert a new list:

list1 = [1, 2, 3]

list1[1:1] = [10, 20, 30] # insert 3 elements at index 1
print list1 # prints [1, 10, 20, 30, 2, 3]

Many languages view lists as primarily sequential data structures, thus only allowing manipulation at their ends. This has both implementation-related and logical advantages: e.g. sequentially you can handle lists of unknown arbitrary length.

Often when you find yourself in need to insert an element into the middle of a list, it's a good sign that what's you're doing is a hack due to a poor design. (Python's sys.path[0:0] manipulation is an example.)


问:
Short function names for often used function or general concept
I am a bit in a dilemma: Let's suppose I have a very general function and a
specialization of it for convenience reasons. Let's also assume that the
specialized function is used 90 per cent of the time, hence being "the common
case".

Should I use a shorter function name for the general case (e.g. do) and a longer
one for the special (do_something_special) or the other way around (e.g.
do_something_general and do)? When applying Larry Wall's words (make simple
things easy and hard ones possible), I'd use a shorter form for the more often
used case.

EDIT: Just to make this a bit more clear: in this example, do is just a placeholder for a short, descriptive name. Of course it could be longer, e.g. run_task or process_file. What I want to know is, if I have a function called run_task_in_specific_way that is used most of time should actually be called run_task (although being more specific) or the general abstraction.

EDIT 2: To clarify once more: The functions I am talking about are neither providing more than one functionality nor should they be replaced by a class-based design. The reason is: they are abstract in the same sense as qsort, e.g. taking callable from users to fulfill a specific action. Wrapping them into some auxiliary class does not make much sense.

答:
Use a name that accurately describes what the function is achieving. If its doing something "special", put "special" in the name. Don't worry about how long the name is (within reason). Over the next few decades, readers deciphering cryptic functions names will take a lot longer working out what they mean than typing the name a few times. </p>

<p>In the above example, I would use "do_general" and "do_special"..... "do" gives no clue that there is an alternate. </p>

Body:
Use a name that accurately describes what the function is achieving. If its doing something "special", put "special" in the name. Don't worry about how long the name is (within reason). Over the next few decades, readers deciphering cryptic functions names will take a lot longer working out what they mean than typing the name a few times.

In the above example, I would use "do_general" and "do_special"..... "do" gives no clue that there is an alternate.


问:
The Agile process: how and what should be documented?
A while ago the company I work for had outsourced a development project to a third party. They employed agile practices in developing the solution. However when asked for documentation they would just say it was required as it was incorporated in a wiki or as part of their sprints.

They did leave at the completion of the project, with all but one of the project team. The project wiki site has now been closed down once the yearly subscription was due.

When they left they took most of the knowledge and understanding of what was developed with them.

So I do have 2 main questions;

Is this normal for agile or just an excuse for not wanting to write it?

What are the industry norm for documentation in agile projects to record development
requirements, designs, key decisions and context?

答:
While I'm not an Agile expert by any means, here is my attempt at an answer:

Was there a story/requirement asking for specific documentation?  If not, then this is part of the problem as you get what is requested to some extent.  It is an excuse and I could wonder what you mean by "normal" here.  Is it just a majority of those following Agile principles that makes something normal or is it part of the overall process that should be expected?  Those are the two views I could see for it. EDIT: I doubt there is anything the majority of teams do that is the same when it comes to documentation, but that is a guess on my part.

A couple links that may be of interest, is about the best I could do on this:

Best Practices for Agile/Lean Documentation

Agile and Technical Documentation

Agile has some specific points in the manifesto, where I'd point out this one along with the note:

Working software over comprehensive documentation

That is, while there is value in the
  items on the right, we value the items
  on the left more.


问:
Sleeping Barber Problem (with multiple barbers)
The Sleeping Barber Problem is a classical synchronization problem that many of you may be familiar with or at least heard of.

It's based on the premise that a barber (a thread) sleeps when there are no customers (each customer is a thread) in the waiting room (which is a semaphore). If there is someone, he cuts his hair (symbolizing some processing) and the costumer leaves. If, then, there is no one in the waiting room, the barber goes to sleep. When another customer arrives, he then must wake up the barber.

I have made a implementation of this using the following basic-idea (pseudo-code, only using sem_wait and sem_post1 for smooth reading)

```<code>Semaphore Customers = 0;
Semaphore Barber = 0;
Mutex accessSeats = 1;
int NumberOfFreeSeats = N;

Barber {
    while(1) {
        sem_wait(Customers) // waits for a customer (sleeps)
        sem_wait(accessSeats) // mutex to protect the number of available seats
        NumberOfFreeSeats++ // a chair gets free
        sem_post(Barber) // bring customer for haircut
        sem_post(accessSeats) // release the mutex on the chair
        // barber is cutting hair
    }
}

Customer {
    while(1) {
        sem_wait(accessSeats) // protects seats so only 1 thread tries to sit in a chair if that's the case
        if(NumberOfFreeSeats > 0) {
            NumberOfFreeSeats-- // sitting down
            sem_post(Customers) // notify the barber
            sem_post(accessSeats) // release the lock
            sem_wait(Barber) // wait in the waiting room if barber is busy
            // customer is having hair cut
        } else {
            sem_post(accessSeats) // release the lock
            // customer leaves
        }
   }
}
</code>```

However, now that I'll implement this problem with multiple barbers, my head got stuck. I went on Wikipedia to see if I could find something about it, but the only thing that I found there was this

A multiple sleeping barbers problem has the additional complexity of coordinating several barbers among the waiting customers.

and I couldn't figure this out by myself. In which case I'd have this complexity? By several barbers going to the waiting room to see if there is anyone there and then taking (more than one barber) a single customer? Would I need an extra semaphore here?

1sem_wait() locks the semaphore. sem_post() unlocks it

答:
With one barber, you only need a message queue (the waiting room). Semaphores are embedded in it.

With multiple barbers, coordination aims at:

preventing several barbers from cutting hair of the same customer.

preventing from having only one busy barber while the others sleep all day long.


答:
Based on my experience, I'd go for the middle way. It's better to have the shortest expression instead of having a short code or a sentence as a name. Generally I think you should not sacrifice being expressive for being brief when it comes to naming.

That was my two cents!

P.S.
Based on what you just said to mattnz, I suggest to develop a template for naming and name everything following its guideline, no matter short or a bit longer.

Title: Short function names for often used function or general concept

Body:
I am a bit in a dilemma: Let's suppose I have a very general function and a
specialization of it for convenience reasons. Let's also assume that the
specialized function is used 90 per cent of the time, hence being "the common
case".

Should I use a shorter function name for the general case (e.g. do) and a longer
one for the special (do_something_special) or the other way around (e.g.
do_something_general and do)? When applying Larry Wall's words (make simple
things easy and hard ones possible), I'd use a shorter form for the more often
used case.

EDIT: Just to make this a bit more clear: in this example, do is just a placeholder for a short, descriptive name. Of course it could be longer, e.g. run_task or process_file. What I want to know is, if I have a function called run_task_in_specific_way that is used most of time should actually be called run_task (although being more specific) or the general abstraction.

EDIT 2: To clarify once more: The functions I am talking about are neither providing more than one functionality nor should they be replaced by a class-based design. The reason is: they are abstract in the same sense as qsort, e.g. taking callable from users to fulfill a specific action. Wrapping them into some auxiliary class does not make much sense.


答:
I personally never did like "do" very much in code.  It isn't very descriptive other than implying that something needs to be executed, but unless it is a getter or setter, it is already implied that you're executing something.

When I want to write code pertaining to a general controller-like method, I tend to call it "execute".  How my controller behaves is determined by a configuration set prior to calling execute.  If there is a radically different way of working which is a particular case, I'll rename execute into executeDefault and then I'll create a execute.  In order to keep it short, I'll simply create a method "execute" at that point which calls executeDefault.  In this way, I have the best of both worlds:  short name and understandable code.

If I end up having many such execution cases, then I consider restructuring it using the Abstract Factory pattern which provides me controller classes with "execute" method.

Hope that helps.


问:
Are branches in unit tests bad practice?
Say I want to assert that a certain option menu is displayed in the front-end of a project. The menu is on screen X and I have to first select data in Y to get to X. Now, it doesn't matter at all what data I select in Y, it will always lead to X.

But sometimes, depending on the data, I will get a screen Z which I can just skip through. Now obviously, if I write the test in a deterministic manner the test may fail if the data I selected leads to screen Z.

The data I'm talking about is test data, set up before every test to the same state. So theoretically, I could just select one data entry that I know will not go to screen Z.

But, I could also simply include a check to see if I'm on screen Z after selecting the data and skip Z. Now, even changes to the test data (though rare, it happens) would not break my test.

Somehow I don't like this approach but I can't really explain why. Adding a method to check for Z would add a (probably) "useless" method to my test framework.

So my question is, are branches to handle conditional behaviour that is not being tested in that specific test okay? Are there any problems with this approach? Is it good to do this?

答:
It's not unreasonable for a change in test data to change the outcome of a test.

I wouldn't put the conditional branch in, I would ensure that I have a separate test with a set of test data that always goes to screen Z so that behaviour can be tested.

If the initial test you're trying to do is that when data from Y is entered, screen X is displayed then that's exactly what you should test - don't overcomplicate tests.

Y -> Z -> X is not the same as Y -> X and I presume some business logic (which should be tested) controls the appearance of Z?


答:
I think problem is not in nuget/source control/branching, but in what slips into glueing code.

Robert has nice answer, just to see whole picture, I recommend to think about what dependencies these common utilities will bring into each project:

http://ayende.com/blog/3986/let-us-burn-all-those-pesky-util-common-libraries
http://blog.jordanterrell.com/post/CommonUtility-Libraries-Dead.aspx

Best way to avoid the hell you're having is to open source your glue code. In such way you'll start to care, that no business logic would go public, so no concrete project dependences will slip into glue code, that it would be abstract enough to be reused by anyone, even outside your company - and if that glueing code will be good enough - you'll get community input also.

Title: What's the most effective way to share code between .NET applications?

Body:
In our work, we have several different .net applications that share a lot of base functionality.  We've built these applications using a clean n-tier architecture, but we've hit that moment where we realize that we've re-implemented the same functions several different times.  Obviously this violates DRY, and we would like to correct that.  We're already using Nuget to some success for common glue code (wiring up IoC, logging, settings), but we also would like to share our data and business layers between all our applications.  The idea is that the UI would only deal with the parts of the business layer it actually needs.

This seems like a straight-forward problem at first, but ongoing development could provide some pitfalls and we're not sure how to proceed.  Let's say we make our One Business Layer to Rule Them All.  For brevity, I'll call it "Foundation."  We port our applications to use the Foundation, and everything is runnding great.  The Foundation is distributed to light UI layers via nuget, and we're looking good.  But then we start adding features to our applications, and we run into trouble.

Let's say we're working on Project A and we add a new feature that requires changes to Foundation.  We make the changes to foundation (Foundation-A) and push them out to the nuget feed as an unstable package.  Project A gets the latest nuget package, and all is good.  Meanwhile, another developer is working on Project B.  He gets the latest Foundation from source control, but takes it from a stable branch, so that it doesn't have Project A changes in it.  He makes changes and created Foundation-B.  And all is good.  But then we discover that Foundation-A and Foundation-B implementation functionality that could actually share code, so we combine them.  Meanwhile Foundation-C is floating out there with it's own changes.  Eventually, Foundation-B is ready for production, so we push it out.  But then we need to update Production A, B, & C with the new foundation, so we update the nuget packages and deploy (as long as nothing breaks).

This seems like it could work, but we're worried about working with different database schemas and keeping everything synchronized between the various branches of the Foundation repository as well as the Project A, B, and C repositories.  It seems like it will probably take a lot of manual work, which opens up the possibility for errors.  I would like this as automated as possible.

Here's the stack we're using: C#, TFS with Continuous Integration, Nuget. Our applications are all various types of ASP.NET applications.  We're willing to look at different SCM's if it will make things easier.

I'm looking for ways to keep Nuget sane with our different source code branches.  We don't want to accidentally push development code into production because we reference the wrong Nuget Package.


问:
Returning multiple values in Javascript
Often I am writing a function that returns multiple values, such as a pair of coordinates:

```<code>function get_coords() {
  return ???;
}
</code>```

If I was using a language like Python, I would use a tuple:

```<code>return (x, y)
</code>```

Or, in an OOP language like Java, I would create a custom coordinate class:

```<code>class Coordinates {
  public int x;
  public int y;

  public Coordinates(x, y) {
    this.x = x;
    this.y = y;
  }
}
</code>```

Then return like this:

```<code>return new Coordinates(x, y);
</code>```

On to JavaScript.

In JavaScript, we have the option of returning a simple object:

```<code>return {x: x, y: y}
</code>```

or a Java-like approach, with a custom object:

```<code>return new coordinates(x, y)
</code>```

Are there any reasons to use one above the other?

答:
Well, the both approaches are equal, since both are Objects with same properties, just  different prototypes.

For the sake of simplicity, you should probably go with the first option. Or even simpler, with the array of the form [x, y].

Title: Returning multiple values in Javascript


问:
How to cross-reference many character encodings with ASCII OR UTFx?
I'm working with a binary structure, the goal of which is to index the significance of specific bits for any character encoding so that we may trigger events while doing specific checks against the profile.

Each character encoding scheme has an associated system record. This record's leading value will be a C++ unsigned long long binary value and signifies the length, in bits, of encoded characters.

Following the length are three values, each is a bit field of that length.

offset_mask - defines the occurrence of non-printable characters within the min,max of print_mask

range_mask - defines the occurrence of the most popular 50% of printable characters

print_mask - defines the occurrence value of printable characters

The structure of profiles has changed from the op of this question. Most likely I will try to factorize or compress these values in the long-term instead of starting out with ranges after reading more.

I have to write some of the core functionality for these main reasons.

It has to fit into a particular event architecture we are using,

Better understanding of character encoding. I'm about to need it.

Integrating into non-linear design is excluding many libraries without special hooks.

I'm unsure if there is a standard, cross-encoding mechanism for communicating such data already. I'm just starting to look into how chardet might do profiling as suggested by @amon. The Unicode BOM would be easily enough (for my current project) if all encodings were Unicode.

Of course ideally, one would like to support all encodings, but I'm not asking about implementation - only the general case.

How can these profiles be efficiently populated, to produce a set of bitmasks which we can use to match strings with common characters in multiple languages?

If you have any editing suggestions please feel free, I am a lightweight when it comes to localization, which is why I'm trying to reach out to the more experienced. Any caveats you may be able to help with will be appreciated.

答:
Your assumptions are mostly wrong, because you do not account for encodings like UTF-16be.

If you take a look at ASCII (or by virtue at UTF-8); the first 32 characters are control characters. This is pretty common for lots of reasons.

No. It happens that ASCII, Unicode codepoints and UTF-8 all have control characters at the first 32 byte/codepoint positions, but this is to ensure backwards compatibility to ASCII! There are many other encodings that do this as well, usually single-byte encodings.

UTF-16 (and predecessors) and UTF-32 encode codepoints with a minimum of 2 resp. 4 bytes. In UTF-16be, a newline is 00 0A, the letter a is 00 7A – in UTF-16le, this is 7A 00.

Control characters for all covered character sets are in the first N bits, hopefully 4.

Haha, what? Control characters do not occupy certain bits, they are usually full bytes. If you are entertaining the idea that control characters are always in a closed range at the beginning of the encoding table, I'll have to disappoint you.

For example, the delete character U+007F encodes to ASCII and UTF-8 7F. Unicode has control characters in the ranges U+0000–U+001F and U+007F–U+009F. The latter range encodes to multiple bytes in UTF-8, and can't be represented in ASCII.

The most frequently used characters and phrases in a localization are in a particular range smaller than 8 or 8-N bits, but may be contained neighboring bytes (depending on packing order).

I do not quite understand this statement (grammar…). If you mean that there is a single small subrange of byte sequences that is primarily used in a certain language, then you are partially correct – most writers will stick to a specific script. However, consider the following:

Some of these ranges are vast. Take for example chinese characters. Unicode contains thousands of CJK characters.

Many graphemes have multiple representations. Depending on Unicode normalization, an East Europan writer might produce text with characters from few codepoint ranges,  or he may use combining diacritics.

Many non-english documents (esp. on the Web) will likely include some latin characters as well.

There are dozens of single-byte encodings that only differ above the ASCII range. These encodings are still widely used, and can make it impossible to detect the actual encoding. Compare the encodings Latin-1 to Latin-16.

{ control: 31, range: [65,122], print: [32,255] }

This is wrong for various reasons, some already mentioned. You should realize that encodings trying to be ASCII-compatible will likely not be compatible with each other above including 0x80 (see above). UTF-8 uses bytes in this range to encode the length of the byte sequence of this code point (actually just a few bits, but that puts the resulting bytes here).

Encoding detection can use the following techniques to find a possible encoding:

Standards. For example, any XML document is UTF-8 until proven otherwise.

Conventions. Windows-1252 is depressingly common.

Byte order marks (BOMs) can identify UTF-16 encodings.

Exclusion. Many encodings have illegal byte sequences that cannot occur (this is especially helpful to rule out UTF-8). Even in single-byte encodings, some bytes are unassigned.

Unique characteristics. If every 2nd byte is NUL, there is a good chance we are seeing UTF-16le (but we might still be wrong).

Statistics using external information. What are the odds that data from France will use a Chinese encoding?

Read the Wikipedia article on charset detection to get started. I recommend using an existing solution for your project, e.g. Mozilla's chardet.


答:
Don't you use classes? Or is it a global function? In general you could use short ones like:

```<code><?PHP
class Text {
  public function show() {
  }
  public function hide() {
  }
  public function delete() {
  }
}
class Image {
  public function show() {
  }
  public function delete() {
  }
}

//Implementation, even if we mix them up it stays quite clear and readable:
$firstText=new Text();
$firstText->show();
$imageOfMyFriend=new Image();
$firstText->delete();
$imageOfMyFriend->show();
?>
</code>```

The class instance name will define what we are talking about. This could also be done with more utility classes which you call static:

```<code><?PHP
  class File {
    public static function read($path) {
    }
    public static function readStream($path) {
    }
  }

  //implementation
  echo File::read('/home/myfile');
  echo File::readStream('/pathToMyStream');
?>
</code>```

All very simple names but still seems to work for me.

When you have exceptions you can define them in multiple ways. If you really need a seperate public method you can always derive the alternatives (As you see in File::readStream). That is also clear.

Generally I would reduce the public outputs, so make the read function detect whether we are handling a stream for example. It's the same idea, read, so it's the same thing you try to achieve. That makes it possible to switch implementations later on.

Body:
Don't you use classes? Or is it a global function? In general you could use short ones like:

<?PHP
class Text {
  public function show() {
  }
  public function hide() {
  }
  public function delete() {
  }
}
class Image {
  public function show() {
  }
  public function delete() {
  }
}

//Implementation, even if we mix them up it stays quite clear and readable:
$firstText=new Text();
$firstText->show();
$imageOfMyFriend=new Image();
$firstText->delete();
$imageOfMyFriend->show();
?>

The class instance name will define what we are talking about. This could also be done with more utility classes which you call static:

<?PHP
  class File {
    public static function read($path) {
    }
    public static function readStream($path) {
    }
  }

  //implementation
  echo File::read('/home/myfile');
  echo File::readStream('/pathToMyStream');
?>

All very simple names but still seems to work for me.

When you have exceptions you can define them in multiple ways. If you really need a seperate public method you can always derive the alternatives (As you see in File::readStream). That is also clear.

Generally I would reduce the public outputs, so make the read function detect whether we are handling a stream for example. It's the same idea, read, so it's the same thing you try to achieve. That makes it possible to switch implementations later on.


问:
Is it bad practice to store metadata information in file names? Better solutions?
I have noticed where I work people are keen on storing information in file names, and parsing the file names.

To me this doesn't seem to be especially good practice. I already see the occasional issues with scripts globbing for a file, and getting the wrong one because another file matches first.We are also discussing how to get around problems with separators for the fields.

Is it considered bad practice or not?

What are other accepted solutions for retrieving files from a file system based on some type of metadata?

答:
Yes I think it's bad practice. It is subject to all sorts of problems - for example length limits, encoding issues and conflicts due to duplicate data.

Better is to use a "master file" (sometimes called manifest or index) that contains metadata and paths to the files. Or something similar in a database, register or whatnot. Or to put the meta data inside the actual files, at the top level of some datastructure contained in the file in for example JSON or XML.

This is somewhat analogous to the concept of putting information, or namespacing keys in key-value stores. I think this is ok as long as you use it only to namespace and do quick lookups - the key components are not there to provide parsable information. If you need that information, duplicate it into the value (file in the above case).


答:
Let's take a look at Java's String class.

It has a method length(), which returns the length of a String. Often you need to check if a String is empty (e.g. to check if the user has entered a username in a web form). So you do:

```<code>if(username.length() == 0) {
    // Stupid users!
}
</code>```

For convenience, String has the method isEmpty() since Java 1.6. Now, you need only to do:

```<code>if(username.isEmpty()) {
    // Do stuff
}
</code>```

However, the documentation clearly states what isEmtpy() does:

Returns true if, and only if, length() is 0.

There is nothing wrong with it:

Keep the general function (obviously)

Give the specialized function a meaningful name. specialLength() would not give any hint what it does.

In your documentation, make it clear that your specialized function is only a "shortcut" for an existing function, and describe it.

Body:
Let's take a look at Java's String class.

It has a method length(), which returns the length of a String. Often you need to check if a String is empty (e.g. to check if the user has entered a username in a web form). So you do:

if(username.length() == 0) {
    // Stupid users!
}

For convenience, String has the method isEmpty() since Java 1.6. Now, you need only to do:

if(username.isEmpty()) {
    // Do stuff
}

However, the documentation clearly states what isEmtpy() does:

Returns true if, and only if, length() is 0.

There is nothing wrong with it:

Keep the general function (obviously)

Give the specialized function a meaningful name. specialLength() would not give any hint what it does.

In your documentation, make it clear that your specialized function is only a "shortcut" for an existing function, and describe it.


问:
Can I use open source libraries in my project which is released into the public domain?
I am writing a Windows Phone application which I intend to release into the public domain (the source code and releated resources, that is). My application does, however, use a few third party open source libraries (statically linking to them). Does releasing my code into the public domain make any difference regarding the licenses of the open source libraries I use or would I have to make sure my (un)license is compatible with the open source licenses, the same way I would have to if I released the source code using an open source license (or kept the code closed source, for that matter)?

I releasing my code into the public domain doesn't make any difference, how do I know if an open source license is usable with code released into the public domain?

答:
Open source isn't just open source. There are lots and lots of open source licenses with different conditions.

So-called permissive OS licenses like BSD or MIT allow you to do almost anything you want with the covered work, even relicense it under a completely different license, as long as you include a copyright notice.

But there are also share-alike OS licenses like the GPL which only allow derivates to be released under the same license. When you use a GPL library, any software which links to it statically must also be licensed under the GPL. Because this is very inconvenient for libraries, there is a special version of the GPL, the LGPL. LGPL stands for "Lesser GPL" or "Library GPL". It allows to place software which uses the library under any other license as long as you don't make change to the library itself. And even when you do, you just have to distribute the changes to the library under LGPL, not your own application.

And then there are lots of other licenses with their own conditions. So what you should do now is find out which license is used by each of the libraries and then find out what they allow.


问:
What to do when request is sent to server and while waiting for response internet connectivity lost?
I am sending a huge amount of data to server. Now while I have sent the data and waiting for server response, suddenly my android device gets internet connection lost.

So what I used to do is, showing an alert dialog of connection lost, but at server side the data was already processed and it updated somewhere e.g. on any URL. But my android phone does not know this as it did not get response ever. How to resolve it.
Whether it could be done on server side or on android itself How?
How server would know that android phone is not going to listen the response?
It may be client-server communication optimization perspective.

答:
This is a fairly common problem with asynchronous transactions, and falls into several parts.

How do both sides know that the transaction request has been successfully received?

How do you resend a transaction request that the client believes has not been received properly?

How does the server detect repeat requests from the client when the server successfully received the first request?

How does the client know where to get the transaction results from?

The great thing about HTTP is that its fairly easy to solve all of these issues.

Imagine a URL structure like this:

POST http://my.server.com/application/engine/queue
GET  http://my.server.com/application/engine/results?jobid=43425

Using HTTP post to send a request to the server, using a unique client request id - and have the server respond with the job ID. From a clients perspective, if this response does not occur, then the request needs to be resent.  From a servers perspective client request id's need to be cached for a few minutes, in-case the client sends duplicated requests. Duplicated requests are handled simply by returning the same job ID to the client.

The client gets the results of the request from the results URL. This call can be repeated as often as needed to get the results. If its called before the results are available, then the response could be a NO-CONTENT response so the client knows that the server recognises the job id but does not have the content yet.  If the job id is not recognised then NOT-FOUND is the appropriate response.

End result is that the client can always make a sensible action when the network is lost and recovered, and likewise the server can always process requests from the client sensibly


问:
New nodes joining distributed genetic algorithm
I'm sort of torn on what to do for implementation of my distributed genetic algorithm problem. I would like to be able to have nodes join and part at will and not take down the whole system. But this introduces the problem of mismatch of generations. Often times a genetic algorithm simulation is capped by a certain amount of generations and if I have a node that is on 75 out of 100 generations and a brand new node joins the cluster I'm not sure if I should fake it and start at 75 and copy one of the other nodes as a starting point or have it start out at 0 and potentially have the results delayed until the end of execution of the new node. I was hoping someone had some input on what they could see as problems in addition to a long wait time with this new node if I start at 0, I am struggling to think of what could go wrong in both approaches other than that.</p>

答:
start out at 0 and potentially have the results delayed until the end of execution of the new node.

This could make it arbitrary slow: another node could join when you just catched up and so on...

The easiest way is to throw out the whole generation idea:

In reality, there are no generations either, just older and newer individuals, no master clock.

There's no evidence of any advantage of the generational approach.

Unless you want to exactly mimic an existing algorithm, simply cap yours by the total number of individuals. Try to use the nodes in the most efficient way according to their availability.


答:
My advice is usually to never use generation count as a performance metric or termination criterion. Aside from the problem you're facing, it's just too dependent on population size to be of much use. You can't compare across runs, because if your GA has a population of 10 and mine has a population of 10,000 then of course mine will be better than yours over any fixed number of generations, as it gets to do 1000 times more searching.

Just halt the GA after a fixed number of evaluations instead. When a new node joins, it just starts contributing to the global evaluation count. If you want to alleviate some communication overhead, then let each node buffer some number of evaluations locally, and then periodically have them all increment the global counter by however many evaluations they performed since the last update. When the global count passes the limit, just terminate all the nodes and return the answer.

Title: New nodes joining distributed genetic algorithm

Body: I'm sort of torn on what to do for implementation of my distributed genetic algorithm problem. I would like to be able to have nodes join and part at will and not take down the whole system. But this introduces the problem of mismatch of generations. Often times a genetic algorithm simulation is capped by a certain amount of generations and if I have a node that is on 75 out of 100 generations and a brand new node joins the cluster I'm not sure if I should fake it and start at 75 and copy one of the other nodes as a starting point or have it start out at 0 and potentially have the results delayed until the end of execution of the new node. I was hoping someone had some input on what they could see as problems in addition to a long wait time with this new node if I start at 0, I am struggling to think of what could go wrong in both approaches other than that.</p>


答:
This falls under the basics of protocol communication. A transaction has been requested by the Android client, and the Server has to perform the transaction. If the transaction is dependant upon the Android client acknowledgment than this is call ACK/NAK communication.

ACK (acknowledgment) and NAK (negative-acknowledgment) are used to tell the other-side the result of a request.

What you are asking about is a type of handshaking exchange between the client and server, and it can be performed with a basic ACK/NAK exchange.

Here is an example of Android uploading a file with two way acknowledgment.

```<code>Android -> upload files -> Server
Android <- ACK #id <- Server
Android -> ACK #id -> Server
</code>```

In the above example I've added a #id unique identifier for the transaction. The server should receive the files, create a transaction record and send that as the response back to Android. Android should then follow with an acknowledgement of that transaction (or alternatively a NAK for a rejection).

Here is an example of an Android disconnecting during the handshaking.

```<code>Android -> upload files -> Server
Android <- ACK #id <- Server
/** no ACK response **/
</code>```

In the above example the Server has accepted the uploaded files and sent a #id ACK response back to Android, but Android never responds with an ACK. The Android device has failed to complete the handshaking. It's up to you to decide how the Server should handle this. Destroy the transaction, keep the transaction and wait for the Android device to return later or complete the transaction anyway.

The Server can assume that since the device did not respond with ACK. That the Android device did not update it's internal state to indicate that the upload was successful. I would discard the transaction and allow the device to repeat it in the future.

Title: What to do when request is sent to server and while waiting for response internet connectivity lost?

Body:
I am sending a huge amount of data to server. Now while I have sent the data and waiting for server response, suddenly my android device gets internet connection lost.

So what I used to do is, showing an alert dialog of connection lost, but at server side the data was already processed and it updated somewhere e.g. on any URL. But my android phone does not know this as it did not get response ever. How to resolve it.
Whether it could be done on server side or on android itself How?
How server would know that android phone is not going to listen the response?
It may be client-server communication optimization perspective.

Body:
This falls under the basics of protocol communication. A transaction has been requested by the Android client, and the Server has to perform the transaction. If the transaction is dependant upon the Android client acknowledgment than this is call ACK/NAK communication.

ACK (acknowledgment) and NAK (negative-acknowledgment) are used to tell the other-side the result of a request.

What you are asking about is a type of handshaking exchange between the client and server, and it can be performed with a basic ACK/NAK exchange.

Here is an example of Android uploading a file with two way acknowledgment.

Android -> upload files -> Server
Android <- ACK #id <- Server
Android -> ACK #id -> Server

In the above example I've added a #id unique identifier for the transaction. The server should receive the files, create a transaction record and send that as the response back to Android. Android should then follow with an acknowledgement of that transaction (or alternatively a NAK for a rejection).

Here is an example of an Android disconnecting during the handshaking.

Android -> upload files -> Server
Android <- ACK #id <- Server
/** no ACK response **/

In the above example the Server has accepted the uploaded files and sent a #id ACK response back to Android, but Android never responds with an ACK. The Android device has failed to complete the handshaking. It's up to you to decide how the Server should handle this. Destroy the transaction, keep the transaction and wait for the Android device to return later or complete the transaction anyway.

The Server can assume that since the device did not respond with ACK. That the Android device did not update it's internal state to indicate that the upload was successful. I would discard the transaction and allow the device to repeat it in the future.


问:
Entity Framework and distributed Systems
I need some help or maybe only a hint for the right direction.

I've got a system that is sperated into two applications.
An existing VB.NET desktop client using Entity Framework 5 with code first approach and a asp.net Web Api client in C# that will be refactored right yet. It should be possible to deliver OData.
The system and the datamodel is still involving and so migrations will happen in undefined intervalls.

So I'm now struggling how to manage my database access on the web api system. So my favourd approch would be us Entity Framework on both systems but I'm running into trouble while creating new migrations. Two solutions I've thought about:

Shared Data Access dll

The first idea was to separate the data access layer to a seperate project an reference from each of the systems. The context would be the same as long as the dll is up to date in each system. This way both soulutions would be able to make a migration.
The main problem ist that it is much more complicate to update a web api system than it is with the client Click Once Update Solution and not every migration is important for the web api. This would couse more update trouble and out of sync libraries

Database First on Web Api

The second idea was just to use the database first approch an on web api side. But it seems that all annotations will be lost by each model update.

Other solutions with stored procedures have been discarded because of missing OData support and maintainability.

Does anyone run into same conflicts or has any advices how such a problem can be solved!

答:
Assuming you are using a single database for both, I would look at having the database and ORM  layer behind a web service that both UIs can consume. That would allow you to put your business logic where it needs to be and decouple things so that the day you need a mobile interface or whatever else, you don't have to write another data access layer. Assuming you are using WCF on a windows stack, some of the native bindings should be as fast as you need them to be and designing for this environment forces some good habits in terms of data management.

Having the facility to put some logic on the service side also saves on having to write anything twice.

The downside is that updating your API affects all your clients, so you might want to have that well defined to start with and it does mean your desktop client and your web api client are tied in more closely to the application as a whole, but given that they are sharing a data store to start with, that is not necessarily a bad thing.

OwnerDisplayName: Dirk Beckmann


答:
I would avoid branches in the testing code- I would be wanting to find the exact conditions that took me along the X->Y path and test the commonest and boundary paths for that. Then I would identify the conditions that took the user along the X -> Z -> Y path and write a separate test for the boundary conditions of that.

If you aren't using completely deterministic data/mocks so that your tests don't behave totally predictably, you aren't writing unit tests.

If the two tests have a lot in common, you might want to put the shared code into helper or setup/takedown methods so you aren't repeating yourself too much inside your tests.

Depending on the platform you are working with it can be very helpful to have parameterised tests so you can run different data through the same test to cover different boundary conditions.

Title: Are branches in unit tests bad practice?

Body:
Say I want to assert that a certain option menu is displayed in the front-end of a project. The menu is on screen X and I have to first select data in Y to get to X. Now, it doesn't matter at all what data I select in Y, it will always lead to X.

But sometimes, depending on the data, I will get a screen Z which I can just skip through. Now obviously, if I write the test in a deterministic manner the test may fail if the data I selected leads to screen Z.

The data I'm talking about is test data, set up before every test to the same state. So theoretically, I could just select one data entry that I know will not go to screen Z.

But, I could also simply include a check to see if I'm on screen Z after selecting the data and skip Z. Now, even changes to the test data (though rare, it happens) would not break my test.

Somehow I don't like this approach but I can't really explain why. Adding a method to check for Z would add a (probably) "useless" method to my test framework.

So my question is, are branches to handle conditional behaviour that is not being tested in that specific test okay? Are there any problems with this approach? Is it good to do this?


问:
Specifying the format in which I want to get a response through POST
It's a good practice to let a client specify the format in Web REST API:

```<code>GET /api/items/123.csv
</code>```

However, not only GET can return some answer, but POST also can do

```<code>Status: 201 Created

{
  mgs: "Your item has created successfully",
  href: "/example.com/items/123"
}
</code>```

How should URI look like for a POST (PUT or whatever, but not GET) request which returns a response so that a client can specify the format they want the response to be in? Like this?:

```<code>POST /api/items/.csv
</code>```

Or suppose there is an error when a client sends a POST request and the server must inform the client about it:

```<code>Status: 400 Bad Request
{
  mgs: "this is a bad request",
  devMessage: "it's bad because ...."
  friendlyMessage: "something bad happened..."
}
</code>```

What format should it respond in, why and how do I specify it as a client?

P.S. - I'm aware about REST - Tradeoffs between content negotiation via Accept header versus extensions

答:
Why do you want to send back an URL after a POST request? What's usually done is redirecting to the newly created resource. For example:

```<code>Status: 201 Created
Location: /example/items/123
</code>```

All this in the headers.

Same for when an error happens, the status code is enough. 403 Forbidden means what it says.

With regards to the POST URL, the other question definitely answers that.

Body:
Why do you want to send back an URL after a POST request? What's usually done is redirecting to the newly created resource. For example:

Status: 201 Created
Location: /example/items/123

All this in the headers.

Same for when an error happens, the status code is enough. 403 Forbidden means what it says.

With regards to the POST URL, the other question definitely answers that.


问:
A* search for Sudoku
I have a homework problem for an Artificial Intelligence course that I am having trouble answering.

Consider solving the Sudoku problem using A* search. The start state
  has some number of cells filled in, and the successors of each state
  are all legal ways an additional cell can be filled in. At any time we
  know exactly the number of cells that remain to filled.

Therefore, if K cells remain to be filled at node n, we know that h(n)
  = K. Thus if we set our heuristic function h(n) to be h(n)=K, we will have perfect heuristic knowledge in A.

Explain the mistake in the above statement.

I understand that this heuristic is entirely pointless since if there was some function that could find legal successors you might as well run a depth first search but what exactly is wrong with the above statement.

答:
The "legal successor" is not same as "valid successor". Eg. if single cell can contain N numbers, based on current state of the field, then each of them is "legal successor". But only one of them is "valid successor" (assuming it has only one solution).

But I don't agree that it describes number of unfilled cells as perfect heuristic. But that is just my feeling.

And shouldn't you be asking this your professor?

Title: A* search for Sudoku


答:
The solution is simple : create separate project for it, and manage it as separate thing : it's own requirements, testing, conventions, documentation, planning, people, etc.. This way, you ensure that quality remains high and possible breaking changes will get evaluated first before they create a problem.

Or even better : make it "open-source" within your organization. So anyone can change the code, but only few selected people will have full commit rights. And those people will be responsible for ensuring quality and correct features.


问:
Cogent arguments for 'semantic css' over 'object oriented css'
[Context - I'm a Java developer, having a discussion with a designer who works in the html/css space]

I was having a discussion with a co-worker today about the merits of 'semantic css'.

His response was, "Oh we're not interested in semantic css, we use object oriented css"

I understand what he means, ie that they're using the 'inheritance' properties of css and SASS mixins to describe styles. But I feel like he has not tried to understand 'semantic css'.

I'm trying to construct a cogent argument about why 'object oriented css over semantic css' is flawed.

This is my reasoning so far:

“css isn’t object oriented” https://stackoverflow.com/a/7431746/15441

Write html code with semantic components http://css.dzone.com/articles/object-oriented-css-crap-long

Examples of layout out your page with semantic components http://woork.blogspot.com.au/2008/11/css-coding-semantic-approach-in-naming.html

Examples of non-semantic naming http://css-tricks.com/semantic-class-names/

My question is "what are some cogent arguments explain semantic css to someone who thinks that 'inheritance', 'classes' and 'mixins' make something object oriented and that he doesn't need to worry about good naming?"

答:
I personally can get on board with a nice balance of the two where in you have oocss for helpers and you have semantic css for components... and the decision to create a component would come in when you find yourself applying the same oocss elements repeatedly.

I don't get why people are so all or nothing, there needs to be a balance, one nice thing about a balanced approach is the ability to have an over-ride on a semantic class using oocss... so say you have a container defined that has all of the properties you want but you want blue text instead of black, you can use your semantic class followed by a blue text color class and css hierarchy will respect it.
This means you don't have to bloat your css with another almost identical semantic component
and you don't have to write any css at all, just drop in two classes and you're done...


答:
We make the changes to foundation (Foundation-A) and push them out to the nuget feed as an unstable package.

Here's where your problem begins... Don't do that.

Any changes to Foundation v1.0 should inherently be valuable to all consumers of Foundation, otherwise it doesn't belong in Foundation. So, when creating the nuget package, do it as an official, stable version of Foundation (i.e. v1.1), or don't do it at all.

Project B should build its Foundation enhancements as it normally would, but (in good source management fashion) should merge in the trunk changes (v1.1) before pushing a stable Foundation (v1.2) to nuget.

Other projects which can use the Foundation enhancements can upgrade their nuget references when appropriate, or stick with the older versions if they need to.

I agree with @Giedrius; this seems to me to be more of a source control/branching issue in the sense that if the branching/merging of Foundation is handled properly, the package management issues become moot.


问:
Why do books say, "the compiler allocates space for variables in memory"?
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".

答:
Saying "the compiler allocates memory" may not be factually accurate in the literal sense, but it's a metaphor that's suggestive in the right way.

What really happens is that the compiler creates a program that allocates its own memory.  Except that it isn't the program that allocates memory, but the OS.

So what really happens is that the compiler creates a program that describes its memory requirements and the OS takes that description and uses it to allocate memory.  Except that the OS is a program, and programs don't actually do anything, they describe a computation that is performed by the CPU.  Except that the CPU is really just a complicated electronic circuit, not an anthropomorphised little homonculus.

But it makes sense to think of programs and compilers and CPUs as little people who live inside a computer, not because they actually are, but because that's a metaphor that fits the human brain well.

Some metaphors work well for describing things on one level of abstraction, but don't work as well on another level.  If you think on the level of the compiler, it makes sense to describe the act of generating code that will result in memory being allocated when the program that is being compiled is actually run as "allocating memory".  It's close enough that when we're thinking about how a compiler works, we have the right idea, and it's not so long-winded that we forget what we were doing.  If we try to use that metaphor on the level of the compiled program running, it's misleading in a weird sort of way, which is what you noticed.


答: Did they leave you a set of TDD Tests, Acceptance Tests, or other Unit Tests?  They do a good job of documenting how an application works and is expected to work, as well as providing a sample implementation of how to use what was developed.</p>

Title: The Agile process: how and what should be documented?

Body:
A while ago the company I work for had outsourced a development project to a third party. They employed agile practices in developing the solution. However when asked for documentation they would just say it was required as it was incorporated in a wiki or as part of their sprints.

They did leave at the completion of the project, with all but one of the project team. The project wiki site has now been closed down once the yearly subscription was due.

When they left they took most of the knowledge and understanding of what was developed with them.

So I do have 2 main questions;

Is this normal for agile or just an excuse for not wanting to write it?

What are the industry norm for documentation in agile projects to record development
requirements, designs, key decisions and context?


问:
What's the most effective way to share code between .NET applications?
In our work, we have several different .net applications that share a lot of base functionality.  We've built these applications using a clean n-tier architecture, but we've hit that moment where we realize that we've re-implemented the same functions several different times.  Obviously this violates DRY, and we would like to correct that.  We're already using Nuget to some success for common glue code (wiring up IoC, logging, settings), but we also would like to share our data and business layers between all our applications.  The idea is that the UI would only deal with the parts of the business layer it actually needs.

This seems like a straight-forward problem at first, but ongoing development could provide some pitfalls and we're not sure how to proceed.  Let's say we make our One Business Layer to Rule Them All.  For brevity, I'll call it "Foundation."  We port our applications to use the Foundation, and everything is runnding great.  The Foundation is distributed to light UI layers via nuget, and we're looking good.  But then we start adding features to our applications, and we run into trouble.

Let's say we're working on Project A and we add a new feature that requires changes to Foundation.  We make the changes to foundation (Foundation-A) and push them out to the nuget feed as an unstable package.  Project A gets the latest nuget package, and all is good.  Meanwhile, another developer is working on Project B.  He gets the latest Foundation from source control, but takes it from a stable branch, so that it doesn't have Project A changes in it.  He makes changes and created Foundation-B.  And all is good.  But then we discover that Foundation-A and Foundation-B implementation functionality that could actually share code, so we combine them.  Meanwhile Foundation-C is floating out there with it's own changes.  Eventually, Foundation-B is ready for production, so we push it out.  But then we need to update Production A, B, & C with the new foundation, so we update the nuget packages and deploy (as long as nothing breaks).

This seems like it could work, but we're worried about working with different database schemas and keeping everything synchronized between the various branches of the Foundation repository as well as the Project A, B, and C repositories.  It seems like it will probably take a lot of manual work, which opens up the possibility for errors.  I would like this as automated as possible.

Here's the stack we're using: C#, TFS with Continuous Integration, Nuget. Our applications are all various types of ASP.NET applications.  We're willing to look at different SCM's if it will make things easier.

I'm looking for ways to keep Nuget sane with our different source code branches.  We don't want to accidentally push development code into production because we reference the wrong Nuget Package.

答:
Code Reuse

There have been several approaches to code reuse that have found favour over the years.  Each approach has it's place, and more importantly its issues, but the viable ways to reuse code in .NET are:

Common Library.  The code that is needed in more than one place is put into a common library, and all other parts of the code base then have a single reference to this code. The principle downside is that you end up with the majority of your project depending on this library which contains lots of unrelated functions. This is a bad idea from a quality assurance aspect.

Common Source Code. The code that is needed in more than one place is written once and placed in a source file in a common directory structure. All projects that need this code then include this file as one of their source files.  This provides code reuse, and the advantages of write once, use many.  However. Its downside is that it becomes possible to have different parts of the project compiled with different versions of this code - which may introduce some subtle defects that can be very tricky to detect and identify by quality assurance.

Service. The common code is implemented as a service, that other aspects can access. This has the advantage that there will be a single service in a deployment, and avoids dependencies.  However it will introduce latency and failures.  This kind of approach works well in large distributed products where high availability and fault tolerance are already understood and managed.

Managing NuGET

Here you have a much more interesting problem.  Managing multiple configurations. My advice here is to not to manage a diverse customer base with different code versions, but with configuration files. There are at least 3 layers of configuration data to manage.  Base (internal) product configuration that the customer never sees. The default configuration options that your customer may change and the final layer of configuration options that your customer have changed.  By separating these different layers you will be able to roll out upgrades without destroying your customers configurations.


答:
In general when you are testing, you want to avoid any uncertainty and you want to keep the test to the point. Uncertainty/randomness in the data or in the test logic will only make things more complicated/less understandable to you or other developers which leads to a maintenance nightmare. This is true for all tests across the board.

This means only set up data (if possible) that is required to test that one thing. This will make the tests easier to understand and maintain because there is less distractions from what matters. It also makes tests more decoupled from each other because the data you are using for the one functionality does not interfere with other tests. For smaller applications with a small test suite you might get away with 'single large test data' up front. However, maintaining such large data set becomes a nightmare when you are working with a larger application.

As far as the test logic is concerned, you do not want to clutter it with conditionals like if by any chance I got this intermediate thing, ignore it and continue. In a test you should always know what action leads to what state so you should specifically code for it. Such conditional statements only distract from what is important about the test and may lead to more code that simply deals with these 'possibilities' than the test code itself. Another problem with this approach is that the application and test code can get out of sync. As the application evolves you remove state Z but it does not get cleaned up from the test code itself because it was there only conditionally (tests will not break, therefore not signal that there is a problem). This can be extremely stressful especially for someone who is new to the code base because now they have to dig to see what this code is all about.


答:
This isn't an answer, but it's too long for a comment...

Using that remaining-distance metric, you can certainly implement an A* search and it will give the correct result, but it will be extremely inefficient. The reason is that it's really a Dijkstra search disguised as A*. Worse than that, as Shawn notes, it's really a simple breadth-first search.

The reason it has decayed to Dijkstra is because your metric gives no clues as to which is the best direction to take through the state space. Each step from a particular intermediate state is just filling in one digit in one cell - precisely as cheap/costly as filling in any other possible digit/cell at that point and with no clue as to which successor states (with the same number of empty cells) are closer to a correct solution. All paths from that intermediate state to the solution are the same length, including the ones leading through illegal states to a broken solution.

This is legal in the sense that the distance metric is a lower bound to the remaining distance to a solution. But it's not just a lower bound, it's an exact distance. Your "perfect heuristic" isn't guiding the search towards the solution in any useful way beyond what Dijkstra could do.

The reason it has decayed to a breadth-first search is the same thing, but in terms of the weights of edges already traversed so far. Every path from the start to any intermediate state has the same number of edges and the same total cost (same number of cells filled in). Every edge effectively has weight one, and there are no short-cuts for Dijkstra to exploit.

In practice, Sodoku solvers usually use backtracking depth-first search with relatively cheap checks (if there are two of the same digit in any cell, row or block, this state is impossible as are all possible successor states) to avoid searching impossible parts of the search space. There's not much guidance you can get on which intermediate states are better without spending more on the heuristics and search algorithm than you gain by pruning the search tree further, and besides, backtracking search with that simple pruning is very fast.

Title: A* search for Sudoku

Body:
I have a homework problem for an Artificial Intelligence course that I am having trouble answering.

Consider solving the Sudoku problem using A* search. The start state
  has some number of cells filled in, and the successors of each state
  are all legal ways an additional cell can be filled in. At any time we
  know exactly the number of cells that remain to filled.

Therefore, if K cells remain to be filled at node n, we know that h(n)
  = K. Thus if we set our heuristic function h(n) to be h(n)=K, we will have perfect heuristic knowledge in A.

Explain the mistake in the above statement.

I understand that this heuristic is entirely pointless since if there was some function that could find legal successors you might as well run a depth first search but what exactly is wrong with the above statement.