答:
In general, RPC offers far more of a language integration than REST. As you mentioned, this comes with a number of problems in terms of scale, error handling, type safety, etc., especially when a single distributed system involves multiple hosts running code written in multiple languages. However, after having written business systems that use RPC, REST, and even both simultaneously, I've found that there are some good reasons to choose RPC over REST in certain cases.

Here's the cases where I've found RPC to be a better fit:

Tight coupling. The (distributed) components of the system are designed to work together, and changing one will likely impact all of the others. It is unlikely that the components will have to be adapted to communicate with other systems in the future.

Reliable communication. The components will communicate with each other either entirely on the same host or on a network that is unlikely to experience latency issues, packet loss, etc.. (This still means you need to design your system to handle these cases, however.)

Uniform language. All (or mostly all) components will be written in a single language. It is unlikely that additional components written in a different language will be added in the future.

Regarding the point about IDL, in a REST system you also have to write code that converts the data in the REST requests and responses to whatever internal data representation you are using. IDL sources (with good comments) can also serve as documentation of the interface, which has to be written and maintained separately for a REST API.

The above three items often occur when you are looking to build one component of a larger system. In my experience, these components are often ones where their subsystems need to be able to fail independently and not cause the total failure of other subsystems or the entire component. Many systems are written in Erlang to accomplish these goals as well, and in some cases Erlang may be a better choice than writing a system in another language and using RPC just to gain these benefits.

Like most engineering problems, there isn't a single solution to the problem of inter-process communication. You need to look at the system you are designing and make the best choice for your use case.

Title: When are RPC-ish approaches more appropriate than REST?

Body:
After watching this talk on REST, Reuse and Serendipity by Steve Vinoski, I wonder if there are business cases in greenfield projects for (XML-)RPC-ish setups, that REST could not solve in a better way.

A few RPC-Problems he mentions:

Focus on language (fit the distributed system to the language, not the other way around)

"Make it look local" (and cope with failure and latency as exceptions rather than the rule)

intended to be language-independent, but still has "function calls"  across languages as main ingredient

IDL boilerplate

Illusion of type safety

and a few more ...

Just to dramatize it a bit, some Google Instant results for RPC vs REST:


问:
Is online freelance work viable by American standards?
I've always been curious about trying out online freelance sites... it would be nice to work from home, feel independent, get to choose what I want to work on, get to work on different technologies, lose the PHB, etc.

However I never really gave them a chance because I'm used to American rates and assumed that I would be competing with people from India, Russia, China, etc. that would severely undercut me, and it wouldn't be viable for me.

Am I correct in this assumption or should I give it a shot?  What kind of hourly rate would I be able to expect on short-term programming work?

答: I just started doing freelance work (in order to build a portfolio) and I have noticed that many of the tech freelance sites (Project4Hire, Elance, etc.) have rates that are sub-(American)standard because of the bids from places like India and Pakistan. The one site that I have noticed that offers decent wages and definitely local work is Craigslist. I always keep an eye on the "Computer Gigs" in my area and it seems that the majority of the time people are looking for local freelancers so that they can actually meet face to face. While it is more hit or miss (projects range from "real" projects to helping somebody with their homework) I have seen more local stuff that would allow you for better wages. </p>

ContentLicense: CC BY-SA 2.5


问:
What is proper etiquette and recommended GitHub workflow for simultaneously contributing to and diverging from upstream repo?
I'm new to GitHub and VCS in general. I've been programming in various languages for years, but I've always worked solo on custom projects (no public releases). I recently started using a jQuery UI widget I downloaded from GitHub in a project I am working on. The repo is no longer maintained by the original author. Another fork has incorporated some of the original pull requests. This is the one I forked from.

I found a couple of bugs and have come up with the fixes for them. I'd like to contribute these fixes, but I also have a whole lot of other changes I want to make, for our own use, that will break some of the existing features. Plus, I'd like to incorporate an idea from another fork.

I'm still learning GIT and GitHub and I'm trying to figure out the best way to go about everything. I've done a lot of reading (here, SO, GitHub help pages, Pro Git) about different concepts/tasks: workflows, merging, pull requests, cherry picking, rebasing, branching. My grey matter is swimming and I need to start doing so I can better understand what I've read.

Main Issues:

I think I read (somewhere) that you can only have one pull request on a branch at a time. So does that mean I should have a separate branch for each bug and then do a separate pull request for each one?

I want to clean up whitespace issues and I seem to remember reading that it's best to do this in a separate commit. Should I do this in my master or a separate branch? I don't want to do a pull request for something so trivial, but if I make whitespace changes before branching, will that affect the pull request for the bug fixes? Some forks did whitespace cleanup and it effectively made the diff pretty useless.

I was thinking of creating issues against my fork as a way of documenting the bugs even though I already have the fix for them. Is that a good idea? How do I go about linking together the issue, the commit, and the merge to master? If I do a pull request upstream, will my issue appear upstream as well or will that documentation link be lost? I can't open an issue against the upstream repo (there is no issue tab).

What's the best way to give credit to the other fork author for the idea of his that I want to use? I can't use his code exactly, especially since his change is applied against an older version of the upstream and is not compatible with my other changes as is. But I want to use the idea and I want to give credit where credit is due. Should I just link to his repo (or profile or specific commit) in my commit message?

What is the etiquette regarding changing the readme file and the DocBlock at the top of the main file? Is it ok to make changes, add my name, add links to my repo and demo, remove links to the original demo (since my fork will end up being incompatible with the original)? Of course, I will leave the original author name and license information. For the record, it's licensed under the MIT license.

As a solo developer who's never used VCS, I am accustomed to rewriting history. I'm a perfectionist and like things to be neat and tidy. The idea of recorded history is making me a little nervous and I want to do it right the first time. I've created a new repo to play/learn with, but I am anxious to get moving on fixing up the jQuery UI widget so I can move on with my project.

答:
Correct: a pull-request is linked to a branch in your repository. If you modify the branch, you are then also modifying what you're submitting as a pull-request.

So yes, you do have to create a branch (and pull-request) per bug fix. It might be wise to start with one and see how the maintainer reacts to that one before going on to do the rest. Open source is an inherently social process.

Do make a pull-request for your whitespace changes! Speaking as someone who's sometimes a maintainer, I love these types of pull-requests: I either approve them or don't, and they take little time to process.

What you also might run into is that the maintainer does not agree with your whitespace changes! So, beware..

Hmm.. It's not clear what you're trying to achieve here. It sounds like over-documentation and not that good of an idea -- maybe you can clarify why you would want to do this?

Linking to his repo in your commit message (or even in a comment in the code) is a great way to give credit. Be careful though -- make explicit that you are thanking him for his ideas and not for his code. If you have copied code, then I would e-mail him about it, unless it's very clear which license he's using for his code. If the licensing is clear (and it's a different license from the repository you're submitting the commit to) then you need to add the different license in your pull-request and also mention that in your pull-request message.

This is a really good question and differs depending on who you talk to. My opinion is that you should never add your name to any commit or code you do. The main reason is that it implies "ownership of and responsibility for the code" -- it might prevent others from modifying the code because "it's yours". But now we're getting into a huge discussion about the nature of open source, so I'll stop here and say -- ask the project maintainer or just do it and see what his reaction his.

You can rewrite (your local, not-yet-published) history with GIT! Learn the git rebase command -- this is one the main reasons that I love git. It's a really bad idea to (force) push rewritten commits/history to the shared repository (github, for example). This will then screw with the repositories that the other developers have -- they will have to do difficult things when pulling your (rewritten history) changes.

