答:
I had an opportunity to intern at an Agile/Extreme programming factory.  They were using story-cards to drive the iterative development process.  Each story-card drove an implementation or change.  The key was user interaction.  How can one successfully design an interface meant for a user without interacting with a user of the software?

A possible scenario is to begin with user interaction to decide what the user wants first.  Then, iteratively, design the UI based upon increasing feedback, user priority, and what the user must have.

The user stories are there to drive how the user would interact, at what level, and in what manner.  But they are only approximations until interacting with the user.  If there are a multitude of users that would all desire something specific, then a small survey of people may be in order to define some baseline for the UI.


问:
How to deal with warnings in a legacy project
I work on a C++ project that generates bajillions of warnings. Most of the warnings appeared after the code was written:

Initially the project used Visual C++ 8, soon switching to 9, but there is little difference in the generated warnings. Warnings were either fixed or silenced, so there were no warnings then.

Then a 64-bit target was added. It generated a huge amount of warnings, mainly because of sloppy use of types (e.g. unsigned vs. size_t). No one bothered, or had time, to fix them once the code worked for the purpose.

Then support for other platforms using GCC (4.5 and 4.6, some 4.4 initially) was added. GCC is much more picky, so it generated many more warnings. Again nobody bothered, or had time, to fix them. This was complicated by the fact that GCC didn't have a pragma to silence a warning in particular bit of code until 4.5, and according to the documentation it is still not what one would need.

In the mean time some deprecated warnings popped up.

So now we have a project generating thousands of warnings. And I can't even say from how many places, since even .cpp files are compiled several times by different compilers and warnings in headers get printed over and over.

Is there a best practice for cleaning up something like that? Or at least some positive experience dealing with it?

答:
I was reading C++ Coding Standards: 101 Rules, Guideleines, and Best Practices and the second of guidelines suggests "Compile cleany at high warning levels".  It outlines a number of reasons why you would not want that many warnings in a program and chief among them are

There is a potential problem in your code.

Should have silent, successful builds and, if not, you may be missing real problems.

Benign warnings ignored could obscure warnings pointing to real dangers

Programs that compile with warnings may appear correct but it is possible there are real problems with the code that may crop up at some point.  I would suggest categorizing the warnings, give them a level of prioritization and, when you have time, get them corrected.

ContentLicense: CC BY-SA 3.0


答:
I feel your pain because I am in a similar situation. The way I approached the problem is - remove the warnings one module/subproject at the time and set the "treat warnings as error" (Werr) compiler flag for the module after it has been cleaned up. Also, I decided to focus on one platform only, even though we build on several operating systems with different compilers. Finally, for the third-part libraries that we compile, I just turn the warnings off.

Mind you, getting rid of some of these warnings is much easier said than done. For instance, size_t vs unsigned issues you mention can cause integer overflows if you just silence the warnings with casts - so in some cases you replace unsigned with size_t, in other cases you need to detect an overflow at run-time. It is all case-by-case - very tedious and hard.

Title: How to deal with warnings in a legacy project

Body:
I work on a C++ project that generates bajillions of warnings. Most of the warnings appeared after the code was written:

Initially the project used Visual C++ 8, soon switching to 9, but there is little difference in the generated warnings. Warnings were either fixed or silenced, so there were no warnings then.

Then a 64-bit target was added. It generated a huge amount of warnings, mainly because of sloppy use of types (e.g. unsigned vs. size_t). No one bothered, or had time, to fix them once the code worked for the purpose.

Then support for other platforms using GCC (4.5 and 4.6, some 4.4 initially) was added. GCC is much more picky, so it generated many more warnings. Again nobody bothered, or had time, to fix them. This was complicated by the fact that GCC didn't have a pragma to silence a warning in particular bit of code until 4.5, and according to the documentation it is still not what one would need.

In the mean time some deprecated warnings popped up.

So now we have a project generating thousands of warnings. And I can't even say from how many places, since even .cpp files are compiled several times by different compilers and warnings in headers get printed over and over.

Is there a best practice for cleaning up something like that? Or at least some positive experience dealing with it?


问:
Suggested Web Application Framework and Database for Enterprise, “Big-Data” App?
I have a web application that I have been developing for a small group within my company over the past few years, using Pipeline Pilot (plus jQuery and Python scripting) for web development and back-end computation, and Oracle 10g for my RDBMS. Users upload experimental genomic data, which is parsed into a database, and made available for querying, transformation, and reporting.

Experimental data sets are large and have many layers of metadata.  A given experimental data record might have a foreign key relationship with a table that describes this data point's assay. Assays can cover multiple genes, which can have multiple transcript, which can have multiple mutations, which can affect multiple signaling pathways, etc.  Users need to approach this data from any point in those layers in the metadata. Since all data sets for a given data type can run over a billion rows, this results in some large, dynamic queries that are hard to predict.

New data sets are added on a weekly basis (~1GB per set).  Experimental data is never updated, but the associated metadata can be updated weekly for a few records and yearly for most others.  For every data set insert the system sees, there will be between 10 and 100 selects run against it and associated data.  It is okay for updates and inserts to run slow, so long as queries run quick and are as up-to-date as possible.

The application continues to grow in size and scope and is already starting to run slower than I like.  I am worried that we have about outgrown Pipeline Pilot, and perhaps Oracle (as the sole database). Would a NoSQL database or an OLAP system be appropriate here? What web application frameworks work well with systems like this? I'd like the solution to be something scalable, portable and supportable X-years down the road.

Here is the current state of the application:

Web Server/Data Processing: Pipeline Pilot on Windows Server + IIS

Database: Oracle 10g, ~1TB of data, ~180 tables with several billion-plus row tables

Network Storage: Isilon, ~50TB of low-priority raw data

答:
You probably would not have to concern yourself with a particular web framework. Just ensure that your apps are readily disributable/clusterable (avoid specific file system dependencies, ensure it can run on any system with a single build, ...) and that your systems are set up to handle multiple nodes.

As far as the backend it really depends on your functionality; you want to choose a datastore(s) that makes sense for your app. You would want to look at the various categories of "NoSQL" type data stores (document, graph, key-value, ...) to see if one or many can be appropriate for your needs. You will also want to ensure that Oracle or another RDBMS actually has limitations your business cannot live with (ex/ have you looked at RAC?).

In short, there is no good answer to this question. Understand your needs, isolate your bottlenecks, know your options, and don't be afraid to mix solutions where appropriate.


问:
How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?

答: Why are you not considering putting your source-code on a local box you maintain and back-up?  This could be achieved through subversion/Tortoise-SVN quite easily and would obviate the need to utilize a distributed repository unless, of course, that is what you need.</p>


问:
How to learn/become capable of thinking out of the box?
In every problem solving there's always people who think differently, who come with a 6th option when only 5 were suggested by others, who think "out of the box". Please tell how one can achieve such ability? And what it takes to achieve it?</p>

答:
I'm not sure that everyone can achieve such an ability, but here are my suggestions for ways to possibly try to get there, assuming you don't already:

Cognitive Behavior Therapy - This can be similar to "rewiring" one's brain.  In my case, I've gotten much more used to see how balanced things can be, to see the other side rather than plow on with what I initially think of something.  The book, "Mind Over Mood," has some exercises that can help with this if you want to go down this road.  This is used for treating anxiety and depression is how I ran across this topic.

Self-help books - For example, Dr. Phil's first book, "Life Strategies," has exercises that can help to try to unlock how you think and possibly if you do the exercises sincerely and honestly, you may achieve a similar result to one.  There may be other books that work here but also quite a few that don't work for some people so it can be a bit of a trial and error to find the few that do work for someone.

Grand amounts of knowledge - For example, how many different sorting strategies do you know?  I remember a few taught in school like bubble, shell, quick, heap, and merge, so there is the chance that by absorbing ridiculous amounts of knowledge you could have the list of various heuristics to try to solve a problem.  Example of heuristics here would include being greedy, divide and conquer, dynamic programming, and use of specialized data structures.  In some cases, just knowing a ton of stuff that be enough to think in a box bigger than someone initially thought. ;-)

ContentLicense: CC BY-SA 2.5


问:
When to (enforce) linting in a software project
I'm heading a new team of developers working on a software project that makes use of continuous integration (circleci) w/ a pretty fleshed out suite of busterjs unit/integration/acceptance tests. Our project is primarily written w/ coffeescript, and I try to make use of coffeescript-linter to ensure everyone working our code base keeps code consistent and as organized as possible.

My question is, does anyone have any thoughts on when/if/how to enforce linting? Should I integrate linting into my tests that are executed by circleci before deployment?

Another thought I had was writing a simple shell script that combines git-push and the linting utility into one step and then including it in the project & having everyone use it.

I'm pretty new to managing teams of programmers so anyone else's feedback is much appreciated.

EDIT:
In the last 3 seconds it just occurred to me that git-hooks is probably perfect for this. Specifically a git-hook on commit.

答:
When you a) have a coding standard and b) have configured the linter to be consistent with the coding standard, that's when you start enforcing linting.

Put the linter on the CI server.


