问:
Any tools/suggestions on how to refute code coverage quality argument
Now I know people could consider this question duplicate or asked many times, in which case I would appreciate a link to relevant questions with answer to my question.

I have been recently in disagreement with some folks about code coverage. I have a group of people who want our team to drop looking at code coverage altogether based on the argument that 100% coverage does not mean good quality tests and thus good quality code.

I have been able to push back by selling the argument that Code Coverage tells me what has not been tested for sure and help us focus on those areas.

(The above has been discussed in a similar fashion in other SO questions like this one - https://stackoverflow.com/questions/695811/pitfalls-of-code-coverage)

The argument from these folks is - then team would react by quickly creating low quality tests and thus waste time while adding no significant quality.

While I understand their point of view, I am searching for a way to make a more robust case for code coverage by introducing more robust tools/frameworks that take care of more coverage criteria (Functional, Statement,Decision, Branch, Condition, State, LCSAJ, path, jump path, entry/exit, Loop, Parameter Value etc).

What I am looking for is suggestion for a combination of such code coverage tools and practices/processes to go with them which can help me counter such arguments while feeling comfortable about my recommendation.

I would also welcome any accompanying comments/suggestions based on your experience/knowledge on how to counter such an argument, because while subjective, code coverage has helped my team be more conscious of code quality and value of testing.

Edit: To reduce any confusion about my understanding of weakness of typical code coverage, I want to point out that I am not referring to Statement Coverage(or lines of code executed) tools(there are plenty). In fact here is a good article on everything that is wrong with it: http://www.bullseye.com/statementCoverage.html

I was looking for more than just statement or line coverage, going more into multiple coverage criteria and levels.

See: http://en.wikipedia.org/wiki/Code_coverage#Coverage_criteria

The idea is that if a tool can tell us our coverage based on multiple criteria then that becomes a reasonable automated assessment of test quality. I by no means am trying to say that line coverage is a good assessment. In fact that's the premise of my question.

Edit:

Ok, maybe I projected it a bit too dramatically, but you get the point. The problem is about setting processes/policies in general across all teams in a homogeneous/consistent fashion. And the fear is general that how do you ensure quality of tests, how do you allocate guaranteed time without having any measure to it. Thus I like having a measurable feature that when backed up with appropriate processes and the right tools would allow us to improve code quality while knowing that time is not being force spent in wasteful processes.

EDIT: So far what I have from the answers:

Code reviews should cover tests to ensure quality of tests

Test First strategy helps avoid tests that are written after the fact to simply increase coverage %

Exploring alternative tools that cover test criteria other than simply Statement/Line

Analysis of covered code/number of bugs found would help appreciate the importance of coverage and make a better case

Most importantly trust the Team's input to do the right thing and fight for their beliefs

Blocks Covered/# of tests - Debatable but holds some value

Thanks for the awesome answers so far. I really appreciate them. This thread is better than hours of brainstorm with the powers that be.

答:
"team would react by quickly creating low quality tests and thus waste time while adding no significant quality"

This is a real risk, not just theoretical.

Code overage alone is a dysfunctional metric. I learned that lesson the hard way. Once, I emphasized it without the availability of balancing metrics or practices. Hundreds of tests that catch and mask exceptions, and without assertions is an ugly thing.

"suggestion for a combination of such code coverage tools and practices/processes to go with them"

In addition to all the other suggestions, there is one automation technique that can assess the quality of tests: mutation testing (http://en.wikipedia.org/wiki/Mutation_testing). For Java code, PIT (http://pitest.org/) works, and it's the first mutation testing tool I've come across that does.

As you note, lack of code coverage is readily identifiable as a software quality risk. I teach that code coverage is a necessary, but insufficient, condition for software quality. We have to take a balanced scorecard approach to managing software quality.


问:
C++ and the suitable libraries to develop Autocad/Autodesk/CAD applications?
I saw a job opening where the requirement was for a developer
 to develop CAD tools using C++ and OpenGl libraries.

I am a civil engineer and want to be part of such a projects so I thought to learn
C++ and some libraries which could help me to move forward for such job opportunities.

I know a bit of C++ but I am quite unfamiliar with these libraries(qt, openGL).

Can somebody tell me/guide me which is the most suitable library and most required library to develop such applications?

答: I am faced with a similar predicament.  One library I found very useful is tetgen. One use is to break faces of 3D solids into triangles. 3D graphics libraries such as Direct3D and OpenGL require that surface meshes (outer surface of 3D objects) are specified as triangles. tetgen is also used in FEA applications to break down a solid into tetrahedra. http://tetgen.org</p>

ContentLicense: CC BY-SA 3.0


问:
TDD workflow for (implementation specific) edge cases
When developing features with TDD, I create a test for each combination of feature and case. So, one test for creating user successfully, one for validation errors, and one for database errors. I don't test each one with many different types of data, in general, as I write the tests to flesh out features, less to catch errors. I don't think it's time-effective to write out several cases (even with a "data provider") for every single feature I develop in order to validate that the feature works correctly in all cases.

Sometimes, though, there are certain implementation specific bugs to be wary of when implementing the feature. After writing the feature test that allows me to write the implementation, I'll notice that certain edge cases need to be tested more carefully because of the implementation.

How does one organize these tests with the rest of the feature-specific tests? Are the tests I'm describing regression tests?

Edit:

I guess I wasn't clear about what I meant with "different types of data" and "works well in all cases." My main issue is in writing implementation-specific tests--specifically the workflow and organization.

We are testing the interface. We're specifically testing the feature only, at first. But a certain implementation requires more tests.

答:
Any test that is used to validate ongoing development of software can be considered a "regression test", i.e. making sure some new change doesn't break old fixes/enhancements.  However I don't think it helps to single out the "edge case" testing you describe as specifically "regression tests".  TDD is filled with regression tests.

I do see the value of the edge case testing you describe, and the importance of "organizing" them with the TDD feature-minimal tests that are commonly co-written with the code.  One simple principle regarding sequence of running tests would be to arrange them in the same order in which they are added.  Of course, noting your "unit tests" tag, there may be a hierarchy of code modules, and edge cases may require testing at some intermediate level between a unit (or single routine) and the whole package (application or library).

A TDD approach would emphasize testing that is closely integrated with builds, so presumably the specifics of organizing the tests finds its natural expression in terms of the build tools you use.

Added: A nice 2009 write-up on distinguishing the test cases that drive development/specification from the unit tests that validate acceptance criteria (such as the correctness of edge cases you describe):

TDD Tests are not Unit Tests -- Stephen Walther


问:
What algorithm should I use to find the shortest path in this graph
I have a problem about the calculation of shortest paths on an unweighted and undirected graph.

Which algorithm I use to calculate the shortest path between a node A and node B that passing through a node C on an undirected and unweighted graph?

答:
Like ratchet freak pointed out, you'll have to split the solution into finding a path from A to C and then from C to B.

However, Dijkstra is not needed since the graph doesn't have any weight. A simple Breadth First Search (BFS), slightly easier to implement, is enough.

Also, if you were to implement A*, no weight doesn't mean that you cannot find a heuristic. You could still favor paths that go through nodes with a certain property as a heuristic.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答: One return per function/method.</p>

ContentLicense: CC BY-SA 2.5

Body: One return per function/method.


答:
If you can send in different types of data to your methods, and some of those types have a chance of working incorrectly, then you need to be testing those possibilities. Plain and simple.

However, if that is really the case, I think the actual problem is that your code is not set up cleanly. I smell problems.

What I'm going to do is first talk about how to  refactor your code so that it can easily be tested. Then, I'll explain how you might approach testing a system like the one you've described, if you have to (my hope is that you don't).

Code Refatoring (the best solution)

First, lets talk about why your methods allow so many different types to be sent in when they don't work consistently with them. This is an obvious code smell that should probably be addressed. My guess is that you need to refactor your code so that this isn't a problem in the first place. An approach I would take might look like this:

I'm going to make sure that all objects sent to this method have a common interface

I'm going to have the method only use this common interface to do what it needs

The objects themselves will each have their own implementation of the interface that will always work for that type of object.

If you do this, you can now easily test the method and see that it is correctly using the common interface. You now know that this code is working no matter what object you put in. The interface is defined, so the correct action is taken.

You will also test each of the objects that implement the interface, and make sure that they have implemented it correctly for the type of object it is. Once you've tested that, you are done, you know everything is working without a million different tests testing each object with each type.

To illustrate, I've put together some pseudo-code to demonstrate. Lets say your code looks like this:

```<code>function output_to_file (shape x) {
    if (x is a triangle) {
        // output to file
    } else if (x is a square) {
        // output to file
    } else if (x is a pentagon) {
       // output to a file
    }
}
</code>```

Then your tests are going to require you to send every different type of shape to the output_to_file method. If you have a whole bunch of methods like this, and a whole bunch of shapes, you will need a whole bunch of tests. Every time you add a shape, you need to modify your output_to_file code and add tests. No fun at all. Not good code.

Instead, you need to refactor your code to look more like this:

```<code>function output_to_file (shape x) {
    text = x.get_text_representation()
    save text to a file
}
</code>```

Instead of handling the details of each shape, output_to_file just uses a common interface: the method get_text_representation.

Now to test output_to_file all you have to do is check that it is calling get_text_representation and putting the results in a file. If it is doing that, it is working. The output_to_file method now follows the "open/closed" principle. It is open to new types of objects being sent in (as long as they support the interface), but closed to the need for additional changes.

This means of course that our shapes need the get_text_representation function. But that is simple:

```<code>class triangle {
    function get_text_representation {
       // return whatever
    }
}

class square {
    function get_text_representation {
       // return whatever
    }
}

//and so on
</code>```

Now we test the get_text_representation method on each of those objects to make sure that they are working like they should. That method might be used in a variety of places, but we don't really care, as long as it is working right we know that other methods relying on it will work right.

By setting up our objects in a different way, we've eliminated the need to test a whole bunch of different objects/method combinations. We test that the method is using the correct interface, and we test that the objects implement the interface correctly. Nothing more is needed. Yay!

Testing More Cases (the less than best solution)

Now perhaps you've been reading this so far, and you're thinking, "well that is nice and all, but I can't do that, he doesn't understand my situation."

Ok, first, try really hard to refactor your code. I'll be worth it. Did you try? Ok then, I'll give you benefit of the doubt and assume you are in some type of complicated situation that can't be refactored the way it should be (but I still don't believe you).