[#6: Thanks @toxalot!]

ContentLicense: CC BY-SA 3.0


问:
Constructing a Deterministic Finite State Automaton for a given Regex
I have a couple of exam questions for my compilers class and wanted to check if my solutions are correct.

The first question is:

Consider a language in which numbers start with an optional minus
  sign, followed by one or more decimal digits, followed by an optional
  decimal point. If the number contains a decimal point it is followed
  by one or more further decimal digits. Express the syntax of numbers
  in this language as a regular expression.

And for my answer:

("-")? ["0"-"9"]+ ("."["0"-"9"]+)?

The second question is:

Construct a deterministic ﬁnite state automaton for recognising the
  numbers as described in Question 1

And my answer is:

Where state 2,4,5 and 6 are terminals.

Are these solutions correct? I am unsure of what the DFA should look like and it's differences to an NFA.

Thanks !

答:
No, your deterministic finite automaton is incorrect. Your regular expression is.

The problem in your DFA is the declaration of 5 and 6 to be terminal nodes. A testcase such as "0." will be accepted by your DFA even though it should not.

Optional values

I want to point out how you can model a general structure which includes optional values. Let's take for example a regular expression like "a?b". The idea now is to create two branches. One includes the optional element "a" and the other one excludes it. The inclusion branch merges with the other one with the first value that is obligatory again.

One time or more

As a second idea: How do we model quantities such as "once or more times"? We have to create an edge which requires us to read the symbol "a" one time. After that we create a self-loop which reads the symbol as many times as necessary (possibly zero).

Applying those ideas to your Deterministic Finite Automaton, we get the following:

Non-deterministic Finite Automatons

An automaton becomes non-deterministic if there are two edges with the same label starting at the same vertex. In the example below starting with vertex "4" and reading the input "0", you won't know which path will accept the input string (left or down) and will proceed non-deterministically.


问:
I've been told HTML is a markup language, C++ is a programming language, what could make that difference?
My programming friends are always telling me that HTML is a markup language and C++ is a programming language. When I ask them what's the difference, they never give me a reasonable answer.

What could make one call C++ a programming language, and HTML not?

答:
HTML is a declarative language. It doesn't do much on its own, it just describes a document and its content (using tags that have a semantic meaning).

C++ on the other hand does something. It does define functions and classes, but it also describes how these functions should work together, how their inputs and outputs are tied together in a meaningful way and how the application should run as a whole.


问:
Showing a grammar is ambiguous
I have the following question taken from a compilers course exam:

```<code>Show that the following grammar is ambiguous.

S = XcY
X = a
Y = b | Z
Z = bW
W = d | ϵ
</code>```

I drew the following tree:

Am I correct in thinking it is ambiguous because acY can end up at acb (one of which is followed by an epslion) following different paths?

答: Yes. Since epsilon means you can rewrite W as the empty string, acbW -> acb. As you have shown, there are two leftmost derivations for the string acb, which by definition means the grammar is ambiguous.</p>

Title: Showing a grammar is ambiguous


问:
Why is using classic for loops as iterators in stl considered bad?
I've read a couple of articles (example) that consider the classic

for (int ...... size() .... i++) loop bad practice when iterating through for example vectors in stl.  Instead the recommended why is to use vector iterators, i.e. begin, end, etc.

Why is that?

答:
Most of the time, both are about equally bad practice.

What you should normally try to do is figure out what the loop accomplishes, and either use an existing algorithm or else write a new algorithm to accomplish that end generically, then apply that algorithm to the collection/range at hand.

Just for example, let's assume you were adding up the items in a vector:

```<code>int total = 0;

for (int i=0; i<v.size(); i++)
    total += v[i];

std::cout << "Total = " << total << "\n";
</code>```

Rewriting this to use iterators is essentially no improvement (and arguably detrimental):

```<code>int total = 0;

for (std::vector<int>::iterator p = v.begin(); p!= v.end(); ++p)
    total += *p;

std::cout << "Total = " << total << "\n";
</code>```

Using C++11, you can at least restore a little sanity:

```<code>int total = 0;

for (auto p : v)
    total += p;

std:cout << "Total = " << total << "\n";
</code>```

...but you don't even need C++11 to to the job quite a bit better still:

```<code>std::cout << "Total = "
          << std::accumulate(v.begin(), v.end(), 0)
          << "\n";
</code>```

When you find yourself thinking about writing a loop, changing the loop to use an iterator is rarely the right answer -- the right answer is usually to eliminate the loop and replace it with an algorithm instead.

Body:
Most of the time, both are about equally bad practice.

What you should normally try to do is figure out what the loop accomplishes, and either use an existing algorithm or else write a new algorithm to accomplish that end generically, then apply that algorithm to the collection/range at hand.

Just for example, let's assume you were adding up the items in a vector:

int total = 0;

for (int i=0; i<v.size(); i++)
    total += v[i];

std::cout << "Total = " << total << "\n";

Rewriting this to use iterators is essentially no improvement (and arguably detrimental):

int total = 0;

for (std::vector<int>::iterator p = v.begin(); p!= v.end(); ++p)
    total += *p;

std::cout << "Total = " << total << "\n";

Using C++11, you can at least restore a little sanity:

int total = 0;

for (auto p : v)
    total += p;

std:cout << "Total = " << total << "\n";

...but you don't even need C++11 to to the job quite a bit better still:

std::cout << "Total = "
          << std::accumulate(v.begin(), v.end(), 0)
          << "\n";

When you find yourself thinking about writing a loop, changing the loop to use an iterator is rarely the right answer -- the right answer is usually to eliminate the loop and replace it with an algorithm instead.


问:
Alternatives to the repository pattern for encapsulating ORM logic?
I've just had to switch out an ORM and it was a relatively daunting task, because the query logic was leaking everywhere. If i'd ever had to develop a new application, my personal preference would be to encapsulate all query logic (using an ORM) to futureproof it for change. Repository pattern is quite troublesome to code and maintain so i was wondering if there are any other patterns to solve the problem ?

I can foresee posts about not adding extra complexity before it's actually needed, being agile etc. but i'm only interested about the existing patterns solving a similar problem in a simpler way.

My first thought was to have a generic type repository, to which i add methods as needed to specific type repository classes via extension methods, but unit testing static methods is awfully painful. IE:

```<code>public static class PersonExtensions
{
    public static IEnumerable<Person> GetRetiredPeople(this IRepository<Person> personRep)
    {
        // logic
    }
}
</code>```

答:
Consider making your extensions operate on IQueryable instead of IRepository.

```<code>public static class PersonExtensions
{
    public static IQueryable<Person> AreRetired(this IQueryable<Person> people)
    {
        return people.Where(p => p.Status == "Retired");
    }
}
</code>```

To unit test:

```<code>List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Bob", Status = "Retired" });
people.Add(new Person() { Name = "Sam", Status = "Working" });

var retiredPeople = people.AsQueryable().AreRetired();
// assert that Bob is in the list
// assert that Sam is not in the list
</code>```

No fancing mocking required for testing.
You can also combine these extension methods to create more complex queries as needed.

Body:
Consider making your extensions operate on IQueryable instead of IRepository.

public static class PersonExtensions
{
    public static IQueryable<Person> AreRetired(this IQueryable<Person> people)
    {
        return people.Where(p => p.Status == "Retired");
    }
}

To unit test:

List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Bob", Status = "Retired" });
people.Add(new Person() { Name = "Sam", Status = "Working" });

var retiredPeople = people.AsQueryable().AreRetired();
// assert that Bob is in the list
// assert that Sam is not in the list

No fancing mocking required for testing.
You can also combine these extension methods to create more complex queries as needed.


问:
When forking an dual-licensed permissive/GPL project, can I drop one of the licenses?
Consider an existing project that is dual-licensed GPL + either MIT or BSD.

Since it's dual-licensed, when I fork, can I pick one license in the fork? Or do my forked files need to continue to be dual-licensed?

It sure would be simpler to track only one license.

答:
Note, I am not a lawyer.

When a project is dual-licensed it means that you can choose to license the work from the author under either one of the licenses. You are only bound by the one you pick—that is the whole point of dual licensing (though I don't understand the point of dual-licensing under the GPL and a permissive license). The original code may still be distributed under both licenses by the author, but there is no requirement for you to do such a thing.


问:
How do people define the minimum hardware requirements for software?
How do people define the minimum hardware requirements for software? For example: how can a software development company tell the customer that they will need 8 GB of RAM to run the program properly?</p>

答:
Hardware requirements fall into a couple of different buckets.  Often you'll include requirements from a few of these buckets when determining specific hardware requirements for any software system you build.

Technical Constraints in the Architecture

These are the kinds of requirements that absolutely must be satisfied by the built system and are specifically designed into the system from the start.  For example, "x86 processor is required."

An easy example that comes to mind is Microsoft Office for Mac.  Originally Macs used Power PC CPUs while Microsoft Windows was strictly targeted at "IBM Compatible" machines (mostly using x86 processors).  Because Windows and thus Office only worked on x86, a completely new set of code (with different technical constraints) was written to support Office on Power PC for Mac OS.  Once Mac moved to Intel x86 processors, the old Power PC optimized Office for Mac no longer worked -- and technical constraints once again changed for a new version of Office for Mac on Intel.  Applications optimized for 32 vs. 64 bit is another easy example.

Implicit Hardware Requirements

Sometimes you don't actively choose to constrain yourself, but other decisions you make implicitly force requirements on to you.  A common scenario is building on top of any kind of framework.

As an example, if you are building a .Net 4.0 application, .Net 4.0 has hardware requirements vetted through Microsoft's hardware labs.  Now your application requires at least the same hardware requirements that the .Net 4.0 framework requires.

Contextual Hardware Requirements

Most of the time when you're talking about hardware requirements what you are really talking about is how you support specific quality attribute scenarios.  Things like performance, reliability, availability, and other -ilities.

This is something I deal with often in making hardware recommendations for customers building applications on top of IBM InfoSphere Data Explorer (basically a Big Data search engine platform).  Data Explorer's basic requirements are minimal (you can run it on a laptop), but hardware recommendations for any specific Big Data application (read: requirements) comes down to specific quality attribute scenarios for that application.  How quickly should data be indexed?  How many queries per second should be processed?  How much down time is acceptable?

Identifying specific quality attribute scenarios draws a line in the sand and lets me make a recommendation for minimum hardware requirements based on those scenarios -- X number of CPUs with Y amount of RAM, Z Gigabytes of hard drives, N redundant systems.  In our case, we have basic formulas (determined through extensive testing in our hardware labs) that use assumptions from the quality attribute scenarios to help determine a starting point for a hardware recommendation.  This recommendation becomes the requirement for that specific Big Data application.

In this example, for any production system, a laptop really won't do even though it technically meets the "minimum" requirements.  The context of that implementation -- the specific scenarios and data, whether it's running in production or not, and so on, dictate the hardware requirements.

If the assumptions in the scenarios change, then so will the hardware requirements.  So the phrase, "Y GB RAM is required to run the software properly," really means "Y GB of RAM is needed to crawl X million documents in Z hours or a rate of ABC docs/min."

Minimum Supported Hardware Requirements

That is, the hardware specifications expected to work correctly and that your Support group is prepared to help troubleshoot.  Generally this is the set of hardware to which you have direct access, either your development machine or through a testing lab of some kind.

One example of this is pretty much any Android app that has been released.  As an Android developer you test your app through some software simulators, probably on at least a few physical devices.  But there are 1000s of different devices running Android, many of which with little... quirks ...that could cause your app to run into problems.  In most cases, you'll still offer support if a user runs into problems.  And in most cases users won't run into problems even though you didn't specifically test on that hardware variation.  Microsoft has this problem too with Windows -- how many different video card, motherboard, cpu, memory combinations are out there?

Basically, identifying minimum supported hardware is like saying "this software works on my machine, I expect that it will work on machines similar to mine, lots of folks have used this software on lots of different machines without problems, your mileage may vary, and if you have a problem I'll do my best to help/fix but I can make no guarantees."


问:
WCF hardware requirement
I read the hardware requirements of WCF in a book and two of them are the following ones:

A DVD-ROM drive

A 1024 × 768 or higher resolution display with 256 colors or more

Why is there a requirement for the screen resolution, or to have a DVD drive?

Perhaps, this requirement is necessary for Visual Studio to work. Am I wrong?

答: These are probably the requirements to use the software (such as samples) included on the DVD with the book or if WCF was ever to be distributed on DVD. It is also likely to be a copy and paste error.</p>

Title: WCF hardware requirement


问:
Why aren't user-defined operators more common?
One feature I miss in from functional languages is the idea that operators are just functions, so adding a custom operator is often as simple as adding a function. Many procedural languages allow operator overloads, so in some sense operators are still functions (this is very true in D where the operator is passed as a string in a template parameter).

It seems that where operator overloading is allowed, it is often trivial to add additional, custom operators. I found this blog post, which argues that custom operators don't work nicely with infix notation because of precedence rules, but the author gives several solutions to this problem.

I looked around and couldn't find any procedural languages that support custom operators in the language. There are hacks (such as macros in C++), but that's hardly the same as language support.

Since this feature is pretty trivial to implement, why isn't it more common?

I understand that it can lead to some ugly code, but that hasn't stopped language designers in the past from adding useful features that can be easily abused (macros, ternary operator, unsafe pointers).

Actual use cases:

Implement missing operators (e.g. Lua doesn't have bitwise operators)

Mimic D's ~ (array concatenation)

DSLs

Use | as Unix pipe-style syntax sugar (using coroutines/generators)

I'm also interested in languages that do allow custom operators, but I'm more interested in why it has been excluded. I thought about forking a scripting language to add user-defined operators, but stopped myself when I realized that I haven't seen it anywhere, so there's probably a good reason why language designers smarter than me haven't allowed it.

答:
I can think of a few reasons:

They aren't trivial to implement - allowing arbitrary custom operators can make your compiler much more complex, especially if you allow user-defined precedence, fixity and arity rules. If simplicity is a virtue, then operator overloading is taking you away from good language design.

They get abused - mostly by coders who think it is "cool" to redefine operators and start redefining them for all sorts of custom classes. Before long, your code is littered with a load of customised symbols that nobody else can read or understand because the operators don't follow the conventional well-understood rules. I don't buy the "DSL" argument, unless your DSL happens to be a subset of mathematics :-)

They hurt readability and maintainability - if operators are regularly overridden, it can become hard to spot when this facility is being used, and coders are forced to continually ask themselves what an operator is doing. It is much better to give meaningful function names. Typing a few extra character is cheap, long term maintenance problems are expensive.

They can break implicit performance expectations. For example, I'd normally expect lookup of an element in an array to be O(1). But with operator overloading, someobject[i] could easily be an O(n) operation depending on the implementation of the indexing operator.

In reality, there are very few cases where operator overloading has justifiable uses compared to just using regular functions. A legitimate example might be designing a complex number class for use by mathematicians, who understand the well-understood ways that mathematical operators are defined for complex numbers. But this really isn't a very common case.

Some interesting cases to consider:

Lisps: in general don't distinguish at all between operators and functions - + is just a regular function. You can define functions however you like (typically there is a way of defining them in separate namespaces to avoid conflict with the built-in +), including operators. But there is a cultural tendency to use meaningful function names, so this doesn't get abused much. Also, in Lisp prefix notation tends to get used exclusively, so there is less value in the "syntactical sugar" that operator overloads provide.

Java - disallows operator overloading. This is occasionally annoying (for stuff like the Complex number case) but on average it's probably the right design decision for Java which is intended as a simple, general-purpose OOP langauge. Java code is actually quite easy for low/medium-skilled developers to maintain as a result of this simplicity.

C++ has very sophisticated operator overloading. Sometimes this gets abused (cout << "Hello World!" anyone?) but the approach makes sense given C++'s positioning as a complex language that enables high level programming while still allowing you to get very close to the metal for performance, so you can e.g. write a Complex number class that behaves exactly as you want without compromising performance. It is understood that it is your own responsibility if you shoot yourself in the foot.


问:
Evaluate math expressions without a stack
How do you evaluate arbitrary math expressions using temporary variables instead of a stack?  What I'm talking about is translating an expression into an array of simple operations- each that change one variable based on the second argument.

An example list of operations might be:

```<code>=
+=
-=
*=
/=
</code>```

Notice how each operation changes the first argument. (none of them "return" anything)

Here's a simple expression: (I have postfix with depth written under it as well)

```<code>x=2+a*(b+c)
x 2 a b c + * + =
0 1 2 3 4 3 2 1 0

x=c
x+=b
x*=a
x+=2
</code>```

Notice how you don't need temporary variables.

Here's an expression that requires a temporary variable:

```<code>x=a*(b+c)+d*(e+f)
x a b c + * d e f + * + =
0 1 2 3 2 1 2 3 4 3 2 1 0

x=b
x+=c
x*=a
tmp=e
tmp+=f
tmp*=d
x+=tmp
</code>```

I can't seem to figure out an algorithmic solution for obtaining these sets of operations.  Needing temporary variables seems to have something to do with lower-precedence operators that have the result of higher-precedence operators as arguments, but I can't tell.

I feel stupid...  The way seems right in front of me but I can't see it.  Obviously you could do it the "easy" way; AKA, make a temporary variable to store the result of each operation so no operations are destructive to anything but what you put before the =, but that's bad and I don't like it.  How can you get the "algorithm" for an expression in simplest form?

EDIT:  Due to my own ambiguity, I must clarify that a stack is allowed in translation, but not in the end psuedo-language I'm producing.

答:
Here is a suggestion.

Create a parse tree.   Reorder it so that the deepest part of the tree is to the left, and do this recursively.

Every "rising chain" in the parse tree does not need temporaries.  Every time you encounter a node with children on both sides, you will need a temporary.  If you process the whole tree, you can discover the maximum number of temporaries that you need at any given time.

I have not tried to show that this greedy solution is truly optimal, but it discovers the best answer in simple cases, and in all cases you'll come up with an answer with a limited number of temporaries.


问:
2 different tasks in template method
I've read about Template Method Pattern but I'm not sure about one thing.

The steps (methods) of an algorithm are supposed to be in the template method. In the case my template method's algorithm is about 2 completely different tasks that I would like all my objects to perform, let's say the one is drawing and the other calculating, can I still put all these methods in one method and call this my template method?

答:
It is hard to tell without more information but methods are meant to perform a single operation. If it is doing two related but different things, each thing should be moved into a separate method. There is nothing wrong with having multiple template methods, particularly if one thing may want to be modified (that is overridden) but not the other.

Moreover, if the class is doing multiple things (such as drawing and calculating), it may violate the "Single Responsibility Principle", however this digresses from the question.

Title: 2 different tasks in template method


问:
Best Practice to Avoid "Playing Telephone" with Constructor Arguments
I find that the encapsulation required by OO has me frequently passing paramenters down the line from parent to child to great grandchild to second grand nephew once removed (not actually that bad). But inevitably in the process, and especially if graphics are involved there will be garbling the by the third iteration of someConstructor(int minX, int minY, int maxX, int maxY).

I found at least one question here suggesting that parameter objects are the solution. These seem to me more like a kludge designed to satisfy a low parameter count fetish than genuinely useful. Besides, in these scenarios, I am generally cutting the numbers into smaller pieces (of screen) with each step.

It occurs to me if these constructor calls are laid out line by line higher up the chain, I'd have easy comparisons. But this seems to lose all semblance of OOPiness. In my most recent adventure with find-the-transposed-measurements, I was drawing a music keyboard. I don't want the main view to know or care what or exactly where the G# key is.

So, best practices? Please don't say, go slower, be less sloppy.

答:
To expand on @9000's comment, I would use objects that provide more information and possibly error checking about your arguments. For example, in the following:

```<code>drawLine(100, 20, 300, 30);
drawLine(new Point(100, 20), new Point(300, 30));
</code>```

The second is generally more readable. It can check errors (can coordinates be negative? can a rectangle have a negative width or height?) and provides an easier way to access helper methods (such as converting coordinate systems or affine transformations). Also, if there is a lot of data being passed around (such as a list of points for a polyline), you end up passing object references rather than the whole data structure.

Body:
To expand on @9000's comment, I would use objects that provide more information and possibly error checking about your arguments. For example, in the following:

drawLine(100, 20, 300, 30);
drawLine(new Point(100, 20), new Point(300, 30));

The second is generally more readable. It can check errors (can coordinates be negative? can a rectangle have a negative width or height?) and provides an easier way to access helper methods (such as converting coordinate systems or affine transformations). Also, if there is a lot of data being passed around (such as a list of points for a polyline), you end up passing object references rather than the whole data structure.


答:
One thing that hasn't been mentioned yet is the case of Smalltalk, where everything (including operators) is a message send. "Operators" like +, | and so on are actually unary methods.

All methods can be overridden, so a + b means integer addition if a and b are both integers, and means vector addition if they're both OrderedCollections.

There are no precedence rules, since these are just method calls. This has an important implication for standard mathematical notation: 3 + 4 * 5 means (3 + 4) * 5, not 3 + (4 * 5).

(This is a major stumbling block to Smalltalk newbies. Breaking mathematics rules removes a special case, so that all code evaluation proceeds uniformly left to right, making the language that much simpler.)

Title: Why aren't user-defined operators more common?

Body:
One feature I miss in from functional languages is the idea that operators are just functions, so adding a custom operator is often as simple as adding a function. Many procedural languages allow operator overloads, so in some sense operators are still functions (this is very true in D where the operator is passed as a string in a template parameter).

It seems that where operator overloading is allowed, it is often trivial to add additional, custom operators. I found this blog post, which argues that custom operators don't work nicely with infix notation because of precedence rules, but the author gives several solutions to this problem.

I looked around and couldn't find any procedural languages that support custom operators in the language. There are hacks (such as macros in C++), but that's hardly the same as language support.

Since this feature is pretty trivial to implement, why isn't it more common?

I understand that it can lead to some ugly code, but that hasn't stopped language designers in the past from adding useful features that can be easily abused (macros, ternary operator, unsafe pointers).

Actual use cases:

Implement missing operators (e.g. Lua doesn't have bitwise operators)

Mimic D's ~ (array concatenation)

DSLs

Use | as Unix pipe-style syntax sugar (using coroutines/generators)

I'm also interested in languages that do allow custom operators, but I'm more interested in why it has been excluded. I thought about forking a scripting language to add user-defined operators, but stopped myself when I realized that I haven't seen it anywhere, so there's probably a good reason why language designers smarter than me haven't allowed it.


答:
I'm not entirely sure what your class hierarchy looks like, but I will give you my thoughts on object construction and how I have started designing my classes in projects I work on.

Inheritance or Composition: It sounds like you are assuming that because you are programming in an OO style, you must always use inheritance; this is just not true. It is up to you, the designer, to determine what solution best solves you problem. Below I'll give you an example of composition instead of inheritance.

Parameter Objects (as you put it): When you design a class, you are modeling your data by how it is seen in your head; you are giving it a name and structure. A simple example would be a class called Point2D that would have an X and a Y property associated with that class. The good thing about creating this "parameter object" is now you can create functions or methods that operate on that object. I don't create Point2D with a constructor, I make a second class called Point2DFactory with a static Create(x, y) method. This does 2 things for me, it keeps my Point2D class light weight and puts all the logic for creating a Point2D in one place. I can now compose a Point2D in anyway I wish and the Point2D is no longer responsible for both being a point and knowing how a point is created. It is not tied to some inheritance chain, it is the Point2DFactory's job to worry about that.

Inversion of Control: If you need to encapsulate some over arching functionality into a single object that can be broken down into little bits of functionality, you can use an inversion of control framework to help you out. What it does is take all those "parameter objects" you have created (hopefully with abstract interfaces) and figures out how to build the object you require by injecting the functionality into it's constructor.

If you are creating constructors that rely on some math to generate their parameters, consider creating a parameter object and a factory that creates it. Then you can make another factory that creates your desired object based on any input you wish. Can you tell I use the factory pattern a lot :P? I hope what I have said shows you that creating more objects isn't a bad thing (OOP requires it :/) and if you can get each class/object to only have one responsibility, your overall code base will be extremely flexible and a pleasure to maintain.

EDIT in response to comment: Maybe I am not understanding exactly what you are asking. I thought your problem what nested constructors that have similar input names. What I was trying to get at is that, in general, a parent shouldn't need to know how to instantiate its child objects. That makes your parent responsible for doing what ever it is the parent does AND for creating the child objects. If the parent's soul purpose to is create the child objects, that is called a factory in design pattern terms. Instead of constructor chaining, pull that logic that instantiates child objects outside of the constructors. This giving you more flexible usability of the logic that creates child objects and better adherence to SOLID principles.

Title: Best Practice to Avoid "Playing Telephone" with Constructor Arguments

Body:
I find that the encapsulation required by OO has me frequently passing paramenters down the line from parent to child to great grandchild to second grand nephew once removed (not actually that bad). But inevitably in the process, and especially if graphics are involved there will be garbling the by the third iteration of someConstructor(int minX, int minY, int maxX, int maxY).

I found at least one question here suggesting that parameter objects are the solution. These seem to me more like a kludge designed to satisfy a low parameter count fetish than genuinely useful. Besides, in these scenarios, I am generally cutting the numbers into smaller pieces (of screen) with each step.

It occurs to me if these constructor calls are laid out line by line higher up the chain, I'd have easy comparisons. But this seems to lose all semblance of OOPiness. In my most recent adventure with find-the-transposed-measurements, I was drawing a music keyboard. I don't want the main view to know or care what or exactly where the G# key is.

So, best practices? Please don't say, go slower, be less sloppy.


答:
First of all: A generic repository should be considered to be a base class and not complete implementations. It should help you to get the common CRUD methods in place. But you still have to implement the query methods:

```<code>public class UserRepository : EntityFrameworkRepository<User>, IUserRepository
{
    public UserRepository(DbContext context){}

    public ICollection<Person> FindRetired()
    {
        return context.Persons.Where(p => p.Status == "Retired").ToList();
    }
}
</code>```

Second:

Do not return IQueryable. It's a leaky abstraction. Try to implement that interface yourself or use it without knowledge about the underlying db provider. For instance, every db provider has it's own API for eagerly load entities. That's why it's a leaky abstraction.

Alternative

As an alternative you can use queries (for instance as defined by the Command/Query separation pattern). CQS is described in wikipedia.

You basically create query classes which you invoke:

```<code>public class GetMyMessages
{
    public GetMyMessages(IDbConnection connection)
    {
    }

    public Message[] Execute(DateTime minDate)
    {
        //query
    }
}
</code>```

the great thing with queries is that you can use different data access methods for different queries without cluttering the code. you can for instance use a web service in one, nhibernate in another and ADO.NET in a third.

If you are interested in a .NET implementation read my article: http://blog.gauffin.org/2012/10/griffin-decoupled-the-queries/

Title: Alternatives to the repository pattern for encapsulating ORM logic?

Body:
I've just had to switch out an ORM and it was a relatively daunting task, because the query logic was leaking everywhere. If i'd ever had to develop a new application, my personal preference would be to encapsulate all query logic (using an ORM) to futureproof it for change. Repository pattern is quite troublesome to code and maintain so i was wondering if there are any other patterns to solve the problem ?

I can foresee posts about not adding extra complexity before it's actually needed, being agile etc. but i'm only interested about the existing patterns solving a similar problem in a simpler way.

My first thought was to have a generic type repository, to which i add methods as needed to specific type repository classes via extension methods, but unit testing static methods is awfully painful. IE:

```<code>public static class PersonExtensions
{
    public static IEnumerable<Person> GetRetiredPeople(this IRepository<Person> personRep)
    {
        // logic
    }
}
</code>```

Body:
First of all: A generic repository should be considered to be a base class and not complete implementations. It should help you to get the common CRUD methods in place. But you still have to implement the query methods:

public class UserRepository : EntityFrameworkRepository<User>, IUserRepository
{
    public UserRepository(DbContext context){}

    public ICollection<Person> FindRetired()
    {
        return context.Persons.Where(p => p.Status == "Retired").ToList();
    }
}

Second:

Do not return IQueryable. It's a leaky abstraction. Try to implement that interface yourself or use it without knowledge about the underlying db provider. For instance, every db provider has it's own API for eagerly load entities. That's why it's a leaky abstraction.

Alternative

As an alternative you can use queries (for instance as defined by the Command/Query separation pattern). CQS is described in wikipedia.

You basically create query classes which you invoke:

public class GetMyMessages
{
    public GetMyMessages(IDbConnection connection)
    {
    }

    public Message[] Execute(DateTime minDate)
    {
        //query
    }
}

the great thing with queries is that you can use different data access methods for different queries without cluttering the code. you can for instance use a web service in one, nhibernate in another and ADO.NET in a third.

If you are interested in a .NET implementation read my article: http://blog.gauffin.org/2012/10/griffin-decoupled-the-queries/


问:
How to effectively do manual debugging?
Say you don't have a debugger available, what would be an effective approach to debug code which doesn't work (as expected)?</p>

答:
After the other answers have failed, there's always binary search debugging:

Eliminate a certain portion (preferably half) of the possible causes (lines of code, revisions, input, etc)

Try to reproduce the problem again.

If the problem persists: go back to step 1.

If you have only one cause (line of code, revision, piece of input, etc) left: hurray! Exit procedure.

Otherwise: revert step 1, and now eliminate the other half.

Go back to step 2.

Note: obviously, this technique only works if you can reliably reproduce the problem.

Title: How to effectively do manual debugging?


答:
Expanding on the "The most effective debugging tool is still careful thought, coupled with judiciously placed print statements."

First, try to narrow down the moment the bug occurs. Make the user-observable symptoms system-observable. (say, some string changes to gibberish, add a loop that polls the content of the script and triggers your debug as it changes.) Of course if the error is a crash, add segfault handling.

Then try to narrow down the thread if the problem is with multi-threaded environment. Give each thread an identifier, and dump it when the bug occurs.

Once you have the thread, sprinkle the code of given thread with printfs copiously to nail down the point where it surfaces.

Then backtrace to where the actual action that creates it occurs (the destructive action will often be quite a bit before where the damaged data triggers the problem.) Examine what structures/variable occur nearby in the memory, observe loops that affect them, check points where the corrupted value is written to.

Once you have the point that was causing the problem, before fixing it, think twice what the correct behavior should be.

Title: How to effectively do manual debugging?

Body: Say you don't have a debugger available, what would be an effective approach to debug code which doesn't work (as expected)?</p>


问:
Use Queue<T> or stick to native f# lists
I need something that represents a queue in F#.

The queue will be filled with items once, and (as the application progresses) items will be taken from this queue and moved to other lists.

Should I use the Queue class in .NET, or should I avoid it, and use the native lists in F# instead? Is there a better solution?

Why should I use one, or the other, in a functional language such as F#?

答:
If you are creating a class library to be shared with other .NET applications, and this is part of the public interface, then you should stick with normal .NET class library types.

If you are sticking solely to the F# domain, or this is part of the private implementation details, I would prefer to use native F# types.

In your case however, the F# list does not correspond to a Queue, at least not a FIFO queue (first in, first out). The F# list corresponds to a stack (last in, first out).

I'm not aware of a native F# data type providing that functionality, and in fact, the the queue data type does not sit well with the purely functional programming paradigm (I'm not an expert on functional programming so perhaps someone will prove this statement wrong).

So the big question on how to solve the problem is really, is your problem well suited to the functional programming paradigm? If so, you should avoid using imperative data types such as queues, and try to solve the problem using purely functional data types.

If your problem on the other hand is not well suited to a functional programming paradigm, perhaps you should not use F# at all, but use a more object-oriented programming paradigm. Not that F# cannot do object oriented programming, because it can. But if that it is the general programming paradigm, it is IMHO easier to use e.g. C#.


答: If I'm understanding your problem correctly, look at the algorithms used by compiler to compile expressions for machines with registers while trying to use as few registers as possible.  For instance this one is a classic, more modern approaches are using graph coloring.</p>

Title: Evaluate math expressions without a stack

Body:
How do you evaluate arbitrary math expressions using temporary variables instead of a stack?  What I'm talking about is translating an expression into an array of simple operations- each that change one variable based on the second argument.

An example list of operations might be:

```<code>=
+=
-=
*=
/=
</code>```

Notice how each operation changes the first argument. (none of them "return" anything)

Here's a simple expression: (I have postfix with depth written under it as well)

```<code>x=2+a*(b+c)
x 2 a b c + * + =
0 1 2 3 4 3 2 1 0

x=c
x+=b
x*=a
x+=2
</code>```

Notice how you don't need temporary variables.

Here's an expression that requires a temporary variable:

```<code>x=a*(b+c)+d*(e+f)
x a b c + * d e f + * + =
0 1 2 3 2 1 2 3 4 3 2 1 0

x=b
x+=c
x*=a
tmp=e
tmp+=f
tmp*=d
x+=tmp
</code>```

I can't seem to figure out an algorithmic solution for obtaining these sets of operations.  Needing temporary variables seems to have something to do with lower-precedence operators that have the result of higher-precedence operators as arguments, but I can't tell.

I feel stupid...  The way seems right in front of me but I can't see it.  Obviously you could do it the "easy" way; AKA, make a temporary variable to store the result of each operation so no operations are destructive to anything but what you put before the =, but that's bad and I don't like it.  How can you get the "algorithm" for an expression in simplest form?

EDIT:  Due to my own ambiguity, I must clarify that a stack is allowed in translation, but not in the end psuedo-language I'm producing.


问:
How to divide work to a network of computers?
Imagine a scenario as follows: Lets say you have a central computer which generates a lot of data. This data must go through some processing, which unfortunately takes longer than to generate. In order for the processing to catch up with real time, we plug in more slave computers.

Further, we must take into account the possibility of slaves dropping out of the network mid-job as well as additional slaves being added. The central computer should ensure that all jobs are finished to its satisfaction, and that jobs dropped by a slave are retasked to another.

The main question is: What approach should I use to achieve this?

But perhaps the following would help me arrive at an answer:
Is there a name or design pattern to what I am trying to do?

What domain of knowledge do I need to achieve the goal of getting these computers to talk to each other? (eg. will a database, which I have some knowledge of, be enough or will this involve sockets, which I have yet to have knowledge of?)

Are there any examples of such a system? The main question is a bit general so it would be good to have a starting point/reference point.

Note I am assuming constraints of c++ and windows so solutions pointing in that direction would be appreciated.

答:
Are there any examples of such a system?

Yes. This pattern is known as distributed computing(or distributed programming or whatever cool word you want to put after distributed). My suggestion will be not to build this in-house before looking at other solutions. You can look at this stack overflow question for various options. And then take calculated decision.


答:
There is nothing really that prohibits you from calling two things from the template method. In your case you could do it like this:

public abstract class ContextObject {

    // The template method
    public void PerformDraw() {
        Draw();
        Calculate();
    }

    public abstract void Draw();

    public abstract void Calculate();

}

// The implementation is rather obvious:

public class ConcreteObject : ContextObject {

     public void Draw() { ... }

     public void Calculate() { ... }

}

// For all the concrete objects you only need to call
// the template method, regardless of the implementation

for (ContextObject context : contextObjectList) {
    context.PerformDraw();
}
```

<p>The only drawback with this template object class is that everyone needs to implement the <code>Draw</code> and the <code>Calculate</code> methods. So if all subclasses need to mix between draw and calculate in several combinations you might want to use strategy pattern instead like this:</p>

<pre class="lang-cs prettyprint-override"><code>// Strategy #1
public interface IDrawable {
    void Draw();
}

// Strategy #2
public interface ICalculatable {
    void Calculate();
}

// the previous class needs to use the interfaces above:
public abstract class ContextObject {

    private IDrawable drawable;
    private ICalculatable calculatable;

    public ContextObject(IDrawable drawable, ICalculatable calculatable) {
        this.calculatable = calculatable;
        this.drawable = drawable;
    }

    public void PerformDraw() {
        drawable.Draw();
        calculatable.Calculate();
    }

}

// The implementations
public class DrawUno : IDrawable { ... }
public class CalcUno : ICalculatable { ... }

public class ConcreteObject : ContextObject {

    // call the base class's constructor with the implementations
    public ConcreteObject() :
        base(
            new DrawUno(),
                // can be mixed with any other of type IDrawable
            new CalcUno()
                // can be mixed with any other type of ICalculatable
        )
    {
        // no-op, the base constructor does the stuff you need...
    }

}
</code>```

You could also mix and match, it all depends on what you actually need to do.

Title: 2 different tasks in template method

Body:
I've read about Template Method Pattern but I'm not sure about one thing.

The steps (methods) of an algorithm are supposed to be in the template method. In the case my template method's algorithm is about 2 completely different tasks that I would like all my objects to perform, let's say the one is drawing and the other calculating, can I still put all these methods in one method and call this my template method?

Body:
There is nothing really that prohibits you from calling two things from the template method. In your case you could do it like this:

public abstract class ContextObject {

    // The template method
    public void PerformDraw() {
        Draw();
        Calculate();
    }

    public abstract void Draw();

    public abstract void Calculate();

}

// The implementation is rather obvious:

public class ConcreteObject : ContextObject {

     public void Draw() { ... }

     public void Calculate() { ... }

}

// For all the concrete objects you only need to call
// the template method, regardless of the implementation

for (ContextObject context : contextObjectList) {
    context.PerformDraw();
}

The only drawback with this template object class is that everyone needs to implement the Draw and the Calculate methods. So if all subclasses need to mix between draw and calculate in several combinations you might want to use strategy pattern instead like this:

// Strategy #1
public interface IDrawable {
    void Draw();
}

// Strategy #2
public interface ICalculatable {
    void Calculate();
}

// the previous class needs to use the interfaces above:
public abstract class ContextObject {

    private IDrawable drawable;
    private ICalculatable calculatable;

    public ContextObject(IDrawable drawable, ICalculatable calculatable) {
        this.calculatable = calculatable;
        this.drawable = drawable;
    }

    public void PerformDraw() {
        drawable.Draw();
        calculatable.Calculate();
    }

}

// The implementations
public class DrawUno : IDrawable { ... }
public class CalcUno : ICalculatable { ... }

public class ConcreteObject : ContextObject {

    // call the base class's constructor with the implementations
    public ConcreteObject() :
        base(
            new DrawUno(),
                // can be mixed with any other of type IDrawable
            new CalcUno()
                // can be mixed with any other type of ICalculatable
        )
    {
        // no-op, the base constructor does the stuff you need...
    }

}

You could also mix and match, it all depends on what you actually need to do.


答:
If, and only if, the project is truly dual licensed then you may pick your preferred license and fork from there.  But you must make sure that all aspects of the code that you need are licensed in your preferred license.  You are allowed to carve apart a project to 'cherry pick' just the aspects you need or are compatible with your preferred license.

Think of the dual-licensing as trim lines on an automobile.  Presuming you can only afford one vehicle, you pick one trim line and you drive that off the lot.  (Aka, you forked the project.)  The vehicle still runs; everything is fine; you have a single license now.

It's probable that trim line A has some features that you really want, but you can only 'afford' trim line B.  That's when you rely upon the auto parts after-market and other mechanics to install the features you wanted from A but couldn't 'afford'.  And if you're a truly handy DIY'er, you can make those modifications yourself.  Those new features that you built / paid for are now part of trim line B or however you choose to release / license them (this is where the auto analogy falls apart).

Some quick caveats -

1) I use the term 'afford' to make the automobile analogy work.  It's a metaphor, that's all.

2) The license you pick may affect how you can release new features.  Using GPL, for example, would force the new features to be GPL'd.