答:
The question is, how important is it to you that issues found by coffeescript-linter are addressed immediately.

If it is unacceptable to have code in the repository that gets flagged by the linter, then you should have the linter run as a commit hook so it can block the commit if there are issues.

If it is undesirable but not unacceptable, then I would run the linter as part of the test suite (and it it complains, regard that as a test failure)

If it is not practical to run the linter as a test case, then I would run it on the CI server on a separate schedule (for example, once a day or once a week) and encourage developers to use the linter when they have a particularly large commit.

Title: When to (enforce) linting in a software project

Body:
I'm heading a new team of developers working on a software project that makes use of continuous integration (circleci) w/ a pretty fleshed out suite of busterjs unit/integration/acceptance tests. Our project is primarily written w/ coffeescript, and I try to make use of coffeescript-linter to ensure everyone working our code base keeps code consistent and as organized as possible.

My question is, does anyone have any thoughts on when/if/how to enforce linting? Should I integrate linting into my tests that are executed by circleci before deployment?

Another thought I had was writing a simple shell script that combines git-push and the linting utility into one step and then including it in the project & having everyone use it.

I'm pretty new to managing teams of programmers so anyone else's feedback is much appreciated.

EDIT:
In the last 3 seconds it just occurred to me that git-hooks is probably perfect for this. Specifically a git-hook on commit.


答:
Don't touch any of the legacy code. Find a way to suppress the warnings for now. Making seemingly innocuous changes to the code can introduce bugs in code which, I assume, has already been tested and is relatively bug free.

By suppressing all of the warnings that are currently in the codebase, you can pretend to have a clean slate. Any new warnings introduced into the code should be eliminated, and when old code is rewritten the new implementation should not suppress warnings.

Your goals here should be:

Reduce the signal/noise ratio. If developers see thousands of notices when they build, they aren't going to notice that the master branch has 2004 notices and their branch has 2006.

Don't introduce any more bugs. By making the aforementioned innocuous changes, you could be introducing unforseen bugs. This is especially pertinent when you have thousands of warnings. Even if your error rate is incredibly low, you still have thousands of chances to screw up.

Don't let the legacy code lower your standards for new code. Just because the warnings for a class were suppressed doesn't mean that the new class can do the same. Eventually, with diligence, the legacy code will be eliminated from the codebase and replaced with newer, warning-free code.


答:
Have an open mind and go out of your way to explore as many options as you can about anything. Use this with life, not just programming.

If you only stick with what you know, you'll never have anything to compare with. If you go out there and explore alternatives you'll start to see other ways of doing things. After time, you start realizing you can find links in unrelated objects. A video game you enjoy might have some feature that you would absolutely love to see in the business application you're working on even if it is totally unrelated. Your microwave might have a really cool configuration setting you'd like to implement.

Title: How to learn/become capable of thinking out of the box?