Here's the deal: you have to test each possible different type of object with each different method. You just have to. If some of those object/method combinations can cause error, you must test. Sorry.

Now, if it seems tedious or repetitive to be testing the same methods with different types of input again and again, you can automate the process somewhat. A lot of people forget that you can code your tests to do repetitive things for you. Let me give an example of how you might set up your test:

```<code>test_objects = {new triangle, new square, new pentagon .... }

function test_output_to_file {
   foreach (test_objects as x) {
      output_to_file(x)
      assert everything is good
   }
}
</code>```

This is really the best you can do if you can't refactor your code correctly. Is it tedious, yes. Is it clean, no. Refactor your code if you can, this isn't a good alternative.

Conclusion

In conclusion, the problem you are describing -- being able to send many different types of data to many different functions, some of which are not supported or buggy -- is probably an indication that your code isn't clean. Testing isn't the problem, and refactoring your code is the solution.

If for some reason refactoring isn't possible (I find that hard to believe!) then you are going to have to bite the bullet and test every combination. Make some structure that allows you to do that a little more easily.

I highly recommend anyone interested in creating clean, testable code to read the book Clean Code by Robert C Martin.

Title: TDD workflow for (implementation specific) edge cases

Body:
When developing features with TDD, I create a test for each combination of feature and case. So, one test for creating user successfully, one for validation errors, and one for database errors. I don't test each one with many different types of data, in general, as I write the tests to flesh out features, less to catch errors. I don't think it's time-effective to write out several cases (even with a "data provider") for every single feature I develop in order to validate that the feature works correctly in all cases.

Sometimes, though, there are certain implementation specific bugs to be wary of when implementing the feature. After writing the feature test that allows me to write the implementation, I'll notice that certain edge cases need to be tested more carefully because of the implementation.

How does one organize these tests with the rest of the feature-specific tests? Are the tests I'm describing regression tests?

Edit:

I guess I wasn't clear about what I meant with "different types of data" and "works well in all cases." My main issue is in writing implementation-specific tests--specifically the workflow and organization.

We are testing the interface. We're specifically testing the feature only, at first. But a certain implementation requires more tests.

Body:
If you can send in different types of data to your methods, and some of those types have a chance of working incorrectly, then you need to be testing those possibilities. Plain and simple.

However, if that is really the case, I think the actual problem is that your code is not set up cleanly. I smell problems.

What I'm going to do is first talk about how to  refactor your code so that it can easily be tested. Then, I'll explain how you might approach testing a system like the one you've described, if you have to (my hope is that you don't).

Code Refatoring (the best solution)

First, lets talk about why your methods allow so many different types to be sent in when they don't work consistently with them. This is an obvious code smell that should probably be addressed. My guess is that you need to refactor your code so that this isn't a problem in the first place. An approach I would take might look like this:

I'm going to make sure that all objects sent to this method have a common interface

I'm going to have the method only use this common interface to do what it needs

The objects themselves will each have their own implementation of the interface that will always work for that type of object.

If you do this, you can now easily test the method and see that it is correctly using the common interface. You now know that this code is working no matter what object you put in. The interface is defined, so the correct action is taken.

You will also test each of the objects that implement the interface, and make sure that they have implemented it correctly for the type of object it is. Once you've tested that, you are done, you know everything is working without a million different tests testing each object with each type.

To illustrate, I've put together some pseudo-code to demonstrate. Lets say your code looks like this:

function output_to_file (shape x) {
    if (x is a triangle) {
        // output to file
    } else if (x is a square) {
        // output to file
    } else if (x is a pentagon) {
       // output to a file
    }
}

Then your tests are going to require you to send every different type of shape to the output_to_file method. If you have a whole bunch of methods like this, and a whole bunch of shapes, you will need a whole bunch of tests. Every time you add a shape, you need to modify your output_to_file code and add tests. No fun at all. Not good code.

Instead, you need to refactor your code to look more like this:

function output_to_file (shape x) {
    text = x.get_text_representation()
    save text to a file
}

Instead of handling the details of each shape, output_to_file just uses a common interface: the method get_text_representation.

Now to test output_to_file all you have to do is check that it is calling get_text_representation and putting the results in a file. If it is doing that, it is working. The output_to_file method now follows the "open/closed" principle. It is open to new types of objects being sent in (as long as they support the interface), but closed to the need for additional changes.

This means of course that our shapes need the get_text_representation function. But that is simple:

class triangle {
    function get_text_representation {
       // return whatever
    }
}

class square {
    function get_text_representation {
       // return whatever
    }
}

//and so on

Now we test the get_text_representation method on each of those objects to make sure that they are working like they should. That method might be used in a variety of places, but we don't really care, as long as it is working right we know that other methods relying on it will work right.

By setting up our objects in a different way, we've eliminated the need to test a whole bunch of different objects/method combinations. We test that the method is using the correct interface, and we test that the objects implement the interface correctly. Nothing more is needed. Yay!

Testing More Cases (the less than best solution)

Now perhaps you've been reading this so far, and you're thinking, "well that is nice and all, but I can't do that, he doesn't understand my situation."

Ok, first, try really hard to refactor your code. I'll be worth it. Did you try? Ok then, I'll give you benefit of the doubt and assume you are in some type of complicated situation that can't be refactored the way it should be (but I still don't believe you).

Here's the deal: you have to test each possible different type of object with each different method. You just have to. If some of those object/method combinations can cause error, you must test. Sorry.

Now, if it seems tedious or repetitive to be testing the same methods with different types of input again and again, you can automate the process somewhat. A lot of people forget that you can code your tests to do repetitive things for you. Let me give an example of how you might set up your test:

test_objects = {new triangle, new square, new pentagon .... }

function test_output_to_file {
   foreach (test_objects as x) {
      output_to_file(x)
      assert everything is good
   }
}

This is really the best you can do if you can't refactor your code correctly. Is it tedious, yes. Is it clean, no. Refactor your code if you can, this isn't a good alternative.

Conclusion

In conclusion, the problem you are describing -- being able to send many different types of data to many different functions, some of which are not supported or buggy -- is probably an indication that your code isn't clean. Testing isn't the problem, and refactoring your code is the solution.

If for some reason refactoring isn't possible (I find that hard to believe!) then you are going to have to bite the bullet and test every combination. Make some structure that allows you to do that a little more easily.

I highly recommend anyone interested in creating clean, testable code to read the book Clean Code by Robert C Martin.


问:
Product backlog- when do task hours get estimated?
I am wondering if when developing a product backlog do tasks have hours estimated for them. To confirm, i can talking about a product backlog here not a sprint backlog as I know it does have. </p>

答:
The preferred type of Product Backlog Item for a Scrum team is a User Story not a task.

User stories are usually estimated in Story Points. There is no set point at which to estimate a story.

Scrum teams use Planning Poker to estimate stories, which most teams usually do shortly after the initial backlog is created. As new stories are generated through out development, teams tend to run Planning Poker to estimate those stories once per iteration. Some teams don't even estimate at all and just count the number of stories, although this relies on breaking stories down to a fine granularity.

The time which Scrum teams normally create tasks is during the Sprint Planning Meeting. The team create the list of tasks necessary to delivering all the selected product backlog items. Each task on the sprint backlog is also usually estimated.

As with user stories, I've seen several different techniques used to estimate the work required.  Some teams use story points, others use "ideal man days". Some teams again don't bother and use the number of tasks. The purpose of estimating these tasks is so that you can keep track of progress within a sprint and as a secondary check (to the story points) that the team is not taking on too much work.