Title: When forking an dual-licensed permissive/GPL project, can I drop one of the licenses?

Body:
Consider an existing project that is dual-licensed GPL + either MIT or BSD.

Since it's dual-licensed, when I fork, can I pick one license in the fork? Or do my forked files need to continue to be dual-licensed?

It sure would be simpler to track only one license.


问:
How to test the same software on all products in a product line?
In my team we have been working on a firmware for a product. The product was released some years ago but we still implement new features in the firmware and regularly provide a new firmware for our customers. Recently we have developed a new product which use the same firmware as the first one. Of course, we had to change the firmware to allow for some new capabilities (while still keeping functionality for existing product intact).

We have a release test specification which contans mostly manual tests which we carry out before we release any new software. We have adapted this for the new product since it has additional capabilities. But most of it is common.

I know that new products are in the pipeline and in my simplistic reasoning we need to repeat our release test for each product every time we release a firmware. So i am looking for a new approach which is less time consuming. One of the things we are already working on is automation, but due to the nature of the product many tests have to be manual.

答:
The broader scope of software testing involves analyzing all of your products, supported platforms, and then identifying what needs to be tested to provide a particular degree of assurance about the results.

The most important aspect is to document what you decide and why you decided that.  You'll want to provide that documentation to your clients so they can be assured of your testing process.