Body: In every problem solving there's always people who think differently, who come with a 6th option when only 5 were suggested by others, who think "out of the box". Please tell how one can achieve such ability? And what it takes to achieve it?</p>


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
Our company (C#) coding standard called for extensive use of #REGIONs (for those who don't know, it marks blocks of source code that will be collapsted to a single line in Visual Studio). As a consequence, you always opened what seemed to be a nicely structured class, only to find piles and piles of garbage swept under deeply nested rugs of #REGION constructs. You'd even have regions around single lines, e.g. having to fold out a fold out a LOG region to find one single declaration of the Logger. Of course, plenty of methods added after some region was made, were placed in the "wrong" region scope as well. The horror. The horror.

Regions are one of the worst features ever added to Visual Studio; it encourages structuring the surface rather than the actual OO structure.

Nowadays, I kill #REGIONs on sight.


问:
Aspect oriented programming and implicitness
Lets suppose that I have a class which represent an image and has a number of methods.

```<code>class Image
{
    circle(x,y,radius,color);
    square(x,y,w,h,color);
    floodfill(x,y,color)
    clear();
}
</code>```

Furthermore, I want to have undo functionality. A simple way of implementing this is to keep a list of all the actions that have been performed. When I undo, I just re-run all of the actions. One solution would be to implement an aspect, something like this:

```<code>aspect ImageUndo
{
    on Image::circle, Image::square, Image::floodfill
    precall(object, args)
    {
         object.actions_list.add(args)
    }
}
</code>```

Essentially, this aspect has now modified the behavior of Image. That gives me concern. In particular, another programmer unfamiliar with the existence of ImageUndo aspect may run into the following problems:

He adds a method, and it does not work with the undo functionality.

Attempting to debug the undo mechanism, it is not clear where the actions_list get added to.

On the other hand we could have

```<code>class Image
{
    @undoable_action
    circle(x,y,radius,color);

    @undoable_action
    square(x,y,w,h,color);

    @undoable_action
    floodfill(x,y,color)

    @undoable_action
    clear();
}
</code>```

Which does not bother me as much because it gives an idea of where to look for the undo code and makes is so that the new coder will probably notice it an automatically add it to a new method.

To summarize: aspects (at least those like the one I showed) seems to bring "implicit magic" into what code does. It seems to me that the implicitness is dangerous and we should really make it explicit.

Are there good reasons for the implicitness? Do people who actually use AOP write code that does this sort of modification?

Note: this is a reworking of Are certain problems solved more elegantly with AOP? which was closed because my previous version came across, unintentionally, as ranting.

答:
Classes that implement cross-cutting concerns have nothing to say about the core functionality of classes being AOP'd.  That's the core idea here.

Your example is one of an undo action.  Let's take it a step further: we will make a deep copy of your class and store it somewhere.  If we want to perform an undo, all we have to do is reverse the deep copy.  This will "roll back" the class to its original state.  You don't even need to annotate the class members to make it work (although you could annotate the class itself if you wanted the deep copy to operate automatically).

Here's my question: Does this deep copy process have anything at all to do with the primary functionality of the class being deep copied?  Does the deep copy even care what the class does?

Serializing and deserializing objects are another example of this.  The serialization process has no knowlege of the behavior of the class, and the objects being serialized have no knowledge of the serialization process.  It's a powerful decoupling tool.


问:
Evaluating the complete revision of other's software
I'm having some difficulty to evaluate the revision of a software: the software was paid by customer years ago, never used, and now the customer have noticed that it doesn't work as expected.

Now this customer asked me to evaluate the project (I have the sources), and I should give an estimation of the time to fix it and probably a maintenance contract.

However, after having analysed the code all the day, I notice that the source code base is very bad. Here is the crucial characteristics:

A lot of source lines (140K+)

C++ without classes, all statically allocated, all externs, all public

Poor comments, poor documentation

A bunch of warnings, counted more than 7K+ times. Warnings spreads from unsigned/signed mismatch to aliased variables, till uninitialized variables.

Static analysis tools have signaled buffer overflows, unassigned variables, suspect string operations.

Lot of multithreading and no critical section at all.

The code will compile, but only the "debug" version is able to run for a short time. I suspect that buffer overflows are working enough.

I've already encountered code like this, I'm not surprised that it is not working as expected. Now I'm thinking how to face this task in the most convenient way, and this is what I thought:

Fix all compiler warnings.

Fix all static analysis warnings

Ensure exclusive access to data shared across multiple threads

Enable _HAS_ITERATOR_DEBUGGING for debugging std::vector accesses (vector is used a lot). This imply an upgrade to VS 2005, at least.

Uses CRT heap debugging as much as possible, even if this imply to move most of the global variables to be allocated on the heap.

Extensive use of assertions (along with minidump creationg for post-mortem analysis)

Exhaustive test cases to prove/test software robustness.

I would like to prepare unit testing, but I should refactor methods with 2500+ lines, and it would add enough pain to give up.

I think I have a good plan, or maybe I'm only in the right direction. I think I'm missing a measurement to actually evaluate the work I could face. Any thoughts?

答: You are describing dead code.  If it hasn't been used for years, it never worked, and the customer's needs at the time it was written are not the same as the customer's needs today.  Broken, untested, unmaintainable code will never meet your customer's needs and you will go through more pain, and your customer through much greater expense (not to mention risk of failure) by trying to scavenge something useful from the existing code base than by starting fresh, with a minimum viable product that your customer can start using soon and giving you feedback on.</p>


问:
What is the difference between a stock-hardware and a micro-coded machine in "A Critique of Common Lisp"?
I was reading this article: A Critique of Common Lisp and finding it hard to make out the precise definition of "stock-hardware machine" and its difference with "micro-coded" machines. I tried to search for a precise definition of the former to no avail.

What I currently construe stock-hardware machine to be is that, it refers to the computer chip-set commonly available in the market (without much customization).

So given that I would like to ask, what is meant by a stock-hardware machine (in the context of the paper) and how does it differ from a micro-coded machine?

答:
In the context of the paper you linked, the words "micro-coded machine" would almost certainly refer to a Lisp Machine.

At the time Lisp was beginning to get a foothold, it was hoped that it would be run (in the general case) on machines that were designed specifically to execute Lisp instructions, rather than computers with a more general instruction set intended to be used with compilers and interpreters for any language.

Microcode is what happens underneath the actual processor instructions.  The processor that you are using to read this right now has machine instructions that are almost certainly implemented in some sort of microcode.  But at that time, there were probably machines that

Implemented machine instructions in hardware; that is, logic gates, and

Machines that implemented advanced processor instruction sets (Lisp being one example) in microcode.

The former type would have been referred to as "stock hardware."  The paper's point, of course, is that any machine designed specifically to execute Lisp instructions directly would have been much better at executing Lisp programs than a machine which required translation of the Lisp instructions to some other instruction set.

At the time the paper was written, this distinction would have been very important, because there were unavoidable memory and processor constraints that no longer exist today.


答: Stock hardware basically means "not customized," as you surmised.  Which customizations it refers to depends on the context.  In the context of the paper, it means a computer which is not micro-codable.  Micro code is to machine code as assembly is to a high-level language.  It breaks down each instruction into smaller parts.  On most processors, the microcode is completely unchangeable, even by assembly programmers, because it is baked into ROM at the fab.  On some supercomputers you can change it.  The authors are arguing that Common LISP isn't as efficient on computers where the micro code cannot be customized.</p>

Title: What is the difference between a stock-hardware and a micro-coded machine in "A Critique of Common Lisp"?

Body:
I was reading this article: A Critique of Common Lisp and finding it hard to make out the precise definition of "stock-hardware machine" and its difference with "micro-coded" machines. I tried to search for a precise definition of the former to no avail.

What I currently construe stock-hardware machine to be is that, it refers to the computer chip-set commonly available in the market (without much customization).

So given that I would like to ask, what is meant by a stock-hardware machine (in the context of the paper) and how does it differ from a micro-coded machine?


问:
Byte code weaving vs Lisp macros
I have been reading about the libraries people have written for languages like Java and C# that make use of byte code weaving to do things like intercept function calls, insert logging code, etc. I have also been reading up on Lisp/Clojure macros in an attempt to better understand how to utilize them. The more I read about macros, the more it seems like they provide the same kind of functionality as byte code weaving libraries. By functionality, I mean the ability to manipulate code at compile time.

Examples of libraries I have been looking at would be AspectJ, PostSharp, and Cecil.

Is there anything that can be done with one and not the other? Do they actually solve the same problems or am I comparing apples and oranges?

答:
Although they may be used to the same end, LISP macros are quite different from Java byte-code weaving plugins.  LISP macros extend LISP syntax at the LISP source code level.  Since LISP macros are written at the same level as other LISP code, they are a commonly used language feature.

Java byte-code weaving plugins operate at the JVM level.  While many Java programmers may use byte-code weaving plugins written by others, very few Java programmers write their own byte-code weaving plugins.

Some of the work done by Java compiler plugins is very easily done in dynamic languages.  Function-call interception is particularly simple.

Title: Byte code weaving vs Lisp macros


问:
Why didn't == operator string value comparison make it to Java?
Every competent Java programmer knows that you need to use String.equals() to compare a string, rather than == because == checks for reference equality.

When I'm dealing with strings, most of the time I'm checking for value equality rather than reference equality. It seems to me that it would be more intuitive if the language allowed string values to be compared by just using ==.

As a comparison, C#'s == operator checks for value equality for strings. And if you really needed to check for reference equality, you can use String.ReferenceEquals.

Another important point is that Strings are immutable, so there is no harm to be done by allowing this feature.

Is there any particular reason why this isn't implemented in Java?

答:
This has been made different in other languages.

In Object Pascal (Delphi/Free Pascal) and C#, the equality operator is defined to compare values, not references, when operating on strings.

Particularly in Pascal, string is a primitive type (one of the things I really love about Pascal, getting NullreferenceException just because of an uninitialized string is simply irritating) and have copy-on-write semantics thus making (most of time) string operations very cheap (in other words, only noticeable once you start concatenating multi-megabyte strings).

So, it's a language design decision for Java. When they designed the language they followed the C++ way (like Std::String) so strings are objects, which is IMHO an hack to compensate of C lacking an real string type, instead of making strings an primitive (which they are).

So for a reason why, I can only speculate they made that to easy on their side and not coding the operator make an exception on compiler to strings.


答:
There is no way for us to answer this, other than to say that you are being tasked to perform something impossible, and to run as far away as possible!

Okay, that is a bit unfair, but some things just cannot be known/estimated. The only way you can give an estimate that has any chance of being vaguely related to the truth is to work with the code and understand it. We are talking weeks to months. I doubt you are being paid for this estimation effort; it sounds like you are bidding for a job. So, your business depends on what will amount to a total guess.

I would tell the person that it cannot be estimated without weeks of work. Your general workflow sounds not bad, and so just suggest that you do this for a month, and at time you will regroup. Note there is no promise that you will have a better estimate on the amount of work - that too is unknowable. At some point it will become clear whether it makes more sense to keep pouring money into this code, or start from scratch, or just abandon the whole idea.

With that said, I think the post about this being "dead code" is 100% accurate. I cannot estimate how much it would cost to iteratively transform a beat up mobile home into a 35 room mansion, but I can tell you that it would be cheaper to just raze the thing and start from scratch. You don't need to estimate the magnitude of a money sink.

Title: Evaluating the complete revision of other's software

Body:
I'm having some difficulty to evaluate the revision of a software: the software was paid by customer years ago, never used, and now the customer have noticed that it doesn't work as expected.

Now this customer asked me to evaluate the project (I have the sources), and I should give an estimation of the time to fix it and probably a maintenance contract.

However, after having analysed the code all the day, I notice that the source code base is very bad. Here is the crucial characteristics:

A lot of source lines (140K+)

C++ without classes, all statically allocated, all externs, all public

Poor comments, poor documentation

A bunch of warnings, counted more than 7K+ times. Warnings spreads from unsigned/signed mismatch to aliased variables, till uninitialized variables.

Static analysis tools have signaled buffer overflows, unassigned variables, suspect string operations.

Lot of multithreading and no critical section at all.

The code will compile, but only the "debug" version is able to run for a short time. I suspect that buffer overflows are working enough.

I've already encountered code like this, I'm not surprised that it is not working as expected. Now I'm thinking how to face this task in the most convenient way, and this is what I thought:

Fix all compiler warnings.

Fix all static analysis warnings

Ensure exclusive access to data shared across multiple threads

Enable _HAS_ITERATOR_DEBUGGING for debugging std::vector accesses (vector is used a lot). This imply an upgrade to VS 2005, at least.

Uses CRT heap debugging as much as possible, even if this imply to move most of the global variables to be allocated on the heap.

Extensive use of assertions (along with minidump creationg for post-mortem analysis)

Exhaustive test cases to prove/test software robustness.

I would like to prepare unit testing, but I should refactor methods with 2500+ lines, and it would add enough pain to give up.

I think I have a good plan, or maybe I'm only in the right direction. I think I'm missing a measurement to actually evaluate the work I could face. Any thoughts?


答:
Take the time it would take you to build a system like this from scratch and then multiply it by a factor of ten. That might adequately capture the average-case complexity even if it doesn't adequately assess all the risks.

This is about as good an example as I can conceive of for when not to do the Big Rewrite. Whatever the true level of effort is, it's way beyond any reasonable threshold for feasibility.


答:
Even when providers are trustworthy, you never know what crackers targets and any open site is crackable when the will to do so is there.

In my company we bought GitHub Enterprise, which is our very own github on our intranet. If you like GitHub and are serious about keeping your work private, this is probably the safest.

Title: How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?

Body:
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?


答:
Learn to see the box

Look at the box and understand its constraints.  Consider which of those constraints are actually beneficial to solving the problem, and point out which are either in the way or not necessary.

You might think that the answers mentioning assumptions are exactly the same thing, but I'm not sure that they are.  Knowing the realm of the problem is important, too.  Once you've got a clear picture of the problem and already considered solutions, you can pick up one piece and and see if other potential solutions come to mind.

Expand your box

You can never think outside of the box which is your own mind.  So, keep expanding on what you know and have heard about.  Things that may seem uninteresting to other people should hold interest for you.  There is almost always some detail that you actually could find unexpected and exciting.

All of these random, insteresting bits of information can come together in odd ways when you are analyzing a problem.  You just never know what will happen.

Oddball answer:

For fun and practice, listen to what people say in normal conversations and see how it would work out both literally and by using alternative meanings for the words they've chosen.  This can turn into puns or other entertaining misuses of the language, but it also is a rather frequent way to exercise "thinking outside the box".


问:
mvc pattern on procedural php
First off, I do not have anything against OO programming (I'd be mad if i believed so). But I was thinking on some sort of procedural MVC pattern with PHP; let me explain better.

As we all know, variable scopes, unless they are taken from $_SESSION (, database, redis, etc.) are never global and only refer to a singular execution of a script. For example:

```<code>class Car {
  this->name = "foo";
  function setName($name) { ... }
  function getName() { return $this->name; }
}
</code>```

Where obviously in a more common situation, this data will be taken from the DB, otherwise any object car, per execution, would have the same name.

Now, is it not possible to apply MVC pattern on procedural code for simplicity purpose? Imagine a really simple social network like application; I could have a structure like this

```<code>*views
  -profileview.php
  -messageview.php
  -loginview.php
  -notloggedin.php
*models
  -user.php
  -message.php
- profile.php
- messages.php
- login.php
</code>```

where profile, messages and login.php work as controllers and route to the right view; and user and message.php work as the classes, that contain all the functions that are eventually needed by the controllers, such as getUserById($id), postMessage($id, $meesage), etc.

I have simplified it a lot but I think you can sort of understand my point.

What would you think of such implementation on the long run, and why?

答:
You can build a house out of mud but it's much easier when you have boards, nails, and other useful domain objects available.

To expand on this a bit, the reasons object oriented programming is better suited for this task than procedural programming are the same reasons object oriented programming is better at most tasks:

Reuse.

Polymorphism increases expressiveness.

It better models the real world and human thought processes.

Increases cohesion.

Reduces coupling.

Better mechanisms for encapsulation and information hiding.

All of these are debatable but none of them are especially new.

Title: mvc pattern on procedural php


问:
Is path in Set-Cookie URL encoded?
I'm writing some code that sets cookies and I'm wondering about the exact semantics of the Set-Cookie header. Imagine the following HTTP header line:

```<code>Set-Cookie: name=value; Path=/%20
</code>```

For with path does this set the cookie? / or /%20(unescaped) (/%20 or /%2520 escaped)?

The reason I'm asking is that I should support non-ASCII paths. Since HTTP header must only be ASCII my plan was to URL escape the path value but the HTTP specification is not as clear as I'd hoped for.

Edit

I know what Path is supposed to do. My question is: Is the value interpreted as percent encoded or not?

答:
My intuition says that the path is an URL-encoded value (since it is a URL).

Why not test it? I created the following nginx config:

```<code>add_header Set-Cookie "k=v; path=/";
add_header Set-Cookie "f%2520o=ba%2520r; path=/qa%20x";
add_header Set-Cookie "f%2520o=ba%2520r; path=/qb%25x";
add_header Set-Cookie "Z%2520Z=Z%2520Z; path=/";
location ~ /q.* {
    try_files $uri /cookie.html;
}
</code>```

The index page:

```<code><iframe src="/qa%20x"></iframe>
<iframe src="/qa x"></iframe>
<iframe src="/qb%25x"></iframe>
<iframe src="/qb%2520x"></iframe>
<iframe src="/qb%20x"></iframe>
</code>```

The cookie page is essentially writing document.cookie. Conclusion: the path is interpreted as a percent-encoded sequence (with automatic conversion of a space to %20 as needed). I have tested it in Firefox and Chromium, both  browsers show the same behavior. Guess which browser is an exception of this... IE8 did not show the cookies from the percent-encoded path.

I did more tests, and it turned out that IE ignored cookies with path /foo for a literal request to /foo. A request for /foo/ (with Set-Cookie: key=val; path=/foo) works though. Even with percent-encoded values.

Title: Is path in Set-Cookie URL encoded?

Body:
My intuition says that the path is an URL-encoded value (since it is a URL).

Why not test it? I created the following nginx config:

add_header Set-Cookie "k=v; path=/";
add_header Set-Cookie "f%2520o=ba%2520r; path=/qa%20x";
add_header Set-Cookie "f%2520o=ba%2520r; path=/qb%25x";
add_header Set-Cookie "Z%2520Z=Z%2520Z; path=/";
location ~ /q.* {
    try_files $uri /cookie.html;
}

The index page:

<iframe src="/qa%20x"></iframe>
<iframe src="/qa x"></iframe>
<iframe src="/qb%25x"></iframe>
<iframe src="/qb%2520x"></iframe>
<iframe src="/qb%20x"></iframe>

The cookie page is essentially writing document.cookie. Conclusion: the path is interpreted as a percent-encoded sequence (with automatic conversion of a space to %20 as needed). I have tested it in Firefox and Chromium, both  browsers show the same behavior. Guess which browser is an exception of this... IE8 did not show the cookies from the percent-encoded path.

I did more tests, and it turned out that IE ignored cookies with path /foo for a literal request to /foo. A request for /foo/ (with Set-Cookie: key=val; path=/foo) works though. Even with percent-encoded values.


问:
Customer Requirements Contains Equations that Cancel to Nothing
I have a project where the customer requirement specifies a report and contains mathematical equations for the contents of some of the columns on that report. One of the columns on this report is a running total which starts at a opening value, and which 'should' remain at that opening value all the way down the report because the other stuff balances out. I.e. if something had gone missing, the value would change and the customer would see that there is a problem.

The reason I quoted the 'should' in that last paragraph is because the spec defines an equation for this column, and I can mathematically prove that it cancels out to 'the value from the previous row'. In other words, the value will never ever change from the opening value.

So my options are:

Implement the equation as spec'd, I suspect the interpreter will not resolve the equation so there will be a performance hit

Do some cancelling out, and implement the column value as 'value from the previous row'

Send the question back up the chain to the customer and risk missing the deadline because of several days lost to bureaucracy and impromptu math 101 lessons to explain the difference between "yeah, it'll never change, it's there just in case" and "it. will. never. change."

I've pretty much decided what I'm going to do, but I thought it was an interesting question. What do you think is the professional thing to do?

答: Provide a counterexample, rather than a mathematical explanation, to the chain of command.  That way they can immediately see that it's broken, even if they aren't mathematically inclined.  </p>


答:
The standard to support IRIs states the character encoding for such URL must be UTF-8. It also states in 4.1.2.4 in HTTP State Management Mechanism that the path is that of the directory part of the URI (i.e. the encoded IRI). Eg. the directory '/å/' has Cookie path '/%C3%A5/' even though the response header states the content-type is ISO-8859-1.

%20 is a encoded space in UTF-8 charset, thus the cookie-path '/%20' is slash-space.

Title: Is path in Set-Cookie URL encoded?

Body:
I'm writing some code that sets cookies and I'm wondering about the exact semantics of the Set-Cookie header. Imagine the following HTTP header line:

```<code>Set-Cookie: name=value; Path=/%20
</code>```

For with path does this set the cookie? / or /%20(unescaped) (/%20 or /%2520 escaped)?

The reason I'm asking is that I should support non-ASCII paths. Since HTTP header must only be ASCII my plan was to URL escape the path value but the HTTP specification is not as clear as I'd hoped for.

Edit

I know what Path is supposed to do. My question is: Is the value interpreted as percent encoded or not?


问:
Is there genetic relationship between ARM and PDP-11 architectures?
Reading about ARM architecture I found many similarities to PDP-11 architecture which did not exist between ARM and x86.

For example,

General-purpose registers named Rx compared to AX, BX,... for x86

Uniform registry file (all registers permit all kinds of operations)

Similar names for program counter (PC both on ARM and PDP), compared to IP in x86.

Inclusion of Program Counter into general registry file (in PDP it also can be refereed to as R7, in ARM - as R15, both the last registers in the file).

Inclusion of I/O ports into general address space (i.e. addressing them as memory) compared to a separated I/O address space in x85 (and special I/O instructions).

Using 3-letter basic assembler mnemonics (TST compared to "test" in x86) with suffixes specifying data type (such as "B" for byte, compared to constructions like "byte ptr" in x86)

Using BNE, BEQ and other B condition instructions for branches.

Use of "#" symbol before a number to specify an immediate value (compared to "." in x86)

Auto-increment and auto-decrement addressing modes.

etc. So is there any historical relationship between ARM and PDP that makes them closer to each other than to x86?

答:
I don't know how much the designers of the ARM architecture took inspiration from the PDP-11. They probably knew the PDP-11 architecture well as it was one of the major CPUs of the 1970s. However, it's more the x86 which is different from the other two.

ARM is a RISC architecture: its instructions tend to follow a few model and to do just one thing. Compare with MIPS which is pretty much textbook RISC. Both PDP-11 and x86 are CISC, with many instructions combining several operations (e.g. a load and a store, or a memory access plus an arithmetic operation). In some aspects, the PDP-11 was a forerunner of RISC, in particular with its fairly orthogonal instruction set (e.g. the main registers, including the program counter, are general-purpose registers usable with any instruction).

Naming the general-purpose registers Rx is pretty natural. X86 doesn't do this because almost all its registers have a special purpose (even ax through dx have some specificities, e.g. multiplication that can only be ax*dx).

Using special instructions or a memory mapping for I/O is related to how the I/O unit connects to the CPU. If I/O goes through the same bus as RAM, it's natural to use a memory mapping and let the memory bus controller dispatch the signals. If I/O goes on a separate bus, it's natural to have separate instructions, with the CPU doing the dispatching right off the bat.

B for branching isn't specific to PDP and ARM. There are two x86 assembly syntaxes: AT&T syntax and Intel syntax. mov byte ptr [ax], bx is Intel syntax; the corresponding AT&T syntax is movl (%bx), %ax. The AT&T syntax is closer to major assembly languages used today.

OwnerDisplayName: Anixx

ContentLicense: CC BY-SA 4.0


问:
Is (1/(1/x)) always a perfect round trip?
Is the following guaranteed to return true for all numerical and non-zero values of x?

```<code>bool IsRoundTrip(double x)
{
    double y = 1 / (1 / x);
    return x == y;
}
</code>```

What conditions would cause a discrepency?

答:
No.  As a counterexample, 1/(1/49) works out to 49.00000000000000710542735760100185871124267578125 on my machine.

For a more abstract argument, let N be the number of representable floating-point numbers in the interval [1, 2).  (In IEEE 754 double-precision, N happens to be 2^52) There is a trivial one-to-one mapping between this set and the floating-point numbers in the interval [1/2, 1): Just subtract 1 from the exponent.  Thus, there are also N floating-point numbers [1/2, 1).

Within each interval [2^k, 2^(k+1)), floating-point numbers are equally-spaced.  So:

With N floating point numbers in the interval [1/2, 1):

~N/3 are in the interval [1/2, 2/3)

~N/3 are in the interval [2/3, 5/6)

~N/3 are in the interval [5/6, 1)

With N floating-point numbers in the interval [1, 2):

N/2 are in the interval [1, 3/2)

N/2 are in the interval [3/2, 2)

The N/2 floating-point numbers in the interval [3/2, 2) have reciprocals in the interval (1/2, 2/3].  But there are only ~N/3 floating-point numbers available in this range.  Therefore, by the pigeonhole principle, there exists a pair of distinct floating-point numbers that have the same floating-point reciprocal.


问:
How to best organize spaghetti Javascript on the client with an MVC server architecture?
A LAMP project I am currently working on is pretty well organized on the backend. However, there are a ton of pages that just have a diarrhea of javascript and html squirted all over numerous locations with little discernible architecture, rhyme, or reason. In a few cases, some kind of javascript prototype was created for a common control, and the MVC framework in place is taking care of templating pages.

How do we start to get all this spaghetti code under control? On backend projects I would start with getting some unit testing in place, CI, refactor common MVC or model/mapper code out etc..

答:
Do the same things. Unit testing is available via phantomjs or other runtimes and testing frameworks like Jasmine, Mocha, and etc. You might also look at Karma. It is possible to do CI builds using these tools.

You can refactor in JS just like you would in other languages.

In short, take all your knowledge for dealing with this problem in backend code and use the tools that are available to start applying it to your frontend code.


问:
What feedback is or is not appropriate for a code review?
I am interested in hearing some guidelines as to what feedback is or is not appropriate for a code review.  My team has a very unstructured review process and I am trying to suggest some ways to improve it.  I am no expert so I hope to hear from you experts out there!

Should code review comments be limited to actual problems with the    code?

Are criticisms about other LOC in the file appropriate even if those lines are not being modified?  i.e., criticism of pre-existing code?

What about suggestions of different ways to solve the same problem?  Should I suggest a new way only when a case can be made for it being better?  How do I draw the line between contributing ideas but not sounding like a know-it-all?

In matters which are purely a difference of opinion, who should get the 'final say'?  The author, the person who knows the code base the best, the person with the highest title or someone else?

Any other advice for ensuring the code reviews serve their purpose without unnecessarily blocking the developer's progress?

Please, if you could, provide reasoning along with any answers.  It will help this junior developer be able to really understand the best way to approach a code review.

答:
A code review is limited to reviewing the code being changed, and anything directly related to that. For the purposes of the code review, design or requirements are not appropriate for discussion. Ideally you should have settled on the design before code has been written, so if you find such issues during a code review, there was a failure in communication (someone misunderstood the requirements).

Don't get me wrong; it is very important to get the design and requirements right, no matter when you discover problems with them, but if you discover them during a code review, suggestions to do it a different way are not part of the actual review!

Should code review comments be limited to actual problems with the code?

Yes

Are criticisms about other LOC in the file appropriate even if those lines are not being modified? i.e., criticism of pre-existing code?

Unless they are related to the code being modified, no. For example, "I see you are changing these lines like so, it would be great to also change these other lines too" - is appropriate.

What about suggestions of different ways to solve the same problem? Should I suggest a new way only when a case can be made for it being better? How do I draw the line between contributing ideas but not sounding like a know-it-all?

Not appropriate

In matters which are purely a difference of opinion, who should get the 'final say'? The author, the person who knows the code base the best, the person with the highest title or someone else?

It's whoever has final say on what goes into the code base. This is unrelated to the code review process.

Any other advice for ensuring the code reviews serve their purpose without unnecessarily blocking the developer's progress?

Code reviews should be streamlined so that they never block a developer's process. Here are some issues to watch out for:

Make sure code gets reviewed promptly; this means the person reviewing the code shouldn't be too busy

The reviewer must be pretty knowledgeable about the code being reviewed

Ensure that people never have to redo work after issues are discovered during a code review. That is, have clear specifications, or communicate between the coder and reviewer about what the proposed solution will be, before code has been written.

Foster a culture of open reviews - let anyone be able to easily review other people's code, because code reviews are a great way to share knowledge between developers.

Point towards the organisation's coding standards whenever differences in opinion arise. Ideally the standard is the final say, and if any conflicts arise because they are not covered by the standard, update the standard.


问:
How do you keep consistent self confidence while coding?
As the number of bugs in a codebase increases, that number not only decreases the quality of the code, it also affects the mindset of the developers.  Developer self-confidence falls when things are not going well.  If self-confidence is not right, things more easily become a mess.  How do you guys keep your self confidence up in these situations?</p>

答:
Learn about these:

Get to know the language better - starting with introductory books and then move on to advanced ones

Basic algorithm proofing techniques

Unit testing

Integration testing

Combinational testing

The purpose of knowing the language better and learning basic algorithm proofing techniques is to be able to reason about the execution of the code with high confidence.

The purpose of combining multiple testing methodologies is to get an assurance that the code is able to perform correctly in as many cases as possible. By using algorithm proofing techniques (and maybe combined with some code coverage tools, if available), it is possible to get an exhaustive case coverage without having to exhaustively run through all combinations of input parameters.


问:
What algorithm should I use to find the shortest path in this graph?
I have a graph with about a billion vertices, each of which is connected to about 100 other vertices at random.

I want to find the length of the shortest path between two points. I don't care about the actual path used.

Notes:

Sometimes edges will be severed or added. This happens about 500 times less often than lookups. It's also ok to batch up edge-changes if it lets you get better performance.

I can pre-process the graph.

If it takes more than 6 steps, you can just come back with infinity.

It's acceptable to be wrong 0.01% of the time, but only in returning a length that's too long.

All edges have a length of 1.

All edges are bidirectional.

I'm looking for an algorithm. Psuedocode, english descriptions, and actual code are all great.

I could use A*, but that seems optimized for pathfinding.

I thought about using Dijkstra's algorithm, but it has a step which requires setting the shortest-path-found attribute of every vertice to infinity

(If you're wondering about the use-case, it's for the Underhanded C Contest.)

答:
Basic Algorithm

Maintain two sets of the nodes you can reach from the start and end node. In alternating fashion, go three steps from both sides. Each time replacing your set with nodes you can reach through one more step. After each step you check the two sets for common nodes.

Optimizations

Make sure you can iterate the sets as sorted so that you can search for common nodes in a single sweep: an O(n+m) operation. Lists will be up to a million nodes each.

To extend a set with one step, you have query all connections of the nodes in the original set and merge them into a new sorted set. Merging 2 sorted lists can again be done in a single sweep. So you also want to make sure that you can query the connections of a node as sorted. (This could be preprocessed).

In the last two steps each new set is the result of merging up to 10000 of these query results. It is best to do this merge adaptive (merging equally sized chunks). In that way, the sorted set data structure can be a simple linked list.

That way the whole algorithm becomes O(6*n + 6*n*log n) where n is max. 1,000,000.


答:
Should code review comments be limited to actual problems with the code?

Yes. The purpose of a review is to find where the code will not meet its specification (the design and by extension the requirements).
If you find something odd/missing with either the design or the requirements, the author of the code is usually not in a position do do anything about it (at least not without incurring a significant delay). If you find such issues during a code review, you should enter a bug report for it and continue the review on the assumption that the requirements/design are actually correct.

Are criticisms about other LOC in the file appropriate even if those lines are not being modified? i.e., criticism of pre-existing code?

In a code review, you should only critique what you are being asked to look at.
The only thing you should bring up outside that changeset are places where the author missed a required change or places where a change from the author should be applied as well to keep the overall consistency of the code at a high level.
Any other issue you find during the review, you should enter into the bug tracker if it is important enough to warrant fixing. I would not bother too much with typos in comments.

What about suggestions of different ways to solve the same problem? Should I suggest a new way only when a case can be made for it being better? How do I draw the line between contributing ideas but not sounding like a know-it-all?

Ideally, such things should have come up during the design (review). After that it is a balancing act and I would bring them up only if your solution provides a clear and measurable improvement in ways that are relevant to the success of the project. The balance here is between the advantages of your solution versus the costs of implementing it.

In matters which are purely a difference of opinion, who should get the 'final say'? The author, the person who knows the code base the best, the person with the highest title or someone else?

The final say on such issues should lie with the coding standard. If the coding standard does not rule on the issue, it is best to accept the view of the person who knows the code base best, because that is likely to keep the most consistency in the code base.

Any other advice for ensuring the code reviews serve their purpose without unnecessarily blocking the developer's progress?

As a reviewer:

Try to give the review priority over other tasks

As an author:

Select your reviewers carefully. They should not already be overburdened with work and they should know the subject matter and code base already.

While waiting for the review, see if you can start on the next task without messing up the code that is currently under review.

Title: What feedback is or is not appropriate for a code review?

Body:
I am interested in hearing some guidelines as to what feedback is or is not appropriate for a code review.  My team has a very unstructured review process and I am trying to suggest some ways to improve it.  I am no expert so I hope to hear from you experts out there!

Should code review comments be limited to actual problems with the    code?

Are criticisms about other LOC in the file appropriate even if those lines are not being modified?  i.e., criticism of pre-existing code?

What about suggestions of different ways to solve the same problem?  Should I suggest a new way only when a case can be made for it being better?  How do I draw the line between contributing ideas but not sounding like a know-it-all?

In matters which are purely a difference of opinion, who should get the 'final say'?  The author, the person who knows the code base the best, the person with the highest title or someone else?

Any other advice for ensuring the code reviews serve their purpose without unnecessarily blocking the developer's progress?

Please, if you could, provide reasoning along with any answers.  It will help this junior developer be able to really understand the best way to approach a code review.


问:
A simple C library filling the gaps in standard (C, POSIX) libraries?
I'm looking for a C function library, which would contain a collection of simple and plain utility functions "missing" from C or POSIX standards. I found this earlier question, but answers there list only full frameworks or libraries designed to replace/duplicate standard libraries instead of seamlessly fill the gaps.

To give you an example of functions I'm often missing, and would like to find a lib with tested implementations:

afgets, afread: read a line or entire file, like fgets and fread, except really reads all and returns a malloced buffer, in the spirit of GNU asprintf.

A selection of string trimming functions

systemf, popenf: Like system and popen, but take printf-like format string for command.

strjoin: join multiple strings given as vararg/array (which is hard to do with snprintf)

struct timeval arithmetic

These are just examples of functions I often miss for quick stuff. Then some features I'd desire (not mandatory):

Available on common Linux distros out-of-the-box, with man pages etc

Works also on Windows/Visual C

No extra dependencies, self-contained

As usable as existing C lib functions in C++

Preferably licensed under LGPL or BSD-like license, but GPL is ok too

Stuff which I am not looking for:

A string library with its own string type

A data structure library

A framework library which has special initialization, maybe even event loop etc.

So the question is, what is out there? Library name, homepage link, github link, duplicate question link... If you've made your own and have it at public repo, feel free to link to that too, if you dare expose it to many eyes.

答:
The Apache Portable Runtime has a lot of what you want.

Do not expect anything to come from either C or POSIX. The C/C++ standards group think you should be using C++ and C is only for legacy apps. POSIX is run by a group of hardware manufacturers who will fight any change to the standard as they would incur the expense of implementing any change in their various OSes.

There are lots of functions not easily found on thier web site e.g. apr_file_read_full


问:
Tricky compareTo, inheritance, easy to extend - Java
Let's say we have 4 classes A, B, C, D where: A is a superclass of both B and C and C is a superclass of D. I suppose, in a diagram, it should look like this:

```<code>   A
 /   \
B     C
       \
        D
</code>```

Moreover, the class A implements the interface

```<code>Comparable<A>
</code>```

and also implements a method

```<code>public int compareTo(A another)
</code>```

I'd like to be able to compare every pair of objects x, y such that they are instances of classes from the set {A, B, C, D}.  Naturally, I should implement a compareTo method in each of these classes but by default I'm doing this with one sided effect, i.e. defining how to compare object c from C with b from B doesn't tell anything about how to compare b with c.
Now, I could write a lot of code and handle all of those cases (this also means I would have to use 'isInstance' method to handle these, right?) but then every two classes have to be 'aware of' existence of others. So if I wanted to add another class, E, such that D is a superclass of E, I would have to serve all cases in the new class E and moreover I'd have to change something in classes A, B, C, D in order to 'be aware of E'.

So I'm struggling to find an elegant solution to it, i.e. one that doesn't entail changing a lot while adding a new class to the hierarchy.
How can I achieve this?

Thank you in advance for help.

答: You could write a general compareTo method in class A, which uses a key computed by a method compareKey which is also in A, but can be overridden by each subclass to make as fine a distinction as it wants. If you make it return a float, you can keep subdividing the comparison criterion whenever a new level of inheriting classes is added (within reason, obviously).


问:
What is watershed in the context of image processing?
I am new to image processing using Python.  Now I am learning OpenCV and the mahotas module in Python.  Many functions in these modules are related to watershed of an image.  I don't know what watershed means for an image.  Here is an example from the OpenCV documentation: http://docs.opencv.org/search.html?q=watershed&check_keywords=yes&area=default</p>

答:
Watershed transformation is an image enhancement method. You can think of it like a possible preprocessing step to improve the results of your algorithm.

This site has some imho very illustrative animation: http://cmm.ensmp.fr/~beucher/wtshed.html

Wikipedia has an explanation: http://en.wikipedia.org/wiki/Watershed_(image_processing)


问:
Negative test cases confusion
In the Software testing book from Koirala, Sheihk, they say:

A positive test is when you put in a valid input and expect some
  action to be completed in accordance with the specification.

  A
  negative test is when you put in an invalid input and receive errors.

Part of my question:

Let's say there is a requirement: If the customer name=="James Bond", do something.

Is name<>"James Bond" negative or still positive test, verifying the requirement?

Or a login function:

Is correct login positive test case and incorrect negative?

Or Login failed is just confirmation of requirement that a password must be correct ->confirming invalid pass will not work.

For example, if the program is supposed to give an error when the person types in "101" on a field that should be between 1 and 100, then that is positive then if an error shows up. If, however, the application does not give an error when user types 101, then you have a negative test.

答:
I think the book is trying to make a distinction where it is not strictly necessary.

Tests should be written to make sure a system behaves according to its specification. It should do so for normal operating conditions as well as in exceptional situations.

I assume the author is making a distinction because it is easy to forget to test the exceptional situations. It is just a little guideline that can help you think about things.

Here is an example:
If you are writing a function that will multiply a matrix with a scalar, most people will write a test with a demo matrix and some number and check that the multiplication result is correct. The book wants you to also be on the lookout for the case when your matrix might not be initialized or your number might be from the wrong ring.

Knowing or defining if a test case is positive or negative is not really necessary or useful. It's just a guideline to help you avoid missing classes of inputs.
It is basically a simple way of creating equivalence classes: http://en.wikipedia.org/wiki/Equivalence_partitioning

Title: Negative test cases confusion


问:
UDP order of packets with direct connection
If i have two systems (A and B) running on LAN(INTRANET) which are directly connected. There are no routers in the middle. In this case, if system A sends a few UDP packets every few milliseconds to system B:

Is it possible that system B receives the packets in a different order?

Please note that I'm not asking whether to use TCP or UDP. I'm interested in whether the above scenario will have packets out of order - I'm aware that UDP packets are not guaranteed to arrive in order.

答: UDP packets are not guaranteed to arrive in order. You should use TCP for this.</p>


答:
Yes, it might be that the application on system B receives the UDP packets in a different order than they were sent by the application on system A. If both systems are connected to the same network segment, the likelihood of it occurring is small, but will never be negligible.

What also can happen is that packets get lost, for example because there was a collision between two packets on a switch or hub connecting the systems.

Title: UDP order of packets with direct connection

Body:
If i have two systems (A and B) running on LAN(INTRANET) which are directly connected. There are no routers in the middle. In this case, if system A sends a few UDP packets every few milliseconds to system B:

Is it possible that system B receives the packets in a different order?

Please note that I'm not asking whether to use TCP or UDP. I'm interested in whether the above scenario will have packets out of order - I'm aware that UDP packets are not guaranteed to arrive in order.


答:
They don't have to arrive at all nor in order.

I assume you're hoping that this is not the case due to the simplicity of the setup but there is still an underlying bus system and things like both computers trying to send at the same time can happen.

Of course it won't with switched ethernet but you will have to destroy several layers of abstraction to answer your question in any other way than "maybe not".


问:
Do you find languages with indentation requirements cumbersome?
Thoughts on these?  Python is one example, and no this is not a stab against Python I like the language.

What languages have a indentation requirement?

答:
In general, I'm against bondage and discipline features that are geared towards making it hard to write bad code.  However, I don't find that Python's forced indentation fits this mold.  The compiler/interpreter needs to know where blocks begin and end somehow, and about the only human-readable way to denote this is with indentation.  Therefore, using indentation to denote it to the compiler/interpreter as well is a good example of DRY.

Using curly braces for the compiler/interpreter plus indentation for humans is like writing otherwise inscrutable but excessively commented code.  Information is specified once for the compiler/interpreter, then again for humans.  It has to be kept in sync manually and becomes almost impossible to understand if it gets out of sync.


问:
Models structure in PHP/MVC
I have some classes that are composed with ORM generated Models.

example1:
For example the Report.php (Model) is using a Document.php Model generated with ORM. Based on the document object a report is created.

I would like to know some name suggestions for the Report.php folder path.
It clearly belongs to the /Model folder but in what subfolder?

example2:
The CustomTagFilter.php will remove some html tags from a html string.

I wish to find a clear path name for this kind of Models. Any suggestions ?

```<code>/Models/[SUGGESTION]
</code>```

答:
ORMs are working with Entites, which are basically the instances of the model classes (in your case Document.php), so calling your folder Entities would be logical.

To get a proper definition of Entity, dive into the documentation of the ORM you are using. (Here is an example from the documentation of Doctrine.)

Title: Models structure in PHP/MVC


答:
If you need help with keeping up your self-confidence, you probably need to talk with a personal councillor about that.

But it sounds like the problem here is that your project / team is in a dangerously disfunctional state.  You / your team should be using on or more of the standard approaches to keeping code quality high and bug counts low:

Use code reviews, code inspections or peer-programming to get "two sets of eyes" on the problem.

Build unit and system test suites, and run them on a CI server.

Use automated bug detectors and source code analysers to pick up common bug types.

Use a bug tracker.

Use a coding standard.

Use code quality and test coverage metrics (intelligently ...)

And so on.

If you keep on top of the number of bugs, you can be confident ... AND produce a good product.

Of course these things all take time and resources (people).  But your management should be providing these ... or risk ending up with a codebase that is unreliable and unmaintainable with nobody left standing to work on it.

If you are stuck in a disfunctional project / team and it is seriously affecting you, you should consider making a move.  Not all projects and not all organizations are like that.  But maybe the flipside is that you need to learn to not take it personally when things go badly through no fault of your own.

Title: How do you keep consistent self confidence while coding?

Body: As the number of bugs in a codebase increases, that number not only decreases the quality of the code, it also affects the mindset of the developers.  Developer self-confidence falls when things are not going well.  If self-confidence is not right, things more easily become a mess.  How do you guys keep your self confidence up in these situations?</p>


答:
Fix the bugs?

Seriously, all developers make bugs. They're not a sign that things aren't going well, they're a natural part of software development. Go fix them and stop being so emo.


答:
As a junior developer, you are not in a good position to make a difference about the effectiveness of your team's code reviews.  That's really for the leader(s) in the team.

My two cents is that it is the outcome that matters about the code review, not the process.  Reviews that don't result in substantially better design and code are a waste of time.  Structure can help.  But it also can hinder if it inhibits the team from addressing the real problems.

So ...

1) Should code review comments be limited to actual problems with the code?

It is hard to draw a line.  It also depends on whether this just a code review, or also mentoring.

2) Are criticisms about other LOC in the file appropriate even if those lines are not being modified? i.e., criticism of pre-existing code?