I never really have tasks on the product backlog, I normally would keep them within a Sprint. However, I have previously added Spikes to the product backlog. However, they aren't really estimated - they are time-boxed, meaning you set a time limit which you do the work within. A Spike is a kind of information gathering exercise, the code that is created is intended to be thrown away. After the spike, you usually use the information it has gathered to create some stories that can be estimated in the usual fashion.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
"Traditional" control structures like for are about controlling the working man, keeping him subservient to the corrupt ideologies of the ruling capitalist elite.  That's why I use alternative control structures like ph0r instead.  It's like for, but more radical: You won't catch ph0r wearing a suit and tie, spouting some corporate BS.  ph0r keeps it real, man.

Fight the power!


问:
Frontend vs Backend data handling
Firstly I would like an answer from an experienced person (not a one man band), someone whom has worked in a medium/large team and had to battle with this burning question before.

The problem:
I am constantly being asked to not submit empty rows

by rows = I mean a list of items and properties.

A good example would be, multiple file uploads.

```<code><form>
    <input type="text" name="pic[0][label]" />
    <input type="file" name="pic[0][file]" />

    <input type="text" name="pic[1][label]" />
    <input type="file" name="pic[1][file]" />

    <input type="text" name="pic[2][label]" />
    <input type="file" name="pic[2][file]" />
    <input type="submit" value="Upload" />
</form>
</code>```

The requirement states:

As a user I should be presented with fields 3 (three) upload fields.

For each field there should be a corresponding title/name/label

There should be a "Add more" button, to allow me (the user) to add more images.

The reason for the requirement above is user experience. (Less clicks are required)

The Backend argument

Submitting empty rows (to the server) is "error prone" or is seen as a "validation corner"

The Front-end argument

Backend should not dictate what the FE can/cannot do.

JavaScript is very volatile and should not manage/validate whether empty rows should be sent or not

The question

if the user:

Enters 1 (one) title/label

Selects 1 (one) image from his/her local PC

Clicks Upload

Leaves the last 2 (two) upload fields empty.

So in your opinion/experience with this kind of problem. Should the front end send empty rows or data to the server or not?

答:
I really don't see a problem with empty rows.

Its quite common in forms (and most other user UIs) to have optional fields which are not filled in. The back end should simply ignore the empty rows.

Compare the costs of the two solutions.

Back End ignores empty rows. One if statement and two curly brackets.

Front End filters out empty rows. About forty lines of bug prone JavaScript.

OwnerDisplayName: Val

Title: Frontend vs Backend data handling


问:
How to optimize calls to multiple APIs at once and return as one set?
I have a web app that searches across 2 APIs right now.  I have my own Restful web service that I call, and it does all the work on the backend to asynchronously call the 2 APIs and concatenate them into one result set for my web app to use.

I want to scale this out and add as many other APIs as I can (currently looking at about 10 more).  But as I add APIs, the call to my service gets (potentially) slower and more complex.  How do I handle one API not responding ... and other issues that arise?

What would be the best way to approach this?  Should I create a service call for each API, that way each one is independent and not coupled to all the other calls?  Is there a way on the backend to handle the multiple API calls without all the extra complexity it adds?

If I go the route of a service call per API, now my client code gets more complex (and I have a lot of clients)?  And it's more work for the client, and since I have mobile apps, it will cost the client more data usage.

If I go one service call, is there a way to set up some sort of connection so I can return data as I get it, in case one service call hangs?

答:
How would you handle one of the API calls failing? If only some of the calls succeed is it still a valid response to the client?

Since websockets aren't widely supported and you are talking mobile platforms I think you have limited choices.

Long running requests

If the expected response is such that it may be processed in chunks before all requests complete, you may be able to stream the results in a single connection.
Ajax patterns provides some good information and examples for reading from a response stream before it has completed.

Using this approach, you would make a single request and handle the response as each API request completes.

Along with this, you will want to timeout individual API requests aggressively so that a hung service doesn't heavily impact your interface.

Yo don't want the client to timeout before done.

You could go as far as skipping calls for an expanding amount of time for any services which timeout or fail.

If it's an aggregated news feed or something this may make sense but you could poll and cache the feeds server side instead.

Long polling

Instead of a single request, you could make an initial request and then poll for additional data. This has the advantage of not holding the connection and appearance of being a push.

This would completely defeat your intent of limiting the number of connections.

In conclusion

With all this said, I still think you need to consider all the factors of your design.

what is the upper limit of API calls that will be made behind this proxy? 10 may be ok but at 20 or 30 is this still the right design?

do all clients need the data from all services? Are you saving a little at the expense of all?

what is the quantifiable amount of bandwidth and processing time saved using the proxy for say 1000 requests? Is this worth it?


问:
Is using non-standard single-line comments fine in C?
I noticed Visual C++ 2010 (my current environment) and XCode both allow non-standard single-line comments in my C programs. Since these are both my target platforms, I assume it's fine to use it? VC++ 2010 doesn't support C99, so I'm limited to C89, though I know C99 added support. </p>

答: Anything that works is fine as long as you don't care about the environments where it doesn't work.  If you have no ambitions to compile your code in an environment that doesn't support one-line comments (presumably comments that begin with <code>//</code> and continue to the end of the line), then it's fine.  </p>

Body: Anything that works is fine as long as you don't care about the environments where it doesn't work.  If you have no ambitions to compile your code in an environment that doesn't support one-line comments (presumably comments that begin with // and continue to the end of the line), then it's fine.


问:
In which file types I should include the copyright header?
My manager told me to include 15 line copyright notice on top of every file.

I am not sure whether I need to include in sql, xml, txt, documention, config files or even html templates.

In which files should I include copyright notice?

答:
The type of file doesn't matter. What matters is whether someone may be interested in stealing the source code, reuse it in a different project, and make profits.

Imagine your SQL file has a bunch of flat select queries. Having a 15-lines copyright notice feels ridiculous. If someone copy-pastes those selects and uses them elsewhere, would you be able to prove in court that indeed, those are your selects, a product of days of hard work, and not simply a different bunch of selects that another person wrote in a few minutes?

Imagine another SQL file has dozens of stored procedures which deal with some complicated business rules, and do a great job where your competitors were unable to achieve the same result. Now, it seems much more useful to include a copyright notice.

The same applies for other types, with two exceptions:

1. Coding conventions

If you use a tool such as StyleCop for C# which enforces specific coding conventions on commit, and one of the rules is to have a copyright notice, then you have no choice: adding:

```<code>// <copyright file="HelloWorld.cs" company="Example Inc.">
//      Copyright (c) Example Inc. All Rights Reserved.
// </copyright>
</code>```

even on a file containing an elementary piece of code is much faster than adding style suppressions.

2. Control freak

If your manager/boss/customer is convinced that unless there are copyright notices everywhere, someone will undoubtedly steal his idea—the greatest idea of the century, simply add the damn notices; you'll save hours of quarrels and blame.

Body:
The type of file doesn't matter. What matters is whether someone may be interested in stealing the source code, reuse it in a different project, and make profits.

Imagine your SQL file has a bunch of flat select queries. Having a 15-lines copyright notice feels ridiculous. If someone copy-pastes those selects and uses them elsewhere, would you be able to prove in court that indeed, those are your selects, a product of days of hard work, and not simply a different bunch of selects that another person wrote in a few minutes?

Imagine another SQL file has dozens of stored procedures which deal with some complicated business rules, and do a great job where your competitors were unable to achieve the same result. Now, it seems much more useful to include a copyright notice.

The same applies for other types, with two exceptions:

1. Coding conventions

If you use a tool such as StyleCop for C# which enforces specific coding conventions on commit, and one of the rules is to have a copyright notice, then you have no choice: adding:

// <copyright file="HelloWorld.cs" company="Example Inc.">
//      Copyright (c) Example Inc. All Rights Reserved.
// </copyright>

even on a file containing an elementary piece of code is much faster than adding style suppressions.

2. Control freak

If your manager/boss/customer is convinced that unless there are copyright notices everywhere, someone will undoubtedly steal his idea—the greatest idea of the century, simply add the damn notices; you'll save hours of quarrels and blame.


答:
In systems like this, you always have to consider that as far as your code is powerful, at least a call will be delayed, and if your system is successful, that event will happen hundreds of times making your system slow, then maybe unstable.

I do not know the nature of the integration, maybe game providers, maybe social networks or anything else. But if your application is not academic, and it represents a real business requirements (in production) I think this is part of the things to do:

Before code