For your case:

Since you're expanding, you should look for the commonality between products and firmware releases.  Aspects that are truly common don't necessarily have to be tested on every single target platform.  A representative sample should be sufficient.

Provide some discipline around your release process so you can understand what has changed between releases.  If you can demonstrate that functional area XYZ won't be affected by any of this release's changes, then you can either eliminate or reduce the amount of testing of that area.  Your product domain will dictate the balance point between eliminate or reduce testing for that cycle.

It can be expensive, but consider adding robotic automation around your test processes.  Pulling a cable; pressing buttons; dropping the device; etc... can all be performed with a robotics test harness.  This approach allows you to test around the clock, which is the other solution for time consuming tasks.  In other words, you found more time instead of decreasing the amount of time required.


答:
So this would be a problem:

```<code>x=(a*b)+(c*d)
</code>```

Assuming neither a nor b is zero, then factor out the (a*b) term:

```<code>x = (1+(c*d)/(a*b))*(a*b)
</code>```

So:

```<code>x=c
x*=d
x/=a
x/=b
x+=1
x*=a
x*=b
</code>```

As I said, if a or b is zero, you have to pre-reduce the calculation to:

```<code>x=c*d
</code>```

Body:
So this would be a problem:

x=(a*b)+(c*d)

Assuming neither a nor b is zero, then factor out the (a*b) term:

x = (1+(c*d)/(a*b))*(a*b)

So:

x=c
x*=d
x/=a
x/=b
x+=1
x*=a
x*=b

As I said, if a or b is zero, you have to pre-reduce the calculation to:

x=c*d


答:
I would split your tests in three categories:

(Unit)tests on a (simulated) reference platform. These tests should cover all the software that does not directly interface with hardware components and should include both unit-tests for the various software components and functional tests for all the features. The (simulated) reference platform should be able to support all features (even if there is no single product that has them all) and should be able to simulate hardware failures.

Tests of the hardware interfaces. These tests should give you confidence in the interfacing between hardware and software. By necessity, these tests must be executed on the hardware itself and repeated for each distinct hardware design. It might be good if these tests are specified/designed by a combined team of hardware and software people.

System tests. These tests should give confidence that the final assembled system works as designed. They should focus on the most-used features (and perhaps some easy-to-test error scenarios) and be repeated for each product that has a distinct hardware design or non-overlapping feature-set (if two products are technically identical, but one has a reduced feature set, there is no need to  test that second one as extensively).

Title: How to test the same software on all products in a product line?

Body:
In my team we have been working on a firmware for a product. The product was released some years ago but we still implement new features in the firmware and regularly provide a new firmware for our customers. Recently we have developed a new product which use the same firmware as the first one. Of course, we had to change the firmware to allow for some new capabilities (while still keeping functionality for existing product intact).