It depends.  If there is a need to improve the pre-existing code, and the possibility of doing it in the context of the work being done, it could be useful to talk about.

3) What about suggestions of different ways to solve the same problem? Should I suggest a new way only when a case can be made for it being better?

If 1) the alternative way would give a significantly better outcome, 2) it would be practical to implement it now, and 3) the person who would do that work is likely to be receptive, then it could be appropriate.

How do I draw the line between contributing ideas but not sounding like a know-it-all?

Use your common sense, and be sensitive to other peoples' reactions.

4) In matters which are purely a difference of opinion, who should get the 'final say'? The author, the person who knows the code base the best, the person with the highest title or someone else?

That is for the team / management to decide.

5) Any other advice for ensuring the code reviews serve their purpose without unnecessarily blocking the developer's progress?

If code reviews are obstructing progress, you need to discuss this with your project leader.  The team leader carries the can for project delays and  quality issues.


问:
Is there a better way to model a many-to-many relationship on the same table with Entity Framework?

The context

We're building a web application using Entity Framework 5.0. One of the requirements is that it should be possible for the administrators to link related products so that when someone browses to a product we can render a list "You might also like these products:".

Since a product can be linked to many products we need a many-to-many relationship for this.

The table in the database could look something like this:

```<code> _________________________
| LinkedProducts          |
|-------------------------|
| ProductId1 | ProductId2 |
|------------|------------|
|     1      |     2      |
|------------|------------|
|     1      |     3      |
|------------|------------|
|     2      |     4      |
|------------|------------|
</code>```