if possible, all systems that are integrated, they must be aware of the timeouts that are demanded from you (anticipating this from a contractual point of view, it is a good idea mostly because no one guarantees 100% of up-time. It's myth).

if point 1 is not possible, be objective and consider what we are willing to make our customers wait in front of the monitor (45 seconds, 10, 5, 2?). Found the value, we know how to set up the rest.

Should be considered a constant calls/sub-calls prifile and logging;

Should be planned for the possibility of suspending one or more services from the configuration (and not from code);

Technique

As for the technique, I think it is convenient to create a semaphore.

N functions will be called, the callback of each sub-function will be considered only if time set for each integration are respected.

So,

A call is made to the main function,

This considers what services are enabled to be contacted,

The callback functions are configured,

The sub-functions are called,

While making calls, and while the general timer has not expired, all callbacks are considered to be unified in the response of the main function.

Title: How to optimize calls to multiple APIs at once and return as one set?

Body:
I have a web app that searches across 2 APIs right now.  I have my own Restful web service that I call, and it does all the work on the backend to asynchronously call the 2 APIs and concatenate them into one result set for my web app to use.

I want to scale this out and add as many other APIs as I can (currently looking at about 10 more).  But as I add APIs, the call to my service gets (potentially) slower and more complex.  How do I handle one API not responding ... and other issues that arise?

What would be the best way to approach this?  Should I create a service call for each API, that way each one is independent and not coupled to all the other calls?  Is there a way on the backend to handle the multiple API calls without all the extra complexity it adds?

If I go the route of a service call per API, now my client code gets more complex (and I have a lot of clients)?  And it's more work for the client, and since I have mobile apps, it will cost the client more data usage.

If I go one service call, is there a way to set up some sort of connection so I can return data as I get it, in case one service call hangs?


问:
How has an increase in the complexity of systems affected successive generations of programmers?
As a "new" programmer (I first wrote a line of code in 2009), I've noticed it's relatively easy to create a program that exhibits quite complex elements today with things like .NET framework for example. Creating a visual interface, or sorting a list can be done with very few commands now.

When I was learning to program, I was also learning computing theory in parallel. Things like sorting algorithms, principles of how hardware operates together, boolean algebra, and finite-state machines. But I noticed if I ever wanted to test out some very basic principle I'd learned in theory, it was always a lot more difficult to get started because so much technology is obscured by things like libraries, frameworks, and the OS.

Making a memory-efficient program was required 40/50 years ago because there wasn't enough memory and it was expensive, so most programmers paid close attention to data types and how the instructions would be handled by the processor. Nowadays, some might argue that due to increased processing power and available memory, those concerns aren't a priority.

My question is if older programmers see innovations like these as a godsend or an additional layer to abstract through, and why might they think so? And do younger programmers benefit more learning low-level programming BEFORE exploring the realms of expansive libraries? If so then why?

答:
The increase in the complexity of systems is relentless, oppressive and ultimately crippling. For me as an older generation programmer, it is also bitterly disappointing.

I've been programming for well over 40 years, having written code in 50-100 different languages or dialects, and become expert in 5-10. The reason I can claim so many is that mostly they're just the same language, with tweaks. The tweaks add complexity, making every language just a little different.

I have implemented the same algorithms innumerable times: collections, conversions, sort and search, encode/decode, format/parse, buffers and strings, arithmetic, memory, I/O. Every new implementation adds complexity, because every one is just a little different.

I wonder at the magic wrought by the high flying trapeze artists of the web frameworks and mobile apps, at how they can produce something so beautiful in such a short time. Then I realise how much they don't know, how much they will need to learn about data or communications or testing or threads or whatever before what they do becomes useful.

I learnt my craft in the era of fourth generation languages, where we genuinely believed that we would produce a succession of higher and higher level languages to progressively capture more and more of the repetitive parts of writing software. So how did that turn out, exactly?

Microsoft and IBM killed that idea by returning to C for writing apps for Windows and OS/2, while dBase/Foxpro and even Delphi languished. Then the web did it again with its ultimate trio of assembly languages: HTML, CSS and JavaScript/DOM. It's been all downhill from there. Always more languages and more libraries and more frameworks and more complexity.

We know we should be doing it differently. We know about CoffeeScript and Dart, about Less and Sass, about template to avoid having to write HTML. We know and we do it anyway. We have our frameworks, full of leaky abstractions, and we see what wonders can be done by those chosen few who learn the arcane incantations, but we and our programs are trapped by the decisions made in the past. It's too complicated to change or start over.

The result is that things that ought to be easy are not easy, and things that ought to be possible are nearly impossible, because of complexity. I can estimate the cost of making changes to implement a new feature in an established code base and be confident I'll be about right. I can estimate, but I can't justify it or explain it. It's too complicated.

In answer to your final question, I would strongly advise younger programmers to start as high on the layer cake as they possibly can, and only dive down to the lower layers as the need and desire provide the impetus. My preference is for languages with no loops, little or no branching and explicit state. Lisp and Haskell come to mind. In practice I always finish up with C#/Java, Ruby, Javascript, Python and SQL because that's where the communities are.

Final words: complexity is the ultimate enemy! Beat that and life becomes simple.


答:
As having a copyright notice in a file doesn't have any legal implication at all (your work is still protected without it), it's only as information to anyone who can see it.

Also, to be covered by the rights, the file needs to contain something that could be considered to be an original work. If the code in the file is too trivial, you can't really prove that someone else didn't just write the same thing by chance.

So, there is only a need to include it in files that could possibly be viewed by someone outside the company, and that contains any real substance. Of course, you may also have to consider to include it in more files just to satisfy your manager.

Title: In which file types I should include the copyright header?

Body:
My manager told me to include 15 line copyright notice on top of every file.

I am not sure whether I need to include in sql, xml, txt, documention, config files or even html templates.

In which files should I include copyright notice?


问:
Maximizing number of nested triangles
There is a finite set of points on a plane (about 1500 points in the current task). I need to construct triangles on those points such as each triangle lies completely inside one larger triangle:

Now I want an algorithm to maximize the number of such triangles. Where can I start?

I think one of the ways would be to choose a "center" and to find three directions from this center with most point density near those directions. Or just choose an arbitrary center triangle manually and then iteratively choose a larger triangle with the least area or the least distance.

答:
My gut feeling tells me that this is an NP-complete problem. You can try to find a good solution but not the best one.

So yes, a start would be to pick three points in the middle, start there and create a triangle. Find the closest points to each of these three points and try to create a new rectangle. It should give a decent solution in most cases.

To improve on this, you could run it multiple times with a number of different starting triangles. Or add some randomness to the taking of the closest points. Run it a few times and keep the best solution you've found.

Title: Maximizing number of nested triangles


问:
Updating copyright headers each new year just because Jan 1st has passed?
I've seen some projects that - with each new year - start to change all files in their source-tree to update the copyright year.

Isn't this just pushing hot air on a level of magnitude? AFAIK:

Copyright year is based on relevant changes of a work (also) - not only because of a trivial change of the copyright year in a file-header that is the only change.

Changing nearly all files without an actual need brings the code out of order in version control.

I can't help myself but have problems to see why someone wants to do such superfluous stuff, albeit I know some projects are doing this (for example Zend Framework 1 in 2012).

Is there any use in changing the copyright year in each file only because Jan 1st has passed?

答:
Actually the updating of the headers with copyright information is a form of fraud.
You cannot claim that a work you made in 2010 has been made in 2014.</p>


问:
Why do C++ and Java both use the notion of "reference" but not in the same sense?
In C++ a reference argument to a function allows the function to make the reference refer to something else:

```<code>int replacement = 23;

void changeNumberReference(int& reference) {
    reference = replacement;
}

int main() {
    int i = 1;
    std::cout << "i=" << i << "\n"; // i = 1;
    changeNumberReference(i);
    std::cout << "i=" << i << "\n"; // i = 23;
}
</code>```

Analogously, a constant reference argument to a function will throw a compile time error if we try to change the reference:

```<code>void changeNumberReference(const int& reference) {
    reference = replacement; // compile-time error: assignment of read-only reference 'reference'
}
</code>```

Now, with Java, the docs say that functions arguments of non-primitive types are references. Example from the official docs:

```<code>public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);

    // code to assign a new reference to circle
    circle = new Circle(0, 0);
}
</code>```

Then circle is assigned a reference to a new Circle object with x = y
  = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change.

To me this doesn't look at all like C++ references. It doesn't resemble regular C++ references because you cannot make it refer to something else, and it doesn't resemble C++ const references because in Java, the code that would change (but really doesn't) the reference does not throw a compile-time error.

This is more similar in behavior to C++ pointers. You can use it to change the pointed objects values, but you cannot changes the pointer's value itself in a function. Also, as with C++ pointers (but not with C++ references), in Java you can pass "null" as value for such an argument.

So my question is: Why does Java use the notion of "reference"? Is it to be understood that they don't resemble C++ references? Or do they indeed really resemble C++ references and I'm missing something?

答:
It largely goes back to Algol 68, and partly to a reaction against the way C defines pointers.

Algol 68 defined a concept called a reference. It was pretty much the same as (for one example) a pointer in Pascal. It was a cell that contained either NIL or the address of some other cell of some specified type. You could assign to a reference, so a reference could refer to one cell at one time, and a different cell after being reassigned. It did not, however, support anything analogous to C or C++ pointer arithmetic.