We have a release test specification which contans mostly manual tests which we carry out before we release any new software. We have adapted this for the new product since it has additional capabilities. But most of it is common.

I know that new products are in the pipeline and in my simplistic reasoning we need to repeat our release test for each product every time we release a firmware. So i am looking for a new approach which is less time consuming. One of the things we are already working on is automation, but due to the nature of the product many tests have to be manual.


问:
How would type errors be detected while creating mocks in a dynamic language?
The problem occurs while doing TDD. After a couple of test pass, the return types of some class/module change. In a statically typed programming language, if a previous mocked object was used in the tests of some other class and was not modified to reflect the type change, then compilation errors will occur.

For dynamic languages however, the change in return types might not be detected and the tests of the other class will still pass. Sure there might be integration tests that should fail later on, but unit tests would erroneously pass. Is there any way how to avoid this?

Updating with a trivial sample (on some made up language)...

Version 1:

```<code>Calc = {
    doMultiply(x, y) {return x * y}
}
//.... more code ....

// On some faraway remote code on a different file
Rect = {
    computeArea(l, w) {return Calc.doMultipy(x*y)}
}

// test for Rect
testComputeArea() {
    Calc = new Mock()
    Calc.expect(doMultiply, 2, 30) // where 2 is the arity
    assertEqual(30, computeArea)
}
</code>```

Now, on version 2:

```<code>// I change the return types. I also update the tests for Calc
Calc = {
    doMultiply(x, y) {return {result: (x * y), success:true}}
}
</code>```

...Rect will then throw an exception on runtime, yet the test will still succeed.

答:
To a certain extent, this is just part of the cost of doing business with dynamic languages.  You get a lot of flexibility, otherwise known as "enough rope to hang yourself".  Be careful with it.

To me, the problem suggest using different refactoring techniques than you would in a statically typed language.  In a static language, you replace return types in part so that you can "lean on the compiler" to find what places may break.  It is safe to do, and probably safer than modifying the return type in place.

In a dynamic language, you can't do that, so it is much safer to modify the return type in place, rather than replace it.  Possibly, you modify it by adding your new class to it as a member, for the classes that need it.

OwnerDisplayName: jvliwanag

OwnerDisplayName: tallseth


答:
@bytebuster made a comment above that got me to thinking.

The .NET's Queue<T> is mutable, and undoubtedly has a standard OO implementation which has guaranteed O(1) for enqueue and dequeue.

Okasaki's being the standard best-performance immutable functional version of a Queue and not having the same guarantee, perhaps you could apply this rule to your usage in F#:

If the correct data structure is a Queue for your problem, and performance is important (though if it's not for you, it may be important for your consumers, so worth thinking about then as well), stick with the .NET mutable Queue.

Also however I agree with the other answer here, if it's a method signature to be used by other .NET languages, use the common .NET Queue<T>

If performance is irrelevant and it's not to be used by other .NET languages, I guess it would be safe to say it's up to you whether or not you want to implement a functional Queue in F# to use or just stick with the .NET implementation.

Title: Use Queue<T> or stick to native f# lists

Body:
I need something that represents a queue in F#.

The queue will be filled with items once, and (as the application progresses) items will be taken from this queue and moved to other lists.

Should I use the Queue class in .NET, or should I avoid it, and use the native lists in F# instead? Is there a better solution?

Why should I use one, or the other, in a functional language such as F#?


问:
Constants in C#
Why does the compiler store constant values in the assembly metadata?
Are they directly embedded to Intermediate Language code from the assembly metadata?</p>

答:
I think you mix up two assemblies.

The constant is only stored in the metadata in the assembly where it is defined. Metadata contains information about all the types and members in an assembly and constants are members.

No information about the constant is stored in the assembly where it is used. The constant value is used directly in the IL just as if you had written the constant number or string directly in the source.

An example: One of my applications use a lot of constants to identify database tables and fields. I have one assembly that only contain all constants.

When I build the application I add a reference to the "constants" assembly in Visual Studio. Since the assembly only contain constants there is no reference to it in my application and the "constants" assembly is not needed at run-time.

Title: Constants in C#


答:
If your code changes and your tests still pass, then there's either something wrong with your tests (i.e. you are missing an assertion), or the code didn't actually change.

What do I mean by that? Well, your tests describe the contracts between parts of your code. If the contract is "the return value must be iterable", then changing the return value from say an array to a list is not actually a change in contract, and therefore won't necessarily trigger a test failure.

In order to avoid missing assertions, you can use tools such as code coverage analysis (it won't tell you what parts of your code are tested, but it will tell you what parts definitely aren't tested), cyclomatic complexity and NPath complexity (which give you a lower bound on the number of assertions required to achieve full C1 and C2 code coverage) and mutation testers (which inject mutations in your code such as turning true to false, negative numbers into positive, objects into null etc. and check whether that makes tests fail).

Title: How would type errors be detected while creating mocks in a dynamic language?

Body:
The problem occurs while doing TDD. After a couple of test pass, the return types of some class/module change. In a statically typed programming language, if a previous mocked object was used in the tests of some other class and was not modified to reflect the type change, then compilation errors will occur.

For dynamic languages however, the change in return types might not be detected and the tests of the other class will still pass. Sure there might be integration tests that should fail later on, but unit tests would erroneously pass. Is there any way how to avoid this?

Updating with a trivial sample (on some made up language)...

Version 1:

```<code>Calc = {
    doMultiply(x, y) {return x * y}
}
//.... more code ....

// On some faraway remote code on a different file
Rect = {
    computeArea(l, w) {return Calc.doMultipy(x*y)}
}

// test for Rect
testComputeArea() {
    Calc = new Mock()
    Calc.expect(doMultiply, 2, 30) // where 2 is the arity
    assertEqual(30, computeArea)
}
</code>```

Now, on version 2:

```<code>// I change the return types. I also update the tests for Calc
Calc = {
    doMultiply(x, y) {return {result: (x * y), success:true}}
}
</code>```

...Rect will then throw an exception on runtime, yet the test will still succeed.


答:
The best way to think about it I find is: At compile time a const is converted to a literal where it is used.

The only reason it goes into the manifest in the assembly it was defined in was to make it accessible to consumers. It is a part of a given type and that type's metadata is stored in it's assembly, not the assemblies that consume it.

So, it is an in-line literal in consumption, and a consumable type-encapsulated property or field in metadata.

Title: Constants in C#

Body:
Why does the compiler store constant values in the assembly metadata?
Are they directly embedded to Intermediate Language code from the assembly metadata?</p>


问:
Design Patterns - Service Layer
I currently reading a lot about Design Patterns and I have been watching various Pluralsight videos from their library. Now so far I have learnt the following:

Repository Pattern

Unit of Work Pattern

Abstract Factory Pattern

Reading the awesome "DI in .NET" book

Now I read lot about Services and Service Layers and wanted some advice about the best place to read up and learn about these. I presume this fits into Domain Driven Design and I should start there? The term "Service" just seem to be used widely within IT and it can be confusing the exact meaning.

So my questions is:

What is the Service Layer

Where is the best place to learn about them. I know there are probably tonnes of interweb/books/blogs on the subject, but some good areas to start from would be nice.

If I'm being too vague, let me know.

答:
Aside from pluralsight, I found that dofactory was a great place to learn about patterns.  Their Patterns in Action project provides a reference Visual Studio solution depicting many of the architectural patterns you'll want to learn about, including the hosting and service layers.

In dofactory's reference solution, the service layer is depicted as the abstraction of the core functionality of the application.  It is the interface through which the higher layers do work.  Notice the break-out of the hosting and service layer allowing the services to be made available and reused in different scenarios.

Title: Design Patterns - Service Layer


答:
Here's a way:

Start with your expression:

```<code>x=2+a*(b+c)
</code>```

Write out the stack operations that would be used:

```<code>PUSH b
PUSH c
ADD
PUSH a
MULTIPLY
PUSH 2
ADD
STORE x
</code>```

Replace PUSH followed by a math operation by an inplace math operation

```<code>PUSH b
IADD c
IMULTIPLY a
IADD 2
STORE x
</code>```

Simply use variables and temps for each position on the stack. The first position will be x, and the rest will be temps

```<code>x = b
x += c
x *= a
x += 2
</code>```

Body:
Here's a way:

Start with your expression:

x=2+a*(b+c)

Write out the stack operations that would be used:

PUSH b
PUSH c
ADD
PUSH a
MULTIPLY
PUSH 2
ADD
STORE x

Replace PUSH followed by a math operation by an inplace math operation

PUSH b
IADD c
IMULTIPLY a
IADD 2
STORE x

Simply use variables and temps for each position on the stack. The first position will be x, and the rest will be temps

x = b
x += c
x *= a
x += 2


答:
I researched myself for quite long time and found from a book that this can be the reason...

Since constant values never changes, constants are considered to be part of the defining type. Therefore defining constants creates metadata.

Title: Constants in C#


问:
Should I rewrite the git history of a non-GPL project to remove GPL code that was later removed?
I have an MIT-licensed project that used to include a GPL JavaScript library which has since been removed.

Is there any legal necessity to rewrite the revision history to completely remove this code?

答:
I am not a lawyer, but:

The issue largely comes down to licensing documentation. There is no reason why your old revision could not be licensed under the GPL, but if you do not announce that it is licensed under the GPL, then it's functionally not, and those revisions are in violation of the GPL. You cannot even be given the benefit of the doubt that might be given to a young repository with no published license on the revisions ("I hadn't gotten around to putting one up yet, and I thought it would be obvious since I'm using GPL libraries...") , since your licensing documentation for that revision probably says that the project, as a whole, is under MIT.

Thus, the pathological person who downloads the old version of your code has received software that claims to be MIT-licensed but that is legally obligated to be GPL-licensed, which is a GPL violation.

I'm afraid you must eliminate the possibility of public distribution of your non-compliant revisions by removing them from your history.


问:
Best practices: Ajax and server side scripting with stored procedures
I need to rebuild an old huge website and probably to port everyting to ASP.NET and jQuery and I would like to ask for some suggestion and tips. Actually the website uses:

Ajax (client site with prototype.js)

ASP (vb script server side)

SQL Server 2005

IIS 7 as web server

This website uses hundred of stored procedures and the requests are made by an ajax call and only 1 ASP page that contain an huge select case

Shortly an example:

JAVASCRIPT + PROTOTYPE:

```<code>var data = {
    action:     'NEWS',
    callback:   'doNews',
    param1:     $('text_example').value,
    ......:     ..........};
AjaxGet(data); // perform a call using another function + prototype
</code>```

SERVER SIDE ASP:

```<code><% ......
select case request("Action")
case "NEWS"
    With cmmDB
        .ActiveConnection = Conn
        .CommandText = "sp_NEWS_TO_CALL_for_example"
        .CommandType = adCmdStoredProc

        Set par0DB = .CreateParameter("Param1", adVarchar, adParamInput,6)
        Set par1DB = .CreateParameter(".....", adInteger, adParamInput)
        ' ........ ' can be more parameters

        .Parameters.Append par0DB
        .Parameters.Append par1DB

        par0DB.Value = request("Param1")
        par1DB.Value = request(".....")

        set rs=cmmDB.execute

        RecodsetToJSON rs, jsa ' create JSON response using a sub
    End With
.... %>
</code>```

So as you can see I have an ASP page that has a lot of CASE and this page answers to all the ajax request in the site.

My question are:

Instead of having many CASES is it possible to create dynamic vb code that parses the ajax request and creates dynamically the call to the desired SP (also implementing the parameters passed by JS)?

What is the best approach to handle situations like this, by using the advantages of .Net + protoype or jQuery?

How the big sites handle situation like this? Do they do it by creating 1 page for request?

Thanks in advance for suggestion, direction and tips.

答:
Overall, I think this question is too generic to have an "answer", but here is my "opinion" as a first ditch effort which doesn't reflect even a great approach.

I see this post is a bit old so hopefully by now, the OP has obtained a bit more ASP.NET as well as Object-Oriented Programming experience.  With that, I would recommend forgetting about the stored procedures for a bit and focus on adding OOP principals to the web application initially.  With the assumption that the use of ajax is necessary, I'd say the existing approach can be salvaged and to officially promote the use of the parsing ASP page to be an "engine" implemented as a service (think web/WCF service).  Perhaps the service is responsible for parsing or it delegates parsing to a stored procedure or to a .NET object; both have their pros and cons: updating the parsing logic in a stored procedure would not require recompiling/deploying the application and could be delegated to a DBA (who could further optimize the routine), however, storing the logic in code would better suit versioning requirements of the application as the parser and code that uses the parser are likely stored together.


问:
Finding the time complexity of the following program that uses recursion
I need to find the time complexity in terms of Big Oh notation for the following program which computes the factorial of a given number: The program goes like this:

```<code>public int fact(int n){

  if (n <=1)
    return 1;
  else
  return n * fact (n-1);
}
</code>```

I know that the above program uses recursion but how to derive the time complexity for the above program?

答:
This solution can be easily transformed into much simplier:

```<code>int res = 1;
for(int i = 1; i <= n; ++i) {
    res *= i;
}
</code>```

Considering that multiplication is O(1) (if using Karatsuba multiplication, it's O(m^1.585), where m is the length of a number) the result is O(n) for this function.

Body:
This solution can be easily transformed into much simplier:

int res = 1;
for(int i = 1; i <= n; ++i) {
    res *= i;
}

Considering that multiplication is O(1) (if using Karatsuba multiplication, it's O(m^1.585), where m is the length of a number) the result is O(n) for this function.


问:
Reporting and handling asynchronous process errors to a client
I have a product with two separate applications.  The core of the product lives in the database (oracle) and runs according to a schedule. The other is a client application (currently ASP.NET MVC3) used to manage the database application.  There are three levels of validation going on; client, server-side, and database before the client data is saved to the database.

However, there are cases where pieces of the data set are currently valid but could become invalid at some point in the future. In these cases rather than abort the entire (lengthy) data input process, we just place the process for the data set on hold until the data either becomes valid, or is updated to a valid value. The error might be something like, "Hey, you scheduled the copy process of data Foo to location X, and then grant access to user Bob. The Bob user account you originally selected is no longer valid, what would you like to do? 'Cancel the Copy Request' 'Change the User' or 'Wait'".

Is there a best practice for storing and reporting error conditions (fixable by the user) and exceptions (not fatal and not fixable by the user) back to the client from the database?

For example:

- Database starts process A

- Database selects data set Foo

- During process an error or exception is encountered

- Database stores the error or exception

- Database handles the abort for process A with data set Foo

- Database continues process A with next data set until all data sets are processed

- Database completes process A

Then some time later:

- User logs in to client application at a later time (after the weekend?)

- User receives notification that an error or exception occurred

My first thought is some sort of db table storing various fields (event_ time_stamp, process, event, object_type, object_pk, event_code, additional_details, status, last_updated). Then setting up client-side templates (i.e. hard coded with parameters) for each error code and presenting those to the user...but there has to be a better way?

Ideally I am looking for a solution that will allow the client to provide helpful UI options that will aid the user in possibly resolving the errors.

What solutions have you found to this problem? Would something like NServiceBus or MassTransit work?

EDIT:
There are two different requirements here. The first to store the exceptions, and the second to report (and possibly take action on) them.

答: Not having experience with the two products you listed but plenty with ASP.NET, I'd say this problem sounds way too generic for a framework to address, no?  Not sure if to say "generic" or "specific".  I currently follow the less-then desirable approach you laid out: store errors on a db /w certain fields and display to the user.  What I don't do but can extend to do is allow the user to select an entry and have them fix it.  It's the "fixing" part that sounds too generic for a framework to do.  Only you know what "fixing" the error means within your context and can program for that.  In this case, give the user a webform to update the data and save it.  I could see how the two products you mentioned can help in reporting the errors but still feel the rest requires a custom touch.</p>


问:
event listener pattern in api - what should adding the same listener twice do?
In designing an API that provides an event listening interface, it seems there are two conflicting ways of treating calls to add/remove listeners:

Multiple calls to addListener will only add a single listener (like adding it to a set); can be removed with a single call to removeListener.

Multiple calls to addListener will add a listener each time (like adding it to a list); must be balanced by multiple calls to removeListener.

I've found an example of each: (1) - The DOM addEventListener call in browsers only adds listeners once, silently ignoring requests to add the same listener a second time and (2) - jQuery .on behaviour adds listeners multiple times.

Most other listener APIs seem to use (2), such as SWT and Swing event listeners.  If (1) is chosen, there's also the question of whether it should fail silently or with an error when there is a request to add the same listener twice.

In my implementations, I tend to stick with (2) since it provides a cleaner setup/teardown type interface and reveals bugs where 'setup' is unintentionally being done twice, and is consistent with most implementations I've seen.

This leads me to my question - Is there a particular architecture or other underlying design that lends itself better to the other implementation?  (ie: why does the other pattern exist?)

答:
First, I would choose an approach where the order in which the listeners are added is exactly the order they will be called when the related events are triggered. If you decide to go with (1), that will mean you use an ordered set, not just a set.

Second, you should clarify a general design goal: shall your API more follow a "crash early" strategy, or an "error forgiving" strategy? This depends on the usage environment and the usage scenarios of your API. Generally, (developing mainly desktop apps) I prefer "crash early", but sometimes it is better to tolerate some kind of errors to make the usage of an API more smooth. The requirements, for example, in embbeded apps or server apps may be different. Perhaps you discuss this with one of your potential API users?

For a "crash early" strategy, use (2), but forbid adding the same listener twice, throw an exeption if a listener is added again. Also throw an exception if one tries to remove a listener not in the list.

If you think an "error forgiving" strategy is more appropriate in your case, you could either

ignore the double adding of the same listener to the list - which is option (1) -, or

append it to the list like in (2), so it will be called twice when the events are fired

or you append it, but don't call the same listener twice in case of event-triggering

Note that the listener removal should correspond to that - if you ignore double adding, you should also ignore double removal. If you allow the same listener to be added twice, it should be clear which of the two listener entries is going to be removed when one calls removeListener(foo). The last of the three bullets is most probably the least error-prone approach among those suggestions, so in case of an "error forgiving" strategy, I would go with that.


答:
If you've got some events which you're running into problems with managing the add/removes, I would start adding IDs.

Add a listener returns an ID, the class that added it keeps track of the ID's for the listeners it's added and when it needs to remove them, it calls remove listener with that/those unique ID(s).

This puts the consumers in control so that they can get compliance with Principle of Least Astonishment in the behaviour.

This means adding the same one twice adds it twice, gives a different ID for each one, and removal by ID removes only the one associated with that ID. Anyone consuming the API would expect this behaviour when they saw the sigs.

A further addition in violation of YAGNI would be a GetIds where you hand it a listener and it returns a list of IDs associated with that listener if it is capable of getting appropriate equality checks, though that is dependent on your language: is it reference equality, type equality, value equality, etc? you have to be careful here because you may return IDs which that consumer should not be removing or meddling with, therefore this exposure get's dangerous and is ill-advised and should be unnecessary, but GetIDs is a possible addenda if you're feeling lucky.

Title: event listener pattern in api - what should adding the same listener twice do?

Body:
In designing an API that provides an event listening interface, it seems there are two conflicting ways of treating calls to add/remove listeners:

Multiple calls to addListener will only add a single listener (like adding it to a set); can be removed with a single call to removeListener.

Multiple calls to addListener will add a listener each time (like adding it to a list); must be balanced by multiple calls to removeListener.

I've found an example of each: (1) - The DOM addEventListener call in browsers only adds listeners once, silently ignoring requests to add the same listener a second time and (2) - jQuery .on behaviour adds listeners multiple times.

Most other listener APIs seem to use (2), such as SWT and Swing event listeners.  If (1) is chosen, there's also the question of whether it should fail silently or with an error when there is a request to add the same listener twice.

In my implementations, I tend to stick with (2) since it provides a cleaner setup/teardown type interface and reveals bugs where 'setup' is unintentionally being done twice, and is consistent with most implementations I've seen.

This leads me to my question - Is there a particular architecture or other underlying design that lends itself better to the other implementation?  (ie: why does the other pattern exist?)


答:
Okay, let's assume multiplication takes  time as m0nhawk suggests.

We have to define a recursive time equation:

If you resolve this equation, you will get:

This is basically:

where k is n-1 and therefore:

But if you assume that multiplication takes constant time, O(n) is the correct runtime approximation.

Title: Finding the time complexity of the following program that uses recursion

Body:
I need to find the time complexity in terms of Big Oh notation for the following program which computes the factorial of a given number: The program goes like this:

```<code>public int fact(int n){

  if (n <=1)
    return 1;
  else
  return n * fact (n-1);
}
</code>```

I know that the above program uses recursion but how to derive the time complexity for the above program?


问:
Alternatives to the repository pattern for encapsulating ORM logic?
I've just had to switch out an ORM and it was a relatively daunting task, because the query logic was leaking everywhere. If i'd ever had to develop a new application, my personal preference would be to encapsulate all query logic (using an ORM) to futureproof it for change. Repository pattern is quite troublesome to code and maintain so i was wondering if there are any other patterns to solve the problem ?

I can foresee posts about not adding extra complexity before it's actually needed, being agile etc. but i'm only interested about the existing patterns solving a similar problem in a simpler way.

My first thought was to have a generic type repository, to which i add methods as needed to specific type repository classes via extension methods, but unit testing static methods is awfully painful. IE:

```<code>public static class PersonExtensions
{
    public static IEnumerable<Person> GetRetiredPeople(this IRepository<Person> personRep)
    {
        // logic
    }
}
</code>```

答:
The problem with the leaky implementation is that you need many different filter conditions.

You can narrow this api if you implement a repository method FindByExample and use it like this

```<code>// find all retired persons
Person filter = new Person {Status=PersonStatus.Retired};
IEnumerable<Person> found = personRepository.FindByExample(filter);

// find all persons who have a dog named "sam"
Person filter = new Person();
filter.AddPet(new Dog{Name="sam"});
IEnumerable<Person> found = personRepository.FindByExample(filter);
</code>```

Body:
The problem with the leaky implementation is that you need many different filter conditions.

You can narrow this api if you implement a repository method FindByExample and use it like this

// find all retired persons
Person filter = new Person {Status=PersonStatus.Retired};
IEnumerable<Person> found = personRepository.FindByExample(filter);

// find all persons who have a dog named "sam"
Person filter = new Person();
filter.AddPet(new Dog{Name="sam"});
IEnumerable<Person> found = personRepository.FindByExample(filter);


问:
Testing UI for azure web app on iPad
I am working on debugging my mobile application.  There is a specific requirement/issue that I am having related to a drag and drop touch interface on an iPad.  I am at the trial and error phase of trying to figure out how to fix this (meaning I have no idea how to fix the issue I'm seeing).

The only way I have been able to figure out how to test my app on a mobile device is to deploy it to my azure test instance because the azure compute emulator always runs sites under 127.0.0.1.  This is really annoying since each deploy to azure takes 10+ minutes.

So my question is, how the heck to people do mobile development on this platform?    I've have found some people suggesting I could set up a reverse proxy using fiddler to allow remote connections but so far I haven't been able to get this to work.  Is there some sweet ios simulator that I haven't been able to find?  Am I missing something?

答:
I'm not familiar specifically with the azure compute emulator, however setting up a reverse proxy should be fairly straightforward.
I would suggest using nginx, you're config file should be this:

```<code> server {
    listen 80;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }
</code>```

*the proxy_pass should go to whatever port the emulator is running on

Ubuntu Install:
sudo apt-get install nginx

Windows Install:
http://nginx.org/en/docs/windows.html

Title: Testing UI for azure web app on iPad

Body:
I'm not familiar specifically with the azure compute emulator, however setting up a reverse proxy should be fairly straightforward.
I would suggest using nginx, you're config file should be this:

 server {
    listen 80;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }

*the proxy_pass should go to whatever port the emulator is running on

Ubuntu Install:
sudo apt-get install nginx

Windows Install:
http://nginx.org/en/docs/windows.html