An additional requirement is that the linking should be bidirectional. This means that with the sample data from the table above, when you browse to product 2, you should get product 1 and 4 in the list. So for a given ProductId, you should be able to get its linked products from column ProductId1 and ProductId2.

What I've come up with

The product entity:

```<code>public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> References { get; set; }
    public virtual ICollection<Product> ReferencedBy { get; set; }

    public Product()
    {
        References = new List<Product>();
        ReferencedBy = new List<Product>();
    }
}
</code>```

The product mapping:

```<code>public class ProductMapping : EntityTypeConfiguration<Product>
{
    public ProductMapping()
    {
        HasKey(t => t.ProductId);

        Property(t => t.Name).IsRequired().HasMaxLength(150);

        ToTable("Products");
        Property(t => t.ProductId).HasColumnName("ProductId");
        Property(t => t.Name).HasColumnName("Name");

        HasMany(x => x.References).WithMany(x => x.ReferencedBy).Map(map =>
            {
                map.ToTable("LinkedProducts");
                map.MapLeftKey("ProductId1");
                map.MapRightKey("ProductId2");
            });
    }
}
</code>```

This all works. To display the list of linked products for a certain product, I can just get the union of References and ReferencedBy:

```<code>var product = db.Find(2);
var linkedProducts = product.References.Union(product.ReferencedBy);
</code>```