At least as Algol 68 defined things, however, references were are fairly clean concept that were fairly clumsy to use in practice. Most variable definitions were actually of references, so they defined a shorthand notation to keep it from getting completely out of hand, but any more than trivial use could get clumsy pretty quickly anyway.

For example, a declaration like INT j := 7; was really treated by the compiler as a declaration like REF INT j = NEW LOC INT := 7. So, what you declared in Algol 68 was normally a reference, which was then initialized to refer to something that was allocated on the heap, and that was (optionally) initialized to contain some specified value. Unlike Java, however, they at least tried to let you maintain sane syntax for that instead of constantly having things like foo bar = new foo(); or trying to tell fibs about "our pointers aren't pointers."

Pascal and most of its descendants (both direct and...spiritual) renamed the Algol 68 reference concept to "pointer" but kept the concept itself essentially the same: a pointer was a variable that held either nil, or the address of something you allocated on the heap (i.e., at least as originally defined by Jensen and Wirth, there was no "address-of" operator, so there was no way for a pointer to refer to a normally defined variable). Despite being "pointers", no pointer arithmetic was supported.

C and C++ added a few twists to that. First, they do have an address-of operator, so a pointer can refer not only to something allocated on the heap, but to any variable, regardless of how it's allocated. Second, they define arithmetic on pointers--and define array subscripts as basically just a shorthand notation for pointer arithmetic, so pointer arithmetic is ubiquitous (next to unavoidable) in most C and C++.

When Java was being invented, Sun apparently thought "Java doesn't have pointers" was a simpler, cleaner marketing message than: "nearly everything in Java is a pointer, but these pointers are mostly like Pascal's instead of C's." Since they'd decided "pointer" wasn't an acceptable term, they needed something else, and dredged up "reference" instead, even though their references were subtly (and in some cases not so subtly) different from Algol 68 references.

Though it came out somewhat differently, C++ was stuck with roughly the same problem: the word "pointer" was already known and understood, so they needed a different word for this different thing they were adding that referred to something else, but was otherwise quite a bit different from what people understood "pointer" to mean. So, even though it's also noticeably different from an Algol 68 reference, they re-used the term "reference" as well.


问:
How do I decide what testing framework to use?
The situation is this.

I'm a junior developer for a small government IT project. We don't have anything of continuous integration or a automated testing framework. But the idea is to be developing this kind of thing/improving our developing environment.

The product is a data processing algorithm that then displays information to the end user via a webapp.

So coming up is a bunch of work modifying the webapp javascript. As such we want to implement a unit testing for the javascript.

I've looked at this stack overflow question which outlines several different unit testing frameworks for javascript.

The question is - how do I decide between which framework to start using?

What is a list of criteria for choosing a testing framework?

Is it practical to try them all out?

Spend a lot of time reading forums/etc about how they're used?

答:
What is a list of criteria for choosing a testing framework?

1) Syntax

As you investigate different test frameworks you will notice that syntax is a differentiating factor across all of them.  This is really going to depend on what makes you feel comfortable.

For example, qUnit is more of a declarative test framework.  Its API consists of functions called test, equals, strictEqual, deepEqual, etc.

Another test framework, mocha, is more like rspec in that it reads in a more sentence like structure.  Its API consists of functions called describe, it, assert.equal, etc.

My personal preference is a qunit like structure.

2) Features - Stubs, Spies, Fake server, Fake clock, etc

When you start testing in Javascript you will quickly find yourself in situations where you need your test framework to help you test certain use cases.  For example:

Spies - This will help you detect whether your code called a function when it should have

Stubs - Very similar to a spy except it contains predefined behavior (Example: When the stub is called, return foo)

Fake Server - If your code issues AJAX calls and you want to fake the response of the AJAX call, a Fake Server will help you more easily test.

Fake Clock - If your code reacts differently based on the date or time, then a fake clock will help you control exactly what time it is while your test runs.

My recommendation for a Javascript Framework that supports all the features above is Sinon.JS.  Because I like a qunit like syntax and framework, I use qunit AND Sinon.JS.  qunit handles my assertions and runs my tests.  Sinon.JS gives me the ability to stub, spy, run a fake server, and fake the clock.

3) Community Support

Is your test framework supported by the community?  For example, grunt (a build environment tool) supports running qunit in a headless PhantomJS server: https://github.com/gruntjs/grunt-contrib-qunit .  This makes it easy to write tests and have them be automatically run everytime I save the test file.

Is it practical to try them all out?
No it is not practical. Instead investigate each framework's website and pick one that you feel comfortable with and one that will also support you while your write tests.

Spend a lot of time reading forums/etc about how they're used?
Grab a book on the framework you choose and skim through it as you need it.


答:
If you are okay with an approximated solution (not necessarily the best one possible), you could try genetic approach.

Find a so-so solution as a starting point - using some simple algorithm such as the one suggested by @Carra - then make, say, a 1000 copies of this initial solution and keep on mutating them randomly. Switching points, trying to add more triangles etc.

Reward the best specimen and throw away poor copies, eg. after each generation you could overwrite the entire gene pool with clones of the best 5%. For best results decrease the temperature with time - it means use aggressive mutation at the beginning, but slower mutation rate towards the end in order to finetune the results once they reach high quality level.

After some iterations you should end up with a fairly good solution.

Title: Maximizing number of nested triangles

Body:
There is a finite set of points on a plane (about 1500 points in the current task). I need to construct triangles on those points such as each triangle lies completely inside one larger triangle:

Now I want an algorithm to maximize the number of such triangles. Where can I start?

I think one of the ways would be to choose a "center" and to find three directions from this center with most point density near those directions. Or just choose an arbitrary center triangle manually and then iteratively choose a larger triangle with the least area or the least distance.


问:
Data structures for bioinformatics
What are some data structures that should be known by somebody involved in bioinformatics?

I guess that everyone is expected to know about lists, hashes, balanced trees, etc, but I expect that there are domain specific data structures. Is there any book devoted to this subject?

Thanks,
Lucian

答:
I can't think of any data structures that are really unique to bioinformatics. There are a lot of algorithms that are common in bioinformatics but which you don't see too often in generic commercial programming. Dynamic programming comes up all the time for example. Note that this has nothing to do with dynamic types, rather it is an efficient technique for unrolling recursive calls.

There are dozens of books on algorithms in bioinformatics. A couple of good ones I can name off the top of my head are: Biological Sequence Analysis and An Introduction to Bioinformatics Algorithms

Title: Data structures for bioinformatics


问:
How to determine the better design?
What do I need to consider to determine which design I choose when I have the following scenario?

There are two cases to considerer;

Given T a generic class, I have to do something with multiple T's (Iterating each one of them).

In other cases, with the same T, I have to process just once.

In both cases, independent of what is T and how I'll need to process it, the class that comprises T will behave exactly the same way, therefore, I don't need to worry about implementation details.

There are 2 possible solutions, and I don't know what directions should I follow to decide between them.

Always consider as a List, this is for sake of simplicity, since there are no difference  between a List of T and only T.

Use inheritance; the first child class will receive a List of T and work with it, the second, a single T and work with it.

Are there some good pratices or some article to help to decide such cases?
I'm looking for something like this article, or your experience as well.

UPDATE:

The class I'm design is not T, but its composer.

答:
If processing every instance of T is independent of processing the others, I'd just create a class that processes one T and then enwrap it with a class that "feeds" it with a sequence of Ts and just calls the first class in some sort of a foreach block.

I wouldn't use inheritance for that.