The problem

As I said, this works, but I don't really like it and I was wondering if there is a better way to deal with a situation like this when working with Entity Framework.

The solution

I liked Ryathal's suggestion to add two records to the database when linking products. So, when linking product 1 to product 2, I now insert two records: { 1, 2 } and { 2, 1 }.

This also allows me to remove the ReferencedBy collection in the Product class so that only one collections remains: References.

To link to products:

```<code>product1.References.Add(product2);
product2.References.Add(product1);
</code>```

To remove the link between products:

```<code>product1.References.Remove(product2);
product2.References.Remove(product1);
</code>```

Here is my new Product class with the mapping:

```<code>public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> References { get; set; }

    public Product()
    {
        References = new List<Product>();
    }
}
</code>```

The product mapping:

```<code>public class ProductMapping : EntityTypeConfiguration<Product>
{
    public ProductMapping()
    {
        HasKey(t => t.ProductId);

        Property(t => t.Name).IsRequired().HasMaxLength(150);

        ToTable("Products");
        Property(t => t.ProductId).HasColumnName("ProductId");
        Property(t => t.Name).HasColumnName("Name");

        HasMany(x => x.References).WithMany().Map(map =>
            {
                map.ToTable("LinkedProducts");
                map.MapLeftKey("ProductId1");
                map.MapRightKey("ProductId2");
            });
    }
}
</code>```