Simplified example (C#):

```<code>interface IFoo
{
    void DoStuff();
}

class FooProcessor<T> where T : IFoo
{
    public void Process(T item)
    {
        item.DoStuff();
    }
}

class MultipleFooProcessor<T> where T : IFoo
{
    // composition over inheritance - MultipleFooProcessor does not share any "genes" with FooProcessor,
    // it just keeps an instance of it in a private field
    FooProcessor<T> processor;

    // we're passing a regular FooProcessor here.
    // thanks to not using inheritance, we could eg. create an IFooProcessor interface
    // and pass a different implementation of IFooProcessor here, allowing for a more flexible design.
    // see: dependency injection, loose coupling
    public MultipleFooProcessor(FooProcessor<T> processor)
    {
        this.processor = processor;
    }

    public void Process(IEnumerable<T> sequence)
    {
        foreach (T item in sequence)
        {
            Process(item);
        }
    }

    public void Process(T item)
    {
        processor.Process(item);
    }
}
</code>```

Title: How to determine the better design?

Body:
If processing every instance of T is independent of processing the others, I'd just create a class that processes one T and then enwrap it with a class that "feeds" it with a sequence of Ts and just calls the first class in some sort of a foreach block.

I wouldn't use inheritance for that.

Simplified example (C#):

interface IFoo
{
    void DoStuff();
}

class FooProcessor<T> where T : IFoo
{
    public void Process(T item)
    {
        item.DoStuff();
    }
}

class MultipleFooProcessor<T> where T : IFoo
{
    // composition over inheritance - MultipleFooProcessor does not share any "genes" with FooProcessor,
    // it just keeps an instance of it in a private field
    FooProcessor<T> processor;

    // we're passing a regular FooProcessor here.
    // thanks to not using inheritance, we could eg. create an IFooProcessor interface
    // and pass a different implementation of IFooProcessor here, allowing for a more flexible design.
    // see: dependency injection, loose coupling
    public MultipleFooProcessor(FooProcessor<T> processor)
    {
        this.processor = processor;
    }

    public void Process(IEnumerable<T> sequence)
    {
        foreach (T item in sequence)
        {
            Process(item);
        }
    }

    public void Process(T item)
    {
        processor.Process(item);
    }
}


答:
If only the individual items T are being processed, without any relation to eachother, I would just create a single class that works on a single T.
This keeps that class as simple as possible.
Iterating over multiple Ts and applying the action on each one can be the responsibility of some other class.
This way there is no reason to create a list object when working on an individual item, nor are there multiple classes which basically do the same thing.</p>

Title: How to determine the better design?

Body:
What do I need to consider to determine which design I choose when I have the following scenario?

There are two cases to considerer;

Given T a generic class, I have to do something with multiple T's (Iterating each one of them).

In other cases, with the same T, I have to process just once.

In both cases, independent of what is T and how I'll need to process it, the class that comprises T will behave exactly the same way, therefore, I don't need to worry about implementation details.

There are 2 possible solutions, and I don't know what directions should I follow to decide between them.

Always consider as a List, this is for sake of simplicity, since there are no difference  between a List of T and only T.

Use inheritance; the first child class will receive a List of T and work with it, the second, a single T and work with it.

Are there some good pratices or some article to help to decide such cases?
I'm looking for something like this article, or your experience as well.

UPDATE:

The class I'm design is not T, but its composer.


问:
TDD - Making assertions about C# Expression trees
How would you unit test the PerformUpdate method in the sample below? This is a (very) simplified version of some code that performs updates against a database where the schema is dynamic and represented by the fields collection.

EDIT: If it is not clear what I am asking, I would like to know how different developers would approach testing\mocking this code from a TDD perspective. For example, what tests would you write, what would you mock, how would you verify method calls are made with the right arguments?

```<code>public interface IUnitOfWork
{
    IEfRepository<Field> Fields { get; }
}

public class UpdateService
{
    private IUnitOfWork unitOfWork;

    private IDataUpdater dataService;

    public Activity PerformUpdate(App app, IDictionary<string, object> data)
    {
        var fields = this.unitOfWork.Fields.FindWhere(o => o.App.Identifier == app.Identifier);
        var activity = this.dataService.PerformUpdate(fields, data);

        return activity;
    }
}
</code>```

答:
There are a few different parts to be tested here. Ultimately my answer is the same regardless of the specific portion of the code. The validity of each entities method should be tested separately as it's own concern (I'm sure your doing this anyway).

In terms of testing say the PerformUpdate method, your best bet here is to mock / stub both the IUnitOfWork and IDataUpdater. In each case the mock / stubs would make an assumption (good data and bad data). Simply query these after they are called to confirm the validity of the call.


答:
Here's an unhelpful answer for you :)

I'd probably not unit test this, and would create a more behavioural component-level test with a few complex Fakes.

Wondering how you test a particular implementation seems like a smell to me - you should be asking 'how would I develop an implementation to fulfil this requirement?'

Title: TDD - Making assertions about C# Expression trees

Body:
How would you unit test the PerformUpdate method in the sample below? This is a (very) simplified version of some code that performs updates against a database where the schema is dynamic and represented by the fields collection.

EDIT: If it is not clear what I am asking, I would like to know how different developers would approach testing\mocking this code from a TDD perspective. For example, what tests would you write, what would you mock, how would you verify method calls are made with the right arguments?

```<code>public interface IUnitOfWork
{
    IEfRepository<Field> Fields { get; }
}

public class UpdateService
{
    private IUnitOfWork unitOfWork;

    private IDataUpdater dataService;

    public Activity PerformUpdate(App app, IDictionary<string, object> data)
    {
        var fields = this.unitOfWork.Fields.FindWhere(o => o.App.Identifier == app.Identifier);
        var activity = this.dataService.PerformUpdate(fields, data);

        return activity;
    }
}
</code>```


问:
Should I convert the whole project to UTF-8?
I am working on a highly customized shop software, based on a open-source one, written in PHP and usual web techniques (CSS, HTML, JS).

I did a lot of customization in the past months/years and developed specific, individual features which are necessary to be successful at our branch.

The shop and the project files are encoded in ISO-8859-1 (company is located in Germany).

Now we want to spread out and use the shop system in different countries (e.g. Sweden, Poland, Great Britain) and customize it to the domestic needs.

But I am afraid that I could encounter some encoding problems afterwards, so my question is:

Is it wise to change the encoding of the whole project and the environment to UTF-8 before I prepare the shop for "multi-shop" usage or should I leave the source at it is and handle (possible) encoding problems for each country as they approach afterwards?

答:
You will encounter encoding problems. You can handle Swedish and English with ISO-8859-1, but not Polish. You could use ISO-8859-2 for Polish, but then you would need to use other encodings when moving to languages that are not covered with ISO-8859-1 or ISO-8859-2.

So it is best to internationalize the software, using UTF-8, which covers all languages, and using UTF-8 throughout.


答:
First, create a list of all triangles (subsets of 3 points). Then you make a pairwise comparison of each of two triangles T_i and T_j: either T_i is inside T_j, T_j is inside T_i or none of the two lies inside of the other.

Interpret this as a directed, acyclic graph: the triangles are the vertices of the graph, and each relationship "T_i is inside T_j" defines a directed edge from T_i to T_j. Now  finding of a maximum sequence of triangles is just the longest path problem for such kind of graphs. And as you can read in the Wikipedia article, there exist linear time algorithms for solving this problem.

"Linear time" here means "linear to the number of edges" (the number of triangle pairs where one is inside the other). For n points, you have to consider

```<code>t := C(n,3)=n*(n-1)*(n-2)/6
</code>```

triangles (see binomial coefficient), and thus a maximum of

```<code>C(t,2) = t*(t-1)/2
</code>```

triangle pairs, which can be a huge number with increasing n - its a polynomial of order O(n^6). But since most triangle pairs are not expected to of the type "where one is inside the other", I would expect the real world computational effort to be much smaller. For n below 100 it should be no problem to find a solution directly.

For n >=1.000, this approach most probably won't be fast enough to give you a result in a reasonable amount of time. Thus, better try to solve it with an approximating algorithm like the one suggested by @KonradMorawski, or (easier to implement) simulated annealing. The "simulated annealing" will need a "small modification" step, which may be implemented by removing one or two randomly choosen triangles from your "current solution", and then add triangles again by some kind of "greedy algorithm" with a bit of randomness. You will surely need to experiment with these details to see what works best for your specific problem. As a free resource about this topics, here you find an e-book dealing with different global optimization techniques.

Title: Maximizing number of nested triangles

Body:
First, create a list of all triangles (subsets of 3 points). Then you make a pairwise comparison of each of two triangles T_i and T_j: either T_i is inside T_j, T_j is inside T_i or none of the two lies inside of the other.

Interpret this as a directed, acyclic graph: the triangles are the vertices of the graph, and each relationship "T_i is inside T_j" defines a directed edge from T_i to T_j. Now  finding of a maximum sequence of triangles is just the longest path problem for such kind of graphs. And as you can read in the Wikipedia article, there exist linear time algorithms for solving this problem.

"Linear time" here means "linear to the number of edges" (the number of triangle pairs where one is inside the other). For n points, you have to consider

t := C(n,3)=n*(n-1)*(n-2)/6

triangles (see binomial coefficient), and thus a maximum of

C(t,2) = t*(t-1)/2

triangle pairs, which can be a huge number with increasing n - its a polynomial of order O(n^6). But since most triangle pairs are not expected to of the type "where one is inside the other", I would expect the real world computational effort to be much smaller. For n below 100 it should be no problem to find a solution directly.

For n >=1.000, this approach most probably won't be fast enough to give you a result in a reasonable amount of time. Thus, better try to solve it with an approximating algorithm like the one suggested by @KonradMorawski, or (easier to implement) simulated annealing. The "simulated annealing" will need a "small modification" step, which may be implemented by removing one or two randomly choosen triangles from your "current solution", and then add triangles again by some kind of "greedy algorithm" with a bit of randomness. You will surely need to experiment with these details to see what works best for your specific problem. As a free resource about this topics, here you find an e-book dealing with different global optimization techniques.


问:
Combining version numbers of app components
I have an app that is made up of multiple different components, each with their own version number and history. I would like to create a version number of the entire application, preferably somehow based on the version numbers of the components. I am not sure if this is possible at all, but I would like:

The version number be unique for each version of the components, so that when I upgrade the version number of one of the components, the version number of the whole app will change as well, and the number must not be ambigous so that it could refer to some other constellation of components.

It would be nice if there was a way to reverse the process to go from a combined version number to see what versions of components it consists of.

It is also nice if the combined version number is not too long to remember

It's a plus if the combined version number always increases with the increase of a component version number.

I am aware that some of these desires are not possible to accomodate together (such as short AND reversable since you would lose information when shortening)

The easiest approach is of course to just add the version number together in a long row, but that would be too long to be practical. Another is to create some kind of hash, but it would not be very readable.

Is there a standard way of doing this? Or will I have to name the major version manually and take note of what component versions it consists of?

答: For your last requirement (monotonicity in numbering generations) you didn't specify anything further (e.g. some components have larger impact and therefore advance the total version in larger steps) so it would be easy to devise a simple addition of all version numbers which guarantees ever-increasing numbers on the same branch (i.e. furthermore only advancing one component), but the impossibility to define a total ordering will make this solution quite unattractive. OTOH the ability to roughly sort the total version number at first glance is one of the most important, otherwise you could go with a completely cryptic hash function. So first make clear if you are able to define a hierarchy of components based on their importance. If not, only a function which is able to look back in history (in a database at your site) is able to produce and decode version numbers.


问:
Security concern regarding web service
I'm currently working on a pet project with two of my buddies. This web service will provide basic functionality such as Login/Password Modification/Registration etc.

All of us are comfortable with jQuery and ASP.NET. My friend's idea is to -

Set up a web service on the same domain and send it data for registration, validation and password retrieval through jQuery ajax.

This same process is going to be used for other CRUD ops as well.

I'm not sure though, isn't this a huge security risk? Couldn't a normal person write some code that could create thousands of dummy users in our application?

Would setting up a secondary web service that handles authorization (OAUTH 2.0 or something like that) and calls the web service that connects directly to the database reduce the security risk?

答: If you're going to write a login system yourself, it's probably best to stick with traditional methods of registration via confirmation emails or similar. You can't both make registration something that can be automated (web API) and make it hard to automate (spam bots). Delegating to a third party for authentication may be a good option.</p>

Title: Security concern regarding web service


问:
Testing: Should I wrap system notifications and send my own?
In the current Cocoa app I'm working on, I've got an object, RecordScheduler, which responds to two types of notifications, "day did pass" and "quicksaving interval did pass".  In both cases, the RecordScheduler tells a Recorder to do its recording job, among other things.

Now I want RecordScheduler to issue a recording when the Mac goes to sleep.

You subscribe to sleep/wake notifications via NSWorkspace:

```<code>[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
        selector:@selector(computerWillSleep:)
        name:NSWorkspaceWillSleepNotification object:nil];
</code>```

This is easy enough.  Add it to RecordScheduler's -init and the notifications would be processed just nicely.

Thing is, for the other two cases I wrote helper methods like fireDayDidPass() to use in unit tests.  I fired my custom notifications and added assertions for RecordScheduler's response.  Works well.  I don't feel comfortable firing a NSWorkspaceWillSleepNotification since (a) it's not my own, and (b) I don't know about any side effects.

Instead, I resorted to calling [scheduler computerWillSleep:nil] which would receive notifications.  Now I don't have an intergration-ish test to verify RecordScheduler subscribes to NSWorkspaceWillSleepNotification.

After I found out there is no additional information to be sent, I abandoned the idea of creating a HibernationObserver which subscribes to NSWorkspace's notifications and re-sends my own kind of "Will Sleep" and "Did Wake" notifications.  There seemed to be no additional benefit.

Now here's the point:

Is it still a unit test when I fire a notification and assert for both the side effects of notification handling and the receiver's subscription upon initialization?

How else could I verify an object signs up itself as a notification receiver?

Should I make it a habit to wrap system notifications in my own?

答:
Without going to formal definitions unit test should test a software unit (==>method). This is the lowest system test you perform.

Unit test should be light as possible and test the system from the unit perspective and you should not create any wrappers or test any system dependencies. doing so would create objects that are not part of your unit logic and the test shifts to wider aspects under unit test definition.

The solution of your problem is to create another testing layer (let's call it "component tests") in this test you need to test the integration between different system components.
This would give you the ability to test the application in wider context and aspect, test the behavior of other objects etc.

This testing type can still use the same test framework you use for unit tests.
At the component testing I do not think you should create dedicated test objects because of the overhead of the maintenance.

Creating dedicated object are basically the first steps of creating auto test framework and you should invest on it when testing the application context and above (application ==> system ==> network ==> eco-system ...).

In order to understand where each test belong to ask yourself questions about the context needed to run the test.
This is in general:

Object context ==> unit test (verification)

Several objects context ==> component test (verification)

Application context ==> application tests (Validation)

Several applications context ==> System tests (validation)

client-server context ==> advanced system tests (validation)

Eco-System ==> Advanced system tests (Validation)

Each context has its own characteristics. You need to analyze each of which and create a mix for the best ROI.

Either way do I do not recommend you to invest much on the verification tests - any of the exist unit test frameworks should answer much of your needs - you just need to get familiar with it.


答:
Yes, it helps security - possibly not by much, but every little helps in the web world. What you've done is reduce the attack surface for someone who's taken over your web server with a zero-day (or other) attack. If you accessed the database directly in your webserver, the attacker would be able to simply read out all the user's data (or worse - their credit card data) without much trouble. At least now they have to hit each user individually via the API you created for the web service.

So you can take the concept further and build more layers of security into it. Throttle the user creation limit, add additional values that need to be correct in order to access the service.

Nothings perfect, but you can make it much harder for an attacker by not letting them have easy access to all your data. Personally, I'd put all your other business logic code into webservices too.

Title: Security concern regarding web service

Body:
I'm currently working on a pet project with two of my buddies. This web service will provide basic functionality such as Login/Password Modification/Registration etc.

All of us are comfortable with jQuery and ASP.NET. My friend's idea is to -

Set up a web service on the same domain and send it data for registration, validation and password retrieval through jQuery ajax.

This same process is going to be used for other CRUD ops as well.

I'm not sure though, isn't this a huge security risk? Couldn't a normal person write some code that could create thousands of dummy users in our application?

Would setting up a secondary web service that handles authorization (OAUTH 2.0 or something like that) and calls the web service that connects directly to the database reduce the security risk?


答:
Converting from a single-byte to a multi-byte encoding (which utf-8 is) is far from trivial. It will require you to touch almost every string in your application (or at least examine it), and every function that manipulates it. Bear in mind that PHP 6 and Perl 6 have been held up for years because of this. I would not recommend committing to the switch unless (a) you are confident that you can carry it out, and (b) you consider carefully whether it's worth the effort.

I'd recommend doing some work on a trial basis to see how smoothly it goes, before you commit fully.

From what you say it is clear that you will need more than ISO-8859-1, so you do need internationalization. But if your expected customer base can be handled with the ISO-8859 family of encodings, you have a choice:

Implement internationalization in terms of setting the appropriate 8-bit encoding (and including it in webpage encodings, SQL tables, etc.)

Implement internationalization by switching to utf-8.

The first option should be a lot easier than the second, so consider carefully what utf-8 gains you.

Notes

Since this is based on an open source application I would consider doing this as an improvement to the open-source base for your system. This allows you to get the community's help, since multilingual support is of benefit to everyone. And if you carry out such a fundamental conversion in your proprietary customized version, you will definitely have trouble merging the next open source version into your codebase.

One real benefit of Unicode is that it easily allows a multi-lingual (multi-encoding) site. If the current system is limited to a fixed encoding, tracking multiple encodings in a single system would be an even bigger mess to implement than switching to Unicode. It doesn't sound like you'll need this in the foreseeable future, though.

Full disclosure: I speak from experience, an attempted conversion that turned out to be very, very difficult. (So this could go either way: maybe I'm just overcautious and you'll be fine).

Title: Should I convert the whole project to UTF-8?

Body:
I am working on a highly customized shop software, based on a open-source one, written in PHP and usual web techniques (CSS, HTML, JS).

I did a lot of customization in the past months/years and developed specific, individual features which are necessary to be successful at our branch.

The shop and the project files are encoded in ISO-8859-1 (company is located in Germany).

Now we want to spread out and use the shop system in different countries (e.g. Sweden, Poland, Great Britain) and customize it to the domestic needs.

But I am afraid that I could encounter some encoding problems afterwards, so my question is:

Is it wise to change the encoding of the whole project and the environment to UTF-8 before I prepare the shop for "multi-shop" usage or should I leave the source at it is and handle (possible) encoding problems for each country as they approach afterwards?


问:
DataSet Validation vs. ASP.NET MVC Validation
I have a general question on where to put validation.

I have an asp.net mvc that gets/sets data from/to a DataSet. Currently, the fields in the form are validated by the form itself (e.g. for invalid length, range, etc.). Is it a good or better idea to transfer these validation checks into the DataSet? The downside is I need to trigger update calls to the DataSet in order to get the column with errors. In using forms, I can catch the error earlier.

Or should I use validation for both of them?

For additional consideration - it's possible I will be re-using this Dataset assembly with another project (a WCF service?). And I'd like to re-use the same validation code when possible.

答:
You should consider validating the inputs on the form at both the UI layer as well as at the service layer.

Validating at the UI layer means your application will appear more responsive and can instantly provide feedback to the user on what's missing or what's wrong.  Validating at the UI avoids a network call, and makes it simpler to identify what's wrong because you don't have to dig into an object and find a list of errors to report.

Validating at the service layer is required since your service shouldn't blindly trust what's being passed to it by a client.  If you only did one, you must validate at your service layer.

Unfortunately, validating at both layers means you'll likely duplicate some of the validation code.  But that's the trade-off you have to make in order to gain a responsive UI with quick problem notification as well as having a secure service.


问:
Which one of the SOLID principles had the largest effect on your code?
Which if the SOLID principles introduced by "Uncle Bob" Martin had the largest effect on your day to day coding? Please give details!</p>

答:
S ingle r  esponsibility p rinciple.

Whether I'm working a small utility or a large scale service, I like my components to do one thing and to do that thing well. It makes my components easy to test and promotes code reuse.

The rest are important too.


问:
Is there a licence that let people see my code but not use it?
I'm building free games in javascript, with my code is easily accessible by looking into the html of the webpage.

I really don't mind people looking at my code (for curiosity, or to learn something). But I don't want anyone to use my code to make their own games, or steal the art I've done.

With this goal in mind, what software licence should I use? Thanks!

答:
You don't need to specify any license.

By default, when you publish something, you retain all copyrights on it, unless you explicitly provide a license for reproduction, reuse etc.

If it makes you feel better you can add a "all rights reserved" statement to your source, but that isn't necessary to assert your copyright.


问:
How to map TFS to two local directories
I am working with a web application, using TFS.  Every time I build the site it takes an unproductivly long time to start up again.  I would like to have a second mapping of the site on my c drive, where I would only get latest and build once a day, so this version would always be fast.  This would be like a "readonly" directory as I wouldn't personally make any edits to it.

Please let me know if this possible, or if you have any alternative.

答:
It is possible to do this.

Unmap Your TFS

Right click on the folder and Map the sub directory to a folder for example C:\temp

Click on the root and map it to another folder C:\localDev\

you will be asked to remove the existing mapping on C:\temp

Select No (do not press Cancel)

I have tried this and it works fine.

Title: How to map TFS to two local directories


问:
Does anyone else feel Scrum isn't agile?
I am a big fan of agile development and used XP on a very successful project a few years ago. I loved everything about it, the iterative development approach, writing code around a test, pair programming, having a customer on site to run things by. It was a highly productive work environment and I never felt like I was under pressure.

However the last few places I have worked use/used Scrum. I know it's the poster child for agile development these days but I'm not 100% convinced it is agile. Below are the two main reasons why it just doesn't feel agile to me.

Project Managers Love It

Project managers, who by their very nature are obsessed with timelines, all seem to love Scrum. In my experience they seem to use the Sprint Backlog as a means to track time requirements and keep a record of how much time was spent on a given task. Instead of using a whiteboard they all use an excel sheet, which each developer is required to fill out, religiously.

In my opinion this is way too much documentation/time tracking for an agile process. Why would I waste time estimating how long a task is going to take me when I can just get on with the task itself. Or similarly why would I waste time documenting how long a task took when I can move onto the next task at hand.

Standup Meetings

The standup meetings in the previous place I worked were a nightmare. Everyday we had to explain what we had done yesterday and what what we were going to do that day. If we went over on our time "estimate" for a task the project manager would kick up a stink, and reference the Sprint Backlog as a means of showing of incompetent you are for not adhering to the timeline.

Now I understand the need for communication but surely the tone of daily meetings should be lighthearted and focus on knowledge sharing. I don't think it should turn into a where's your homework style charade. Also surely the hole point of agile is that timelines change, they shouldn't be set in stone.

Conclusion

The idea of agile is to make the software better by making the developers life easier. Therefore in my opinion any agile process used by a team should be developer led. I don't think having a project manager use a process they have labeled "agile" to track a project has anything to do with agile development.

Thoughts anyone?

答:
There are certain elements in Scrum which are more prone to perversion, but to be frank, what you are describing is the result of trying to get a organisation to adopt Scrum without educating all the stakeholding parties as to what it's all about, how it works and why it works. You need buy-in across the entire company to get results.

Any agile transformation is going to expose everything bad that's going on in your organisation, including, but not limited to, micromanagers, powerhungry people with their own agendas, insufficiently trained developers, communication silos, etc. If there's no collective will to address these issues and you just "do standups" and just "work in sprints", the Scrum implementation is going to fall flat on its face.

I can not stress this enough: if you want to do Scrum, you need competent coaches who can show you the path. It's not enough to read Essential Scrum and then just see where it gets you...


答:
What you're describing is what we, Professional Scrum Trainers, see a lot in organisations that have "implemented scrum". Often they "Do XP in the development team" too, meaning that there are a few Unit tests running on a build server somewhere. This isn't scrum.

Yes, Project Managers can use a Product backlog, especially one that has been digitized, to abuse the hell out of the metrics such systems gather. But the Development Team and the Scrum Master should not let him. What is a Project Manager doing there anyway? Shouldn't that be a Product Owner?!

Just as XP can be done badly, and some more rigorous processes can feel very fluid (with continuous integration, deployment, but still very plan driven), Scrum is just a framework. It takes good people who understand the values and the process to execute it well. It takes Continuous learning an improvement to get there.

Title: Does anyone else feel Scrum isn't agile?

Body:
I am a big fan of agile development and used XP on a very successful project a few years ago. I loved everything about it, the iterative development approach, writing code around a test, pair programming, having a customer on site to run things by. It was a highly productive work environment and I never felt like I was under pressure.

However the last few places I have worked use/used Scrum. I know it's the poster child for agile development these days but I'm not 100% convinced it is agile. Below are the two main reasons why it just doesn't feel agile to me.

Project Managers Love It

Project managers, who by their very nature are obsessed with timelines, all seem to love Scrum. In my experience they seem to use the Sprint Backlog as a means to track time requirements and keep a record of how much time was spent on a given task. Instead of using a whiteboard they all use an excel sheet, which each developer is required to fill out, religiously.

In my opinion this is way too much documentation/time tracking for an agile process. Why would I waste time estimating how long a task is going to take me when I can just get on with the task itself. Or similarly why would I waste time documenting how long a task took when I can move onto the next task at hand.

Standup Meetings

The standup meetings in the previous place I worked were a nightmare. Everyday we had to explain what we had done yesterday and what what we were going to do that day. If we went over on our time "estimate" for a task the project manager would kick up a stink, and reference the Sprint Backlog as a means of showing of incompetent you are for not adhering to the timeline.

Now I understand the need for communication but surely the tone of daily meetings should be lighthearted and focus on knowledge sharing. I don't think it should turn into a where's your homework style charade. Also surely the hole point of agile is that timelines change, they shouldn't be set in stone.

Conclusion

The idea of agile is to make the software better by making the developers life easier. Therefore in my opinion any agile process used by a team should be developer led. I don't think having a project manager use a process they have labeled "agile" to track a project has anything to do with agile development.

Thoughts anyone?


问:
Is virtual machine image a good protection for source code?
We have developed an application that is sold as an online service. After some time we realized that some of customers would need/prefer/require to have it installed locally on their intranet. However the application was developed using scripting language and we wouldn't want to allow clients to access the source code.

The question is: What are the technical downsides of distributing application as a virtual machine image?

答: It is not so easy - even if it is a virtual machine, the client still would have access to its harddisk. I see no pros installing it on a VM. Better solution is to create agreement with no rights of selling You app, and "special" price for that customer - it means HIGH ENOUGH to sell Your sourcecode...</p>


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答:
The world's most popular functional language is Excel.

People write iPhone Apps in Scheme.

Google's Map Reduce is basically functional programming


答:
You probably expected that one, but just because some (many ?) people misuse Scrum in an un-agile way doesn't mean Scrum isn't Agile.

Project Manager : there's no such role in a Scrum team. The Scrum Master is not responsible for budget or meeting deadlines. He's responsible for helping the team out and removing any impediments standing on their way to the goal they committed to. From what you describe, it seems your PM hijacked Scrum to take for himself prerogatives that normally go to the team and Product Owner, perpetuating previous command-and-control habits.

Time tracking : Scrum recommends to track remaining time and sum it up to determine sprint status, not point at time spent by individual team members. This might seem a detail but makes all the difference between a blame-oriented culture and a goal-oriented approach.

From the Scrum Guide :

Monitoring Sprint Progress

At any point in time in a Sprint, the
  total work remaining in the Sprint Backlog can be summed. The
  Development Team tracks this total work remaining at least for every
  Daily Scrum to project the likelihood of achieving the Sprint Goal. By
  tracking the remaining work throughout the Sprint, the Development
  Team can manage its progress.