答: Follow good database design and your problems will start getting easier, don't think about entity framework when designing your database structures. Create your Product table and create you related product table with source product and related product ids. The requirement for linking to be bi directional is just a business rule to be handled with the application on creating related products to always insert two rows into your mapping table. Everything stays nice and simple this way.</p>


问:
Byte code weaving vs Lisp macros
I have been reading about the libraries people have written for languages like Java and C# that make use of byte code weaving to do things like intercept function calls, insert logging code, etc. I have also been reading up on Lisp/Clojure macros in an attempt to better understand how to utilize them. The more I read about macros, the more it seems like they provide the same kind of functionality as byte code weaving libraries. By functionality, I mean the ability to manipulate code at compile time.

Examples of libraries I have been looking at would be AspectJ, PostSharp, and Cecil.

Is there anything that can be done with one and not the other? Do they actually solve the same problems or am I comparing apples and oranges?

答:
Lisp macros are operating at the source code level. If you wrap some macro around a piece of code, then you can do a lot of things. Including parsing the source code, inserting code, rewriting code, etc.

If you want to modify function calls, Lisp usually uses two mechanisms:

late binding symbols. You can modify the function bound to a symbol. Every function calling which goes through a symbol, then uses the new function.

Lisp implementations sometimes provide a feature called 'advice'. This allows to execute code before, after or around calls. For example in LispWorks: Advice.

Thus you can intercept calls without low-level code manipulation.

Title: Byte code weaving vs Lisp macros


问:
Architecture suggestions on a multi-project multi-database 'intranet'
Here is the situation I have inherited:

We have approximately 10 websites (Asp.net web forms) that each have their own database.

Each of these databases houses some site specific data, and each has some form of a user table that will map to what is called a User Service.

The User Service is just another website that has a database with one table (User) that have about 3 different unique identifiers for a user: a UserId guid, an internal desktop application id (third party app, needed to map back to it), and a username.

On all the different websites the databases have the User table, sometimes called Person, or Student, or whatever else, and they are inconsistent in which UserService.User.[IdentifyingColumn] they map to.

The Problem:

It is getting to a point where these application are now needing to share some data with each other, and I see that need increasing as the departments are streamlined even more.      With this current set up, it is a lot of hoop jumping to get the right UserId column to match to the right UserId column in the UserService.

Confused yet? Me too..

The Question:

How to approach correcting the issue? I have a few different ideas, some I like more than others, but in order to implement them I need some solid benefits I can bring up to the head of IT, as well as justify the programming time taken for the re-write.

Idea 1: Create a true intranet application. One web application with one database. This way they all live in the same project, and sharing data between the various departments is very simple and quick.

Idea 2: Create a "Master Key" identifying field that will be the end all to identify a user. Make this key available on each database and so there will not be any odd mapping and the various sites can talk to each other. To me this one solves one problem, mapping each db to the next one. It is still very fragmented and there is very little code re-use.

Idea 3: Work with it in the current form trying to continue the present fashion of many small databases and sites.

Which of the above options would you suggest, and why?

答:
I believe you are using old RDBMS Database(like sql 2008)

i would suggest you to go for ORDBMS(Oracle 10g or 111g) which can work more efficiently specially for these types of large amount of data using single instance for multiple database that can share data across.

You can share other table data using *Object_User.table_name* in your own Table all those database would share one instance (connection) as a single SID service.

This way You can connect with any dataabse using a single connection.
for further research visit =

Oracle website
Oracle website for multiple database
or reply for further discussion....


问:
What are some current opinions on WPF?
We are trying to make a decision about if we should create a program in WPF w/ a WCF server, and I was wondering what the current opinions are of WPF. I was looking around online but most of the arguments I saw for/against WPF were dated a year or two ago, and about WPF3.5. I was wondering if those opinions have changed in the past year or two with the release of WPF4.0.

Some notes....

The program we are making is for use by a single-company in a controlled enviornment. With the exception of one or two Vista laptops, most users are on Terminal Servers or WindowsXP. It is not media-heavy and doesn't need a pretty UI (although it won't hurt). It needs to be extensible and allow for easy additions later on. Security and Performance are our key concerns.

EDIT

Primary concern about WPF is Support (MS and community), memory/cpu usage on terminal servers, and finding people to work on the project now and maintain it in the future. Some smaller things of concern are lack of library controls, development time, and learning curve.

The primary alternative we were considering is ASP.Net/jQuery.

答:
I too like WPF but I know I had some issues with Windows XP when I first started using it (albiet it may have been my fault). WPF was originally developed for use with Vista (and then Windows 7) so it originally didn't work on XP. There is a blog post about this on MSDN (http://blogs.msdn.com/b/tims/archive/2007/01/05/comparing-wpf-on-windows-vista-v-windows-xp.aspx) and while it is old it outlines some of the issues that may exist when using XP.

For what you are doing, it may be fine but if you end up needing something media intensive I wouldn't use it as performance may take a hit per the blog above.

Title: What are some current opinions on WPF?


答: Just use breath first search (no need for Dijkstra's alg. because all edges have uniform length) (and as Kris Van Bael said, run it from both sides)</p>

Title: What algorithm should I use to find the shortest path in this graph?

Body:
I have a graph with about a billion vertices, each of which is connected to about 100 other vertices at random.

I want to find the length of the shortest path between two points. I don't care about the actual path used.

Notes:

Sometimes edges will be severed or added. This happens about 500 times less often than lookups. It's also ok to batch up edge-changes if it lets you get better performance.

I can pre-process the graph.

If it takes more than 6 steps, you can just come back with infinity.

It's acceptable to be wrong 0.01% of the time, but only in returning a length that's too long.

All edges have a length of 1.

All edges are bidirectional.

I'm looking for an algorithm. Psuedocode, english descriptions, and actual code are all great.

I could use A*, but that seems optimized for pathfinding.

I thought about using Dijkstra's algorithm, but it has a step which requires setting the shortest-path-found attribute of every vertice to infinity

(If you're wondering about the use-case, it's for the Underhanded C Contest.)


答: "All edges have a length of 1" This is a best-case scenario making Dijkstra's Algorithm a perfect greedy algorithm choice.  Even using the Floyd-Warshall algorithm involving fast matrix multiplication would work well.


问:
Querystring Advanced Search where there are about 20 search fields
I am creating an advanced search page where there are about 20 search fields for a user to filter their search. My question deals with the query string, Is it standard web development practice to have say 20 parameters in a querystring?

The search results display large tables of data. Is there an alternative that still uses HTTP GET(querystring), if it is not standard? I would like the users to be able to bookmark their searches.

答:
It does seem a little odd to have so many items, I would have suggested using a post and putting the content in the data sent.

You however said you want to be able to bookmark the results page so I think you need to keep it in the query string as you're doing. Do consider however that the query string has a max length in most browsers, e.g. IE is limited to 2048 characters, which might be a problem. See - https://stackoverflow.com/questions/812925/what-is-the-maximum-possible-length-of-a-query-string


问:
Going about increasing salary during performance review
I'm currently facing a dilemma with an upcoming performance review.  When I started with my company around 1 year ago I tried to be as honest as possible in my perception of my programming skill set and knowledge.  I based my perceived skills on my coding ability relative to those I consider to be good programmers and developers.  So the salary I was provided I was happy with at the time.

I have no problem with that as I believe honesty is important when going for a job and while in it.  Also, I believe that once I'm in the job if I'm better than what I have given the employer to believe then my performance will reflect that.

At the same another developer was hired.  We were both hired to work on the same project doing the same task set.  A few months back I found out that this person was on substantially more than me wage wise.  Now during the project I have come to realise that this person is well below me in programming skills and even business knowledge.  I have had to help him out numerous times with programming tasks, review his code and offer better solutions, and explain concepts about the project we are working on. Even though we both started at the same time.

How can I go about increasing my salary (during the review) to be at least comparable with this person without directly mentioning their name or that I know what they are on.  If I justify it based on the work I have done, what if they don't offer me a comparative package.  Is it fair that I want more or am I being greedy?

答:
Here is a suggestion. Most employers utilize performance evaluations, merit-based recognition systems.  You could incorporate into your SMART objectives one or two, at most, specific areas in which you are focusing that enable to you demonstrate stated objective fulfillment.

Supervision and management love to see plain and clear objectives and nothing speaks volumes about an employee who satisfies those objectives. One such objective could be mentoring of new employees or giving assistance.  Utilize your employer's means of evaluating you as one method to increase salary.

What I would not do is compare salaries with employees or concern yourself with who has more merit.  You are an individual at the review table so ensure your individuality is enhanced and highlighted through your employer's means.

Wanting more is human but wanting too much or thinking you deserve it is another thing entirely.  Focus on demonstrated performance and keep that the focus on any performance review.  Remember, you can be replaced so you don't want to be obnoxious or place yourself into a position in which your management deem you more trouble than you are currently worth.


答:
In the software world, we deal with certainties and statistically impossible scenarios before deciding to use a given solution. Whether the packets can/will arrive reliably and what you plan on doing to handle that contingency, has everything to do with whether or not you should use that solution. </p>

<p>Anyways, no they will not arrive in order (or at all) and if you use it, you have to deal with it in your transport layer(s)--like the way RTP does it or something of that nature. </p>

Body:
In the software world, we deal with certainties and statistically impossible scenarios before deciding to use a given solution. Whether the packets can/will arrive reliably and what you plan on doing to handle that contingency, has everything to do with whether or not you should use that solution.

Anyways, no they will not arrive in order (or at all) and if you use it, you have to deal with it in your transport layer(s)--like the way RTP does it or something of that nature.


答:
As explained in a related SO question, there's technically no limit to the length of a URI, however IE 8 and below only supports up to 2083 characters, so if there's a possibility that your search page could generate a URL longer than that, you should implement bookmarking another way.

This page has some suggestions for how to work around the practical URL length limit while still allowing bookmarking:

If your field names take up too much space, use a fixed field order instead

Squeeze out any field that doesn't really need to be bookmarked

[A]void large decimal numbers - use only as much accuracy as you must, and consider a base-64 representation using letters and digits

In extreme cases, consider using the gzip algorithm to compress your pretty but excessively long URL. Then reencode that binary data
  in base64 using only characters that are legal in URLs

An alternative is to store the state information in a file or a database. Then you can store only the identifier needed to look up
  that information again in the URL

Title: Querystring Advanced Search where there are about 20 search fields

Body:
I am creating an advanced search page where there are about 20 search fields for a user to filter their search. My question deals with the query string, Is it standard web development practice to have say 20 parameters in a querystring?

The search results display large tables of data. Is there an alternative that still uses HTTP GET(querystring), if it is not standard? I would like the users to be able to bookmark their searches.