答:
LIFO vs FIFO

LIFO stands for Last In, First Out. As in, the Last item put Into the stack is the First item taken out of the stack.

What you described with your dishes analogy (in the first revision), is a queue or FIFO, First In, First Out.

The major difference between the two, being that the LIFO/stack pushes (inserts) and pops (removes) from the same end, and a FIFO/queue does so from opposite ends.

```<code>// Both:

Push(a)
-> [a]
Push(b)
-> [a, b]
Push(c)
-> [a, b, c]

// Stack            // Queue
Pop()               Pop()
-> [a, b]           -> [b, c]
</code>```

The stack pointer

Let's take a look at what's happening under the hood of the stack.
Here's some memory, each box is an address:

```<code>...[ ][ ][ ][ ]...                       char* sp;
    ^- Stack Pointer (SP)
</code>```

And there's a stack pointer pointing at the bottom of the currently empty stack (whether the stack grows up or grows down isn't particularly relevant here so we'll ignore that, but of course in the real world, that does determine which operation adds, and which subtracts from the SP).

So let's push a, b, and c again. Graphics on the left, "high level" operation in the middle, C-ish pseudo code on the right:

```<code>...[a][ ][ ][ ]...        Push('a')      *sp = 'a';
    ^- SP
...[a][ ][ ][ ]...                       ++sp;
       ^- SP

...[a][b][ ][ ]...        Push('b')      *sp = 'b';
       ^- SP
...[a][b][ ][ ]...                       ++sp;
          ^- SP

...[a][b][c][ ]...        Push('c')      *sp = 'c';
          ^- SP
...[a][b][c][ ]...                       ++sp;
             ^- SP
</code>```

As you can see, each time we push, it inserts the argument in the location the stack pointer is currently pointing, and adjusts the stack pointer to point at the next location.

Now let's pop:

```<code>...[a][b][c][ ]...        Pop()          --sp;
          ^- SP
...[a][b][c][ ]...                       return *sp; // returns 'c'
          ^- SP
...[a][b][c][ ]...        Pop()          --sp;
       ^- SP
...[a][b][c][ ]...                       return *sp; // returns 'b'
       ^- SP
</code>```

Pop is the opposite of push, it adjusts the stack pointer to point at the previous location and removes the item that was there (usually to return it to whoever called pop).

You probably noticed that b and c are still in memory. I just want to assure you that those are not typos. We'll return to that shortly.

Life without a stack pointer

Let's see what happens if we don't have a stack pointer. Starting with pushing again:

```<code>...[ ][ ][ ][ ]...
...[ ][ ][ ][ ]...        Push(a)        ? = 'a';
</code>```

Er, hmm... if we don't have a stack pointer, then we can't move something to the address it points to. Maybe we can use a pointer that points to the base instead of the top.

```<code>...[ ][ ][ ][ ]...                       char* bp; // "base pointer"
    ^- bp                                bp = malloc(...);

...[a][ ][ ][ ]...        Push(a)        *bp = 'a';
    ^- bp
// No stack pointer, so no need to update it.
...[b][ ][ ][ ]...        Push(b)        *bp = 'b';
    ^- bp
</code>```

Uh oh. Since we can't change the fixed value of the stack's base, we just overwrote the a by pushing b to the same location.

Well, why don't we keep track of how many times we've pushed. And we'll also need to keep track of the times we've popped.

```<code>...[ ][ ][ ][ ]...                       char* bp; // "base pointer"
    ^- bp                                bp = malloc(...);
                                         int count = 0;

...[a][ ][ ][ ]...        Push(a)        bp[count] = 'a';
    ^- bp
...[a][ ][ ][ ]...                       ++count;
    ^- bp
...[a][b][ ][ ]...        Push(a)        bp[count] = 'b';
    ^- bp
...[a][b][ ][ ]...                       ++count;
    ^- bp
...[a][b][ ][ ]...        Pop()          --count;
    ^- bp
...[a][b][ ][ ]...                       return bp[count]; //returns b
    ^- bp
</code>```

Well it works, but it's actually pretty similar to before, except *pointer is cheaper than pointer[offset] (no extra arithmetic), not to mention it's less to type. This seem like a loss to me.

Let's try again. Instead of using the Pascal string style of finding the end of an array-based collection (tracking how many items are in the collection), let's try the C string style (scan from the beginning to the end):

```<code>...[ ][ ][ ][ ]...                       char* bp; // "base pointer"
    ^- bp                                bp = malloc(...);

...[ ][ ][ ][ ]...        Push(a)        char* top = bp;
    ^- bp, top
                                         while(*top != 0) { ++top; }
...[ ][ ][ ][a]...                       *top = 'a';
    ^- bp    ^- top

...[ ][ ][ ][ ]...        Pop()          char* top = bp;
    ^- bp, top
                                         while(*top != 0) { ++top; }
...[ ][ ][ ][a]...                       --top;
    ^- bp       ^- top                   return *top; // returns '('
</code>```

You may have already guessed the problem here. Uninitialized memory is not guaranteed to be 0. So when we look for the top to place a, we end up skipping over a bunch of unused memory location that have random garbage in them. Similarly, when we scan to the top, we end up skipping well beyond the a we just pushed until we finally find another memory location that just happens to be 0, and move back and return the random garbage just before that.

That's easy enough to fix, we just have to add operations to Push and Pop to make sure the top of the stack is always updated to be marked with a 0, and we have to initialize the stack with such a terminator. Of course that also means we can't have a 0 (or whatever value we pick as a terminator) as an actually value in the stack.

On top of that, we've also changed what were O(1) operations into O(n) operations.

TL;DR

The stack pointer keeps track of the top of the stack, where all of the action occurs. There are ways to sort of get rid of it (bp[count] and top are essentially still the stack pointer), but they both end up being more complicated and slower than simply having the stack pointer. And not knowing where the top of the stack is means you can't use the stack.

Note: The stack pointer pointing to the "bottom" of the runtime stack in x86 might be a misconception related to the entire runtime stack being upside down. In other words, the base of the stack is placed at a high memory address, and the tip of the stack grows down into lower memory addresses. The stack pointer does point to the tip of the stack where all the action occurs, just that tip is at a lower memory address than the base of the stack.

Body:
LIFO vs FIFO

LIFO stands for Last In, First Out. As in, the Last item put Into the stack is the First item taken out of the stack.

What you described with your dishes analogy (in the first revision), is a queue or FIFO, First In, First Out.

The major difference between the two, being that the LIFO/stack pushes (inserts) and pops (removes) from the same end, and a FIFO/queue does so from opposite ends.

// Both:

Push(a)
-> [a]
Push(b)
-> [a, b]
Push(c)
-> [a, b, c]

// Stack            // Queue
Pop()               Pop()
-> [a, b]           -> [b, c]

The stack pointer

Let's take a look at what's happening under the hood of the stack.
Here's some memory, each box is an address:

...[ ][ ][ ][ ]...                       char* sp;
    ^- Stack Pointer (SP)

And there's a stack pointer pointing at the bottom of the currently empty stack (whether the stack grows up or grows down isn't particularly relevant here so we'll ignore that, but of course in the real world, that does determine which operation adds, and which subtracts from the SP).

So let's push a, b, and c again. Graphics on the left, "high level" operation in the middle, C-ish pseudo code on the right:

...[a][ ][ ][ ]...        Push('a')      *sp = 'a';
    ^- SP
...[a][ ][ ][ ]...                       ++sp;
       ^- SP

...[a][b][ ][ ]...        Push('b')      *sp = 'b';
       ^- SP
...[a][b][ ][ ]...                       ++sp;
          ^- SP

...[a][b][c][ ]...        Push('c')      *sp = 'c';
          ^- SP
...[a][b][c][ ]...                       ++sp;
             ^- SP

As you can see, each time we push, it inserts the argument in the location the stack pointer is currently pointing, and adjusts the stack pointer to point at the next location.

Now let's pop:

...[a][b][c][ ]...        Pop()          --sp;
          ^- SP
...[a][b][c][ ]...                       return *sp; // returns 'c'
          ^- SP
...[a][b][c][ ]...        Pop()          --sp;
       ^- SP
...[a][b][c][ ]...                       return *sp; // returns 'b'
       ^- SP

Pop is the opposite of push, it adjusts the stack pointer to point at the previous location and removes the item that was there (usually to return it to whoever called pop).

You probably noticed that b and c are still in memory. I just want to assure you that those are not typos. We'll return to that shortly.

Life without a stack pointer

Let's see what happens if we don't have a stack pointer. Starting with pushing again:

...[ ][ ][ ][ ]...
...[ ][ ][ ][ ]...        Push(a)        ? = 'a';

Er, hmm... if we don't have a stack pointer, then we can't move something to the address it points to. Maybe we can use a pointer that points to the base instead of the top.

...[ ][ ][ ][ ]...                       char* bp; // "base pointer"
    ^- bp                                bp = malloc(...);

...[a][ ][ ][ ]...        Push(a)        *bp = 'a';
    ^- bp
// No stack pointer, so no need to update it.
...[b][ ][ ][ ]...        Push(b)        *bp = 'b';
    ^- bp

Uh oh. Since we can't change the fixed value of the stack's base, we just overwrote the a by pushing b to the same location.

Well, why don't we keep track of how many times we've pushed. And we'll also need to keep track of the times we've popped.

...[ ][ ][ ][ ]...                       char* bp; // "base pointer"
    ^- bp                                bp = malloc(...);
                                         int count = 0;

...[a][ ][ ][ ]...        Push(a)        bp[count] = 'a';
    ^- bp
...[a][ ][ ][ ]...                       ++count;
    ^- bp
...[a][b][ ][ ]...        Push(a)        bp[count] = 'b';
    ^- bp
...[a][b][ ][ ]...                       ++count;
    ^- bp
...[a][b][ ][ ]...        Pop()          --count;
    ^- bp
...[a][b][ ][ ]...                       return bp[count]; //returns b
    ^- bp

Well it works, but it's actually pretty similar to before, except *pointer is cheaper than pointer[offset] (no extra arithmetic), not to mention it's less to type. This seem like a loss to me.

Let's try again. Instead of using the Pascal string style of finding the end of an array-based collection (tracking how many items are in the collection), let's try the C string style (scan from the beginning to the end):

...[ ][ ][ ][ ]...                       char* bp; // "base pointer"
    ^- bp                                bp = malloc(...);

...[ ][ ][ ][ ]...        Push(a)        char* top = bp;
    ^- bp, top
                                         while(*top != 0) { ++top; }
...[ ][ ][ ][a]...                       *top = 'a';
    ^- bp    ^- top

...[ ][ ][ ][ ]...        Pop()          char* top = bp;
    ^- bp, top
                                         while(*top != 0) { ++top; }
...[ ][ ][ ][a]...                       --top;
    ^- bp       ^- top                   return *top; // returns '('

You may have already guessed the problem here. Uninitialized memory is not guaranteed to be 0. So when we look for the top to place a, we end up skipping over a bunch of unused memory location that have random garbage in them. Similarly, when we scan to the top, we end up skipping well beyond the a we just pushed until we finally find another memory location that just happens to be 0, and move back and return the random garbage just before that.

That's easy enough to fix, we just have to add operations to Push and Pop to make sure the top of the stack is always updated to be marked with a 0, and we have to initialize the stack with such a terminator. Of course that also means we can't have a 0 (or whatever value we pick as a terminator) as an actually value in the stack.

On top of that, we've also changed what were O(1) operations into O(n) operations.

TL;DR

The stack pointer keeps track of the top of the stack, where all of the action occurs. There are ways to sort of get rid of it (bp[count] and top are essentially still the stack pointer), but they both end up being more complicated and slower than simply having the stack pointer. And not knowing where the top of the stack is means you can't use the stack.

Note: The stack pointer pointing to the "bottom" of the runtime stack in x86 might be a misconception related to the entire runtime stack being upside down. In other words, the base of the stack is placed at a high memory address, and the tip of the stack grows down into lower memory addresses. The stack pointer does point to the tip of the stack where all the action occurs, just that tip is at a lower memory address than the base of the stack.


问:
I understand what a stack pointer is - but what is it used for?
The stack pointer points to the top of the stack, which stores data on what we call a "LIFO" basis. To steal someone else's analogy, it's like a stack of dishes in which you put and take dishes at the top. The stack pointer, OTOH, points to the top "dish" of the stack. At least, that's true for x86.

But why does the computer/program "care" what the stack pointer's pointing to? In other words, what purpose does having the stack pointer and knowing where it points to serve?

An explanation understandable by C programmers would be appreciated.

答:
What purpose does this stack actually serve, as opposed to explaining its structure?

You have many answers which accurately describe the structure of the data stored on the stack, which I note is the opposite of the question you asked.

The purpose that the stack serves is: the stack is part of the reification of continuation in a language without coroutines.

Let's unpack that.

Continuation is simply put, the answer to the question "what is going to happen next in my program?"  At every point in every program something is going to happen next. Two operands are going to be computed, then the program continues by computing their sum, and then the program continues by assigning the sum to a variable, and then... and so on.

Reification is just a highfalutin word for making a concrete implementation of an abstract concept. "What happens next?" is an abstract concept; the way the stack is laid out is a part of how that abstract concept is turned into a real machine that really computes things.

Coroutines are functions that can remember where they were, yield control to another coroutine for a while, and then resume where they left off later, but not necessarily immediately after the just-called coroutine yields. Think of "yield return" or "await" in C#, which must remember where they were when the next item is requested or the asynchronous operation completes.  Languages with coroutines or similar language features require more advanced data structures than a stack in order to implement continuation.

How does a stack implement continuation?  Other answers say how. The stack stores (1) values of variables and temporaries whose lifetimes are known to be not greater than the activation of the current method, and (2) the address of the continuation code associated with the most recent method activation. In languages with exception handling the stack may also store information about the "error continuation" -- that is, what the program will do next when an exceptional situation occurs.

Let me take this opportunity to note that the stack does not tell you "where did I come from?" -- though it is often so used in debugging. The stack tells you where you are going to next, and what the values of the activation's variables will be when you get there. The fact that in a language without coroutines, where you are going next is almost always where you came from makes this kind of debugging easier. But there is no requirement that a compiler store information about where control came from if it can get away without doing so. Tail-call optimizations for example destroy information about where the program control came from.

Why do we use the stack to implement continuation in languages without coroutines? Because the characteristic of synchronous activation of methods is that the pattern of "suspend the current method, activate another method, resume the current method knowing the result of the activated method" when composed with itself logically forms a stack of activations. Making a data structure that implements this stack-like behaviour is very cheap and easy. Why is it so cheap and easy? Because chip sets have been for many decades specifically designed to make this sort of programming easy for compiler writers.

ContentLicense: CC BY-SA 3.0


问:
Comparison of Red/Black Tree to Java ArrayList, what are advantages of each?
I was looking over some of the general Big-O Algorithm Complexities for different data structures, and wondered what Java's ArrayList would be considered.

Since I tend to default to an ArrayList in my Java code when I need a List (unless I know I need some additional functionality), I was wondering what advantages there would be if I used an implementation (assume well-implemented) of a Red-Black Tree instead.

Since ArrayList is backed by an Array, I would assume that it would be considered either an Array or a Singly-Linked List according to the linked website. If that is true, it would appear that a Red-Black Tree implementation might a better "default" data structure to use.

What would be the advantages/disadvantages of using a Red-Black Tree instead of the ArrayList? (and minor accompanying question, what would ArrayList be considered in the Algorithm Complexities website?)

答:
Since this is about Java, it is worth separating the interfaces from the implementations in its Collections framework.

ArrayList and LinkedList are both types of List. A List is an ordered collection referenced by arbitrary index (i.e. the index is not a property of the data being stored). ArrayList is backed by an array, which is sequence, random-access storage. These are really good when you need to access random elements and are not inserting in the middle: ArrayList supports this operation, but it is potentially slow.

TreeMap and TreeSet are types of Map and Set (and the Sets delegate to the Trees, so the differences in practice are nil). These objects are referenced by some property (key) which is an arbitrary object: for a map it can be anything you want (typically a string), for a set it is the element itself. These are ordered collections, meaning elements in the tree are ordered either by the natural ordering of the elements or by some other criteria (this is what the Comparator interface is used for).

So the differences are:

Access: by index for the list, by key or element for the tree.

Mutation: both are ordered, but a list is in any arbitrary order while the tree resorts itself as you insert elements.

You would use a list when you don't need to access elements by a key, you just need a bunch of objects or you need them in a particular order that is not their natural ordering. You would use a tree (or hashtable) when you want a key/value store similar to retrieving records from a database by primary key.


问:
Sorting an array based on another array's order, quickly
There are two arrays of maps. The first array contains maps of ID values in a specific order (but not necessarily either pure ASC or DESC ordering):

```<code>// pseudo code
first := [
    {"id": 1},
    {"id": 2},
    {"id": 3}
]
</code>```

...and an unsorted array of data with corresponding ID values, but not in the same ordering:

```<code>second := [
    {"id": 3, "text": "hello"},
    {"id": 1, "text": "fizz"},
    {"id": 2, "text": "bar"}
]
</code>```

How can I sort the second array such that its maps are in the same order as the first array via the matching ID values, while achieving the fastest code execution as possible?

(Note that the ordering of the first array is not known before runtime.)

The desired result in this case would be:

```<code>desiredResult := [
    {"id": 1, "text": "fizz"},
    {"id": 2, "text": "bar"},
    {"id": 3, "text": "hello"}
]
</code>```

答:
I'm going to assume that in the general case these ids might be strings and might be in a non-natural order in both first and second, since otherwise the trivial solutions suggested in the comments would be adequate.

One obvious solution is to walk through the lists linearly, rearranging the second array's elements along the way.

I assume this means that for each element in first, you do a linear search in second for the corresponding element and then insert it into the right position in result. This would be an O(n^2) algorithm.

I believe you can do this in O(n) by converting first into a map from id to index. So, assuming we start with this (I'll write Javascript since I'm better at that language, but I assume this works in Go too):

```<code>var first = [
  { "id": "biz" },
  { "id": "qux" },
  { "id": "foo" }
]

var second = [
  { "id": "foo", "text": "dabra" },
  { "id": "biz", "text": "abra" },
  { "id": "qux", "text": "ca" }
]
</code>```

I would iterate over first to construct this map from ids to positions in the final array:

```<code>var idToPositionMap = {
  "biz": 0,
  "qux": 1,
  "foo": 2
}
</code>```

Then I would iterate over second, using lookups in that map to insert items into the the result array:

```<code>second.map(function(item) {
   result[idToPositionMap[item.id]] = item;
});
</code>```

Both of these steps should be O(n), assuming keyed lookup is O(1) and iterating over an array is O(n), like they should be, so total time is O(2n) = O(n).

I'm fairly sure O(n) is the best time complexity you can possibly get for this operation, since you need to touch every element of each array, so any further optimization would have to involve language-specific details and probably a lot of profiling.

Body:
I'm going to assume that in the general case these ids might be strings and might be in a non-natural order in both first and second, since otherwise the trivial solutions suggested in the comments would be adequate.

One obvious solution is to walk through the lists linearly, rearranging the second array's elements along the way.

I assume this means that for each element in first, you do a linear search in second for the corresponding element and then insert it into the right position in result. This would be an O(n^2) algorithm.

I believe you can do this in O(n) by converting first into a map from id to index. So, assuming we start with this (I'll write Javascript since I'm better at that language, but I assume this works in Go too):

var first = [
  { "id": "biz" },
  { "id": "qux" },
  { "id": "foo" }
]

var second = [
  { "id": "foo", "text": "dabra" },
  { "id": "biz", "text": "abra" },
  { "id": "qux", "text": "ca" }
]

I would iterate over first to construct this map from ids to positions in the final array:

var idToPositionMap = {
  "biz": 0,
  "qux": 1,
  "foo": 2
}

Then I would iterate over second, using lookups in that map to insert items into the the result array:

second.map(function(item) {
   result[idToPositionMap[item.id]] = item;
});

Both of these steps should be O(n), assuming keyed lookup is O(1) and iterating over an array is O(n), like they should be, so total time is O(2n) = O(n).

I'm fairly sure O(n) is the best time complexity you can possibly get for this operation, since you need to touch every element of each array, so any further optimization would have to involve language-specific details and probably a lot of profiling.


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答:
For Android, here are some fun ones:

Hackers, developers and tinkerers

Cyanogen - @cyanogen

XDA Developers - @xdadevelopers

simms22 - @simms22

Koush - code writer - @koush

Kmobs - @kmobs

Chris Soyars - @chrissoyars

Bignup412 - @bignup412

Franco Solari - @francoissmexy

Sumyunguy - @sumyunguy

CyanogenMod Source - @cmsrc

Ander Webbs - @anderwebs

CyanogenMod - @cyanogenmod

Prashant Somashekar, Droid Basement - @pershoot

San Mehat, Android Kernal Systems Dev - @sanmehat

Bart, Android freak - @amon_ra

Tord Fauksganger - @tordf

Greg Carron, developer - @pixeladdikt

Kyle Weller - @androidunleashd

Wes Garner - @wesgarner

Source on Engadget: Who should I follow on Twitter? Android edition

ContentLicense: CC BY-SA 2.5


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: Work from home. When I have a tough deadline and I need to focus completely on a problem, I tell my boss that I am working from home. This lets me set up my environment optimally, reduces interruptions, and lets me focus like a laser beam on the problem.</p>

OwnerDisplayName: Nick Gotch

Title: How to become a "faster" programmer?

OwnerDisplayName: Pedro Estrada


问:
At what volume is a specific data structure considered useful
I had this discussion with co-workers before. We had to store users by id and we'd do mostly Add/Get operations on it. I proposed to use a Dictionary which seems like the logical choice. My co-worker argued that the Dictionary was pointless in that case because we didn't have many users (Maybe 150).

I proposed the dictionary because I know, in theory, that it's the best data structure for this scenario. In the case where I have 150 users (that's an arbitrary number), is there really a performance difference between the O(1) access of a Dictionary and the O(n) access of a List?

He proposed the List because the Dictionary seemed useless in that case.

We ended up using the Dictionary because if the application was to grow, we'd have more users and the Dictionary would prove useful.

Though the question remained, are there scenarios where we shouldn't consider which data structures to use?

答:
Aside from performance, you should also consider the principle of least surprise for future programmers: if lookup is being done by item rather than by index, but a list is being used, this is a surprising design choice and if I'm reading the code, it leads me to waste time to figure out why it's implemented in this way.

I might think: "Does it need to be ordered somewhere?" "Is it being sorted?" "Was it meant to be ordered but that wasn't implemented yet? Was it supposed to be implemented but the dev forgot to do that?".

In other words it increases the wtf/per minute rate, which is one way to measure quality of code.


答:
Modern programming languages, as you well know, support the concept of subroutine calls (most often called "function calls").  This means that:

In the middle of some code, you can call some other function in your program;

That function doesn't explicitly know where it was called from;

Nevertheless, when its work is done and it returns, control goes back to the exact point where the call was initiated, with all the local variable values in effect as when the call was initiated.

How does the computer keep track of that?  It maintains an ongoing record of which functions are waiting for which calls to return.  This record is a stack—and since it's such an important one, we normally call it the stack.

And since this call/return pattern is so important, CPUs have long been designed to provide special hardware support for it.  The stack pointer is a hardware feature in CPUs—a register that's exclusively dedicated to keeping track of the top of the stack, and used by the CPU's instructions for branching into a subroutine and returning from it.

Title: I understand what a stack pointer is - but what is it used for?

Body:
The stack pointer points to the top of the stack, which stores data on what we call a "LIFO" basis. To steal someone else's analogy, it's like a stack of dishes in which you put and take dishes at the top. The stack pointer, OTOH, points to the top "dish" of the stack. At least, that's true for x86.

But why does the computer/program "care" what the stack pointer's pointing to? In other words, what purpose does having the stack pointer and knowing where it points to serve?

An explanation understandable by C programmers would be appreciated.


答:
Become a faster programmer by slowing down when you are designing and coding.

Think about what you are doing.

Consider the implications of your design.

Get it right the first time (test your own code vigorously).

It might feel slower, but your throughput will be faster than those code jockeys who turn an iteration in 4 hours, and then need 6 rounds of QA before their code passes.

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: mmc


问:
Webservices vs Microservices
In our org , we have soap & rest based services that have focused set of responsibilities. For instance , there is customer service for managing customer info , account service for managing account info etc. Is there any advantage of making them microservices? If it has to be converted to a microservice , what typically has to be done?

When I read about microservices , it is primarily being compared with monolithic apps. But in all the large companies that I have worked over the past 5-6 yrs , I have always seen things implemented as webservices. I don't see many examples of why microservice is advantageous over rest based service.

答:
Are your web services individually deployable? Individually scalable? Individually monitored?

Microservices are just more granular (and decoupled) varieties of the web services most places have to provide a little more control on the Ops side of the world. Is that useful for you? Maybe. Maybe not. Different solutions have different needs, and if your scaling needs don't vary in their shape or magnitude, it might provide little benefit.

Title: Webservices vs Microservices


问:
In x86, where are the memory addresses of the values on the stack located?
Suppose I have a very simple C program that just does this:

```<code>int i = 6;
int j = 4;
int k = 5;
int a = i + j + k;
</code>```

Since i, j, and k are on the stack, they will be located relative to the stack pointer. I am told the compiler determines these relative locations; my guess is the compiler translates int a = i + j + k into "Add the values located at (stack pointer - 3x), (stack pointer - 2x), and (stack pointer - x) and push the result to the stack." Am I correct?

答:
It depends upon the C compiler, as the specification leaves this up to the compiler implementer. (There are specific requirements, though -- such as if you take the address of a parameter -- which may further constrain the compiler implementer.)

A typical C function generates some "prologue" code, the "body" code, and some "epilogue" code. The prologue will allocate local variable space. In general, a compiler will NOT go through the process you outlined. So let's say we are talking about 16-bit x86 code and about this function in C:

```<code>int f( void ) {
    int i = 6;
    int j = 4;
    int k = 5;
    int a = i + j + k;
    return a;
}
</code>```

Note that in the context I mentioned, the variables will be 2 bytes in size. The compiler will count the number of bytes required for all of the local variables. In this case, you have four of them and since they require 2 bytes each, the compiler "computes" that 8 bytes are required for all of this. (Also note that even if you include variable definitions inside of additional code blocks within the above C function, the C compiler will count ALL OF THEM AT ONCE. It doesn't just count those defined at the outer level.) So the compiler might generate the following prologue in assembly:

```<code>push bp
mov bp, sp
sub sp, 8
</code>```

Usually, the BP register is used as a "frame pointer" for the current context of the function. BP is also known as the pointer to the "activation frame." So the C compiler needs two instructions to save the old activation frame pointer on the stack and to then initialize it to point to the current one for this invocation of the function.

The third instruction is simple and allocates ALL of the necessary space for the 8 bytes needed for ALL of the local variables. It simply moves the stack pointer over the needed 8 bytes. BP will still point at the base of this activation frame. But the SP now is at the other side of that, so additional pushes and calls won't write over the local variables.

The C compiler will also internally assign some offset value for each of the local variables. Perhaps something like IVAR=0, JVAR=2, KVAR=4, and AVAR=6. Now, the C compiler needs to create some BODY code. Because you set these local variable values, something like this (completely un-optimized):

```<code>mov IVAR[BP], 6
mov JVAR[BP], 4
mov KVAR[BP], 5
mov ax, IVAR[BP]
add ax, JVAR[BP]
add ax, KVAR[BP]
</code>```

Note that in this 16-bit context, it's also common for the return value of a function to be placed into AX, if it fits there. In this case, it does. So the answer is already in the right place at this time. So now an epilogue is required:

```<code>mov sp, bp
pop bp
ret
</code>```

And that's it.

Now, an optimizer will do a GREAT DEAL to improve the above code in this case. It will probably completely remove ALL of the local variables, as they aren't needed at all. It can pre-compute the entire result as 15 and just do the following:

```<code>mov ax, 15
ret
</code>```

No need to manage the activation frame, at all. Just return the value. (But then you wouldn't get any idea about how the local variables might be managed.)

Hope that helps a little.

Body:
It depends upon the C compiler, as the specification leaves this up to the compiler implementer. (There are specific requirements, though -- such as if you take the address of a parameter -- which may further constrain the compiler implementer.)

A typical C function generates some "prologue" code, the "body" code, and some "epilogue" code. The prologue will allocate local variable space. In general, a compiler will NOT go through the process you outlined. So let's say we are talking about 16-bit x86 code and about this function in C:

int f( void ) {
    int i = 6;
    int j = 4;
    int k = 5;
    int a = i + j + k;
    return a;
}

Note that in the context I mentioned, the variables will be 2 bytes in size. The compiler will count the number of bytes required for all of the local variables. In this case, you have four of them and since they require 2 bytes each, the compiler "computes" that 8 bytes are required for all of this. (Also note that even if you include variable definitions inside of additional code blocks within the above C function, the C compiler will count ALL OF THEM AT ONCE. It doesn't just count those defined at the outer level.) So the compiler might generate the following prologue in assembly:

push bp
mov bp, sp
sub sp, 8

Usually, the BP register is used as a "frame pointer" for the current context of the function. BP is also known as the pointer to the "activation frame." So the C compiler needs two instructions to save the old activation frame pointer on the stack and to then initialize it to point to the current one for this invocation of the function.

The third instruction is simple and allocates ALL of the necessary space for the 8 bytes needed for ALL of the local variables. It simply moves the stack pointer over the needed 8 bytes. BP will still point at the base of this activation frame. But the SP now is at the other side of that, so additional pushes and calls won't write over the local variables.

The C compiler will also internally assign some offset value for each of the local variables. Perhaps something like IVAR=0, JVAR=2, KVAR=4, and AVAR=6. Now, the C compiler needs to create some BODY code. Because you set these local variable values, something like this (completely un-optimized):

mov IVAR[BP], 6
mov JVAR[BP], 4
mov KVAR[BP], 5
mov ax, IVAR[BP]
add ax, JVAR[BP]
add ax, KVAR[BP]

Note that in this 16-bit context, it's also common for the return value of a function to be placed into AX, if it fits there. In this case, it does. So the answer is already in the right place at this time. So now an epilogue is required:

mov sp, bp
pop bp
ret

And that's it.

Now, an optimizer will do a GREAT DEAL to improve the above code in this case. It will probably completely remove ALL of the local variables, as they aren't needed at all. It can pre-compute the entire result as 15 and just do the following:

mov ax, 15
ret

No need to manage the activation frame, at all. Just return the value. (But then you wouldn't get any idea about how the local variables might be managed.)

Hope that helps a little.


答:
Yes, you are correct.  The compiler never actually determines the exact memory locations, it only determines the relative offsets of these locations from the stack pointer. The value that the stack pointer will have during run-time is unknown to the compiler at compilation time.

(Actually, on 16-bit and 32-bit Intel architectures these locations are relative to the so-called "base pointer", (register BP, in other architectures known as "the frame pointer",) whose value is determined from the stack pointer, but that's irrelevant. They have fixed it in 64-bit and now only the stack pointer is necessary.)

Title: In x86, where are the memory addresses of the values on the stack located?

Body:
Suppose I have a very simple C program that just does this:

```<code>int i = 6;
int j = 4;
int k = 5;
int a = i + j + k;
</code>```

Since i, j, and k are on the stack, they will be located relative to the stack pointer. I am told the compiler determines these relative locations; my guess is the compiler translates int a = i + j + k into "Add the values located at (stack pointer - 3x), (stack pointer - 2x), and (stack pointer - x) and push the result to the stack." Am I correct?


答:
You'll get faster with experience and memorize the API a lot more.

My days of searching the web for fragments of code are a lot shorter now that I've learnt to code better.

Oh, you may also want to try using functional programming concepts and lamda to cut down your code :)

Title: How to become a "faster" programmer?

OwnerDisplayName: Vince


问:
How is defining that a method can be overridden a stronger commitment than defining that a method can be called?
From : http://www.artima.com/lejava/articles/designprinciples4.html

Erich Gamma: I still think it's true even after ten years. Inheritance is a cool way to change behavior. But we know that it's brittle, because the subclass can easily make assumptions about the context in which a method it overrides is getting called. There's a tight coupling between the base class and the subclass, because of the implicit context in which the subclass code I plug in will be called. Composition has a nicer property. The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called.

I don't understand what he means. Could anyone please explain it?

答:
Inheritance Weakens Encapsulation

When you publish an interface with inheritance permitted, you substantially increase the size of your interface. Each overrideable method could be replaced and so should be thought of as callback provided to the constructor. The implementation provided by your class is merely the default value of the callback. Thus, some kind of contract should be provided indicating what the expectations on the method are. This seldom happens and is a major reason why object oriented code is called brittle.

Below is a real (simplified) example from the java collections framework, courtesy of Peter Norvig (http://norvig.com/java-iaq.html).

```<code>Public Class HashTable{
    ...
    Public Object put(K key, V value){
        try{
            //add object to table;
        }catch(TableFullException e){
            increaseTableSize();
            put(key,value);
        }
    }
}
</code>```

So what happens if we subclass this?

```<code>/** A version of Hashtable that lets you do
 * table.put("dog", "canine");, and then have
 * table.get("dogs") return "canine". **/

public class HashtableWithPlurals extends Hashtable {

    /** Make the table map both key and key + "s" to value. **/
    public Object put(Object key, Object value) {
        super.put(key + "s", value);
        return super.put(key, value);
    }
}
</code>```

We have a bug: Occasionally we add "dog" and the hashtable gets an entry for "dogss". The cause was someone providing an implementation of put that the person designing the Hashtable class did not expect.

Inheritance Breaks Extensibility

If you allow your class to be subclassed, you are committing to not add any methods to your class. This could otherwise be done without breaking anything.

When you add new methods to an interface, anyone who has inherited from your class will need to implement those methods.

Body:
Inheritance Weakens Encapsulation

When you publish an interface with inheritance permitted, you substantially increase the size of your interface. Each overrideable method could be replaced and so should be thought of as callback provided to the constructor. The implementation provided by your class is merely the default value of the callback. Thus, some kind of contract should be provided indicating what the expectations on the method are. This seldom happens and is a major reason why object oriented code is called brittle.

Below is a real (simplified) example from the java collections framework, courtesy of Peter Norvig (http://norvig.com/java-iaq.html).

Public Class HashTable{
    ...
    Public Object put(K key, V value){
        try{
            //add object to table;
        }catch(TableFullException e){
            increaseTableSize();
            put(key,value);
        }
    }
}

So what happens if we subclass this?

/** A version of Hashtable that lets you do
 * table.put("dog", "canine");, and then have
 * table.get("dogs") return "canine". **/

public class HashtableWithPlurals extends Hashtable {

    /** Make the table map both key and key + "s" to value. **/
    public Object put(Object key, Object value) {
        super.put(key + "s", value);
        return super.put(key, value);
    }
}

We have a bug: Occasionally we add "dog" and the hashtable gets an entry for "dogss". The cause was someone providing an implementation of put that the person designing the Hashtable class did not expect.

Inheritance Breaks Extensibility

If you allow your class to be subclassed, you are committing to not add any methods to your class. This could otherwise be done without breaking anything.

When you add new methods to an interface, anyone who has inherited from your class will need to implement those methods.


答:
Martin Fowler defines Microservices as a subset of Service Oriented Architecture (SOA). It sounds like this is what you have potentially.

With the disclaimer that there isn't a commonly accepted single definition, a Web services is not the only form it could take. Communication could be over various protocols and be event oriented also.

I also believe that there's an engineering culture required to be successful with a Microservices architecture.

Title: Webservices vs Microservices

Body:
In our org , we have soap & rest based services that have focused set of responsibilities. For instance , there is customer service for managing customer info , account service for managing account info etc. Is there any advantage of making them microservices? If it has to be converted to a microservice , what typically has to be done?

When I read about microservices , it is primarily being compared with monolithic apps. But in all the large companies that I have worked over the past 5-6 yrs , I have always seen things implemented as webservices. I don't see many examples of why microservice is advantageous over rest based service.


答:
If a method is meant to be called, you only have to ensure it works correctly. That's it. Done.

If a method is designed to be overridden, you also have to think carefully about the scope of the method: if the scope is too large, child class will often need to include copy-pasted code from parent method; if it is too small, many methods will need to be overridden to have desired new functionality - this adds complexity and needless line count.

Therefore creator of parent method needs to make assumptions on how the class and its methods might be overridden in the future.

However, the author is talking about a different issue in the quoted text:

But we know that it's brittle, because the subclass can easily make
  assumptions about the context in which a method it overrides is
  getting called.

Consider method a which is being normally called from method b, but in some rare and non-obvious cases from method c. If author of overriding method overlooks the c method and its expectations on a, it's obvious how things can go wrong.

Therefore it's more important that a is defined clearly and unambiguously, well documented, "does one thing and does it well" -- more so than if it were a method only designed to be called.

Title: How is defining that a method can be overridden a stronger commitment than defining that a method can be called?

Body:
From : http://www.artima.com/lejava/articles/designprinciples4.html

Erich Gamma: I still think it's true even after ten years. Inheritance is a cool way to change behavior. But we know that it's brittle, because the subclass can easily make assumptions about the context in which a method it overrides is getting called. There's a tight coupling between the base class and the subclass, because of the implicit context in which the subclass code I plug in will be called. Composition has a nicer property. The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called.

I don't understand what he means. Could anyone please explain it?


问:
Object-Oriented design to create Images in Python
I'm creating images with centered text. I use Python but I'm faced with many question regarding how to write my class.
I know that

A class must aim to do one thing and do it well.

Well, the one thing I want to do with this class is print centered text on a background image but I think I need help to really understand this since I have many questions:

Should I write a class that have a method to create the background
image?

Should I have another method in the same class to put the text centered on the
background image?

And when do I save the image to disk? Should I
have another method to save the image?

If I'm correct, my class will look like this:

```<code># -*- coding: utf-8 -*-

class CreateImage():
    def create_background(self):
        print("Creating background")
    def print_text_image(self, text):
        print("Printing the following text on Image: ")
        print(text)
    def save(self, destination):
        print("Saving the image on disk on: ")
        print(destination)

my_object = CreateImage()
my_object.print_text_image("Hello World!")
my_object.save("Images/my_images")
~
</code>```

It does look fine to me. But the thing is that the print_text_image method  has to many responsibilities:

Calculate how much pixels on the image we can use (width*height)

Calculate how much pixels the text is going to use and if doesn't fit we reduce the font-size until it fits (trial&error)

Calculate margins and finally print the text on the image in a centered way

Looks to me that we can use at least one more method on my CreateImage class:

A method to calculate if the font size (text) is small enough to fit in the image (return true or false)

But I'm not sure. I do want to have a good design in my class because later I will use this class as a base for other classes (for example, another class will paste other images into the image that CreateImage creates.)

In definitive, what would be your design for this class? I will really appreciate if you take the time to help me understand this. Thank you so much in advance.

答:
Your quote is wrong.  It is wrong to say "a class should do one thing and do it well".  A class does not do anything.  Better to say "a class should be one thing and be that thing well".

"Create" is a verb.  "CreateImage" sounds like the name of a function, not a class.  A class should be the sort of thing you'd describe with a noun,  like "Image".

You can see the problem if you read off your methods.

```<code>CreateImage.Save()`
</code>```

What?  You are saving a createimage?  Does that make sense?

```<code>CreateImage.create_background()
</code>```

What?  You are create_backgrounding a CreateImage?  What the hell does that mean?

Let's rename:

```<code>class Image():
   def add_background(self):
      print("Addinging background")

   def add_text(self, text):
      print("Adding the following text to Image: ")
      print(text)

   def save(self, destination):
      print("Saving the image on disk on: ")
      print(destination)
</code>```

Now let's read:

```<code>Image.add_background
</code>```

Oh, well, obviously that adds a background to the image

```<code>Image.add_text
</code>```

Oh, well, obviously that adds text to an image

```<code>Image.save
</code>```

Oh, well, obviously that saves the image

So your class is just fine.  It's your naming that needs work.  If you name appropriately, you can often tell if your class makes sense if it reads naturally.

A class is a noun.  It is a thing you do stuff with.

A function/method is a verb.  It is a thing that does stuff with other things.  (Yes, in some languages a function is an object, but that's not so important when talking about design at this level.)

If you keep this in mind, and also keep in mind that in each case, a class should be a single conceptual thing, and a function should do a single conceptual thing, you'll be ok.

Body:
Your quote is wrong.  It is wrong to say "a class should do one thing and do it well".  A class does not do anything.  Better to say "a class should be one thing and be that thing well".

"Create" is a verb.  "CreateImage" sounds like the name of a function, not a class.  A class should be the sort of thing you'd describe with a noun,  like "Image".

You can see the problem if you read off your methods.

CreateImage.Save()`

What?  You are saving a createimage?  Does that make sense?

CreateImage.create_background()

What?  You are create_backgrounding a CreateImage?  What the hell does that mean?

Let's rename:

class Image():
   def add_background(self):
      print("Addinging background")

   def add_text(self, text):
      print("Adding the following text to Image: ")
      print(text)

   def save(self, destination):
      print("Saving the image on disk on: ")
      print(destination)

Now let's read:

Image.add_background

Oh, well, obviously that adds a background to the image

Image.add_text

Oh, well, obviously that adds text to an image

Image.save

Oh, well, obviously that saves the image

So your class is just fine.  It's your naming that needs work.  If you name appropriately, you can often tell if your class makes sense if it reads naturally.

A class is a noun.  It is a thing you do stuff with.

A function/method is a verb.  It is a thing that does stuff with other things.  (Yes, in some languages a function is an object, but that's not so important when talking about design at this level.)

If you keep this in mind, and also keep in mind that in each case, a class should be a single conceptual thing, and a function should do a single conceptual thing, you'll be ok.


答:
Since i,j, and k are on the stack, they will be located relative to the stack pointer.

First of all, this statement is plainly wrong in a common case with modern compilers. You seem to get used to looking only at very old fashioned compilers, which really worked in the way they allocate positions on stack, map variables to them, and use registers only when explicitly requested (with register keyword) or for temporary values. (Do you make some homework under MS-DOS and 16-bit compilers?) This is a really ancient way.

Modern compilers (GCC, Clang/LLVM, etc.) utilizes SSA and accompanying techniques. With SSA, there are no "variables" internally; there are nearly unchangeable values (except execution path merging points), each of them can get an own place, either in a register or on the stack, depending on how often it is used and how soon it will be used again. If you named some variable "int i", it can be at EAX at one part of function, at EDI at another one, at stack when swapped out of the register pool...

Sometimes, a variable is optimized out at all, if compiler assumes it's easier to use another ones, or even a constant. Sometimes, it is present, but changed (e.g. cycle by i from 1 to N, if accesses an array as x[i-1], is changed to cycle from 0 to N-1 and access as x[i]). And so on and so on, optimization list is nearly infinite.

You can be sure a variable has its place on stack only when you get its address. Nevertheless, it is a variable address only when this address is valid. If you call another function as g(&i), i is placed onto stack before g called, but it can be immediately moved into register or used as an expression argument when g() finished, because this address is never used again.

Example. The C function is:

```<code>int f(int i, int j, int k) {
  return i + j + k;
}
</code>```

It's translated for x86_64/Unix to:

```<code>    addl    %esi, %edi
    leal    (%rdi,%rdx), %eax
    ret
</code>```

No stack is used at all. The calling convention specifies registers for argument and result placing, and that's how it is implemented. (Notice that the same adding is add and then lea - this is spanning instruction flow among different execution units.)

Add an external action for i:

```<code>void g(int*);
int f(int i, int j, int k) {
  g(&i);
  return i + j + k;
}
</code>```

Assembly output:

```<code>    pushq   %rbp
    movl    %esi, %ebp
    pushq   %rbx
    movl    %edx, %ebx
    subq    $24, %rsp
    movl    %edi, 12(%rsp) ; <-- storing i onto stack
    leaq    12(%rsp), %rdi ; <-- getting &i
    call    g
    addl    12(%rsp), %ebp ; <-- using possibly modified i
    addq    $24, %rsp
    leal    0(%rbp,%rbx), %eax
    popq    %rbx
    popq    %rbp
    ret
</code>```

Here, i comes in RDI, then is placed onto stack before g(&i), and then used as summand directly from stack, without returning to a register. (Also, frame pointer is adjusted because this isn't a leaf function anymore.)

Consider again you are utilizing time machine and/or some very embedded environment. SSA is an expensive technique. The mapping of variable set to stack (or, earlier, memory) is how compilers had been worked from the very beginning, namely, early Fortran versions. For that case, you are right. And, the question in that case is how to keep track of possible address changes.

On S/360, a compiler would use a memory chunk after the function body for its variables, and utilize the following instruction sequence to get a base address for this chunk:

```<code>    BALR 15,0
    USING *,15
</code>```

register 15 is a conventional one for this goal, and after this it gets the address just after the command. Then, offset-based memory access is used for variables, like:

```<code>    LR 3,196(15)
</code>```

here 4-byte value from this base plus 196 is loaded into register 3. For the entire function run, i will be at 196(15).

Notice this approach is not stack-based; a function is not reentrant.

With PDP-11, but again not stack-based Fortran, this can be done with instruction pointer based access, like

```<code>    MOV 196(PC), R3
</code>```

because there is no need to allocate a register for such memory access. But offsets will vary (an immediately next instruction will have to use 192 instead of 196).

With stack, this changes to SP-based access and no variable area near the function body:

```<code>    MOV 16(SP), R3
</code>```

but see below for offset changing when SP changes.

With x86 before i386, BP-based stack access was mandatory; since i386, it's still usable, but not unique. After BP setup at function prologue, offsets remain fixed, so you can use the same expression, like [EBP-20] (Intel), -20(%ebp) (AT&T), for a variable during function call lifetime. With ESP/RSP-based access (since i386), offsets are changed with any push/pop. If i was [ESP+20], a single 4-byte push "converts" it to [ESP+24]; "converts" mean the memory address is the same, but formula for it is changed among with ESP adjusting. For example, if g(i,&i,&i) is called, a compiler may produce the following sequence to form the argument list (x86_32 calling conventions are mainly stack-based):

```<code>## assume i is now at 24(%esp)
    leal     24(%esp), %eax ; &i to eax
    pushl    %eax
    leal     28(%esp), %eax ; &i to eax
    pushl    %eax
    movl     32(%esp), %eax ; i to eax
    pushl    %eax
</code>```

(It is obviously suboptimal, but expressing.)

Body:
Since i,j, and k are on the stack, they will be located relative to the stack pointer.

First of all, this statement is plainly wrong in a common case with modern compilers. You seem to get used to looking only at very old fashioned compilers, which really worked in the way they allocate positions on stack, map variables to them, and use registers only when explicitly requested (with register keyword) or for temporary values. (Do you make some homework under MS-DOS and 16-bit compilers?) This is a really ancient way.

Modern compilers (GCC, Clang/LLVM, etc.) utilizes SSA and accompanying techniques. With SSA, there are no "variables" internally; there are nearly unchangeable values (except execution path merging points), each of them can get an own place, either in a register or on the stack, depending on how often it is used and how soon it will be used again. If you named some variable "int i", it can be at EAX at one part of function, at EDI at another one, at stack when swapped out of the register pool...

Sometimes, a variable is optimized out at all, if compiler assumes it's easier to use another ones, or even a constant. Sometimes, it is present, but changed (e.g. cycle by i from 1 to N, if accesses an array as x[i-1], is changed to cycle from 0 to N-1 and access as x[i]). And so on and so on, optimization list is nearly infinite.

You can be sure a variable has its place on stack only when you get its address. Nevertheless, it is a variable address only when this address is valid. If you call another function as g(&i), i is placed onto stack before g called, but it can be immediately moved into register or used as an expression argument when g() finished, because this address is never used again.

Example. The C function is:

int f(int i, int j, int k) {
  return i + j + k;
}

It's translated for x86_64/Unix to:

    addl    %esi, %edi
    leal    (%rdi,%rdx), %eax
    ret

No stack is used at all. The calling convention specifies registers for argument and result placing, and that's how it is implemented. (Notice that the same adding is add and then lea - this is spanning instruction flow among different execution units.)

Add an external action for i:

void g(int*);
int f(int i, int j, int k) {
  g(&i);
  return i + j + k;
}

Assembly output:

    pushq   %rbp
    movl    %esi, %ebp
    pushq   %rbx
    movl    %edx, %ebx
    subq    $24, %rsp
    movl    %edi, 12(%rsp) ; <-- storing i onto stack
    leaq    12(%rsp), %rdi ; <-- getting &i
    call    g
    addl    12(%rsp), %ebp ; <-- using possibly modified i
    addq    $24, %rsp
    leal    0(%rbp,%rbx), %eax
    popq    %rbx
    popq    %rbp
    ret

Here, i comes in RDI, then is placed onto stack before g(&i), and then used as summand directly from stack, without returning to a register. (Also, frame pointer is adjusted because this isn't a leaf function anymore.)

Consider again you are utilizing time machine and/or some very embedded environment. SSA is an expensive technique. The mapping of variable set to stack (or, earlier, memory) is how compilers had been worked from the very beginning, namely, early Fortran versions. For that case, you are right. And, the question in that case is how to keep track of possible address changes.

On S/360, a compiler would use a memory chunk after the function body for its variables, and utilize the following instruction sequence to get a base address for this chunk:

    BALR 15,0
    USING *,15

register 15 is a conventional one for this goal, and after this it gets the address just after the command. Then, offset-based memory access is used for variables, like:

    LR 3,196(15)

here 4-byte value from this base plus 196 is loaded into register 3. For the entire function run, i will be at 196(15).

Notice this approach is not stack-based; a function is not reentrant.

With PDP-11, but again not stack-based Fortran, this can be done with instruction pointer based access, like

    MOV 196(PC), R3

because there is no need to allocate a register for such memory access. But offsets will vary (an immediately next instruction will have to use 192 instead of 196).

With stack, this changes to SP-based access and no variable area near the function body:

    MOV 16(SP), R3

but see below for offset changing when SP changes.

With x86 before i386, BP-based stack access was mandatory; since i386, it's still usable, but not unique. After BP setup at function prologue, offsets remain fixed, so you can use the same expression, like [EBP-20] (Intel), -20(%ebp) (AT&T), for a variable during function call lifetime. With ESP/RSP-based access (since i386), offsets are changed with any push/pop. If i was [ESP+20], a single 4-byte push "converts" it to [ESP+24]; "converts" mean the memory address is the same, but formula for it is changed among with ESP adjusting. For example, if g(i,&i,&i) is called, a compiler may produce the following sequence to form the argument list (x86_32 calling conventions are mainly stack-based):

## assume i is now at 24(%esp)
    leal     24(%esp), %eax ; &i to eax
    pushl    %eax
    leal     28(%esp), %eax ; &i to eax
    pushl    %eax
    movl     32(%esp), %eax ; i to eax
    pushl    %eax

(It is obviously suboptimal, but expressing.)


问:
Executing queries against multiple separate database instances

Premise

I have a number of database servers (different DBMS instances, installations in different physical locations), each of them contains data and uses the same schema. Most of the data is completely the same across all databases, but unfortunately not in every case.

I need to write an application that will issue queries (only selects, not inserts, updates or deletes) against a table across all databases, retrieve all results so that the tool can compare them to be able to report back possible discrepancies to users.

Use case

For example imagine that I have a web based form, where users enter company details. Submitting the form will issue an insert against the same table in all databases (via different database connection, each of them separate). While users typing the company's name the application needs to be able to verify that the value entered doesn't exist across all databases. If it exists or doesn't exist on all databases all is fine. Either the company name is taken or can be used by the user. However if the value exists on some databases, but not on others I have to raise a validation error.

My plan

The tool I'm writing is a Java application, using JDBC (connecting to multiple Oracle databases), so right now my thinking is that I create a Connection towards each of my database servers. Issue the same query in parallel, wait for the results and compare them. My use case involves a handful of users and 5-10 different database servers (database migration or slave/master replication is completely out of question).

In the past I've answered someone's question which required a solution similar to what I'm thinking I should do right now.

Question

What are the possible ways to handle a scenario like this?

答:
Is your application the single point of updates into all the databases? If not, then you will have a lot of issues anyways with dups.

On the other hand, if your app is the single point of updates, then you could use a centralized cache using NoSQL, and use it as a write-through cache, before you save updates to the various databases so that you only need to query that one cache to check for dups.


问:
Why is behavorial subtyping undecidable?

Liskov's work in this area focused on behavioral subtyping, which besides the type system safety discussed in this article also requires that subtypes preserve all invariants guaranteed by the supertypes in some contract.[3] This definition of subtyping is generally undecidable, so it cannot be verified by a type checker.

From : http://www.wikiwand.com/en/Subtyping#/Function_types

答:
Let the contract of operation o of Type T be that it halts for all inputs. Now decide whether operation o of subtype S <: T satisfies that contract: you have just solved the Halting Problem.

More generally, S::o must compute the same function as T::o if S <: T. Deciding whether two programs compute the same function is called the Function Problem and is equivalent to solving the Halting Problem.

In general, statically deciding any non-trivial runtime property is almost always equivalent to the Halting Problem.


答:
Because almost every question about the behavior of programs is undecidable. By Rice's theorem, any decision problem of the form:

Some programs compute functions that have this property, other programs compute functions that don't have this property. Given a program P, does the function computed by P have the aforementioned property or not?

is undecidable. So, for example, you can't always distinguish code that computes the square of an input from code that doesn't. Although in simple cases, it is often possible to prove that a function does or does not do so, there is no general procedure that works for all program.

Almost any interesting behavioral invariant falls under Rice's theorem, since those statements rarely (if ever) talk about what the method looks like internally, only what it returns and what side effects it causes in response to certain inputs.

Title: Why is behavorial subtyping undecidable?

Body:
Liskov's work in this area focused on behavioral subtyping, which besides the type system safety discussed in this article also requires that subtypes preserve all invariants guaranteed by the supertypes in some contract.[3] This definition of subtyping is generally undecidable, so it cannot be verified by a type checker.

From : http://www.wikiwand.com/en/Subtyping#/Function_types


问:
How Should I Design JSON Serializable Data Classes To Respect Future @NonNull Fields
I have an app that uses Gson to serialize/deserialize data classes and persist data between runs.

My code uses @NonNull annotations for many fields/parameters/method returns and one thing that was What if I (or another developer) adds a new @NonNull annotated field (or even just annotates an existing field) to a data class and Gson sets it to null because the JSON was saved in a previous version of the app?

Well I answered that question today. As the user guide says and my tests confirm:

This implementation handles nulls correctly

While serialization, a null field is skipped from the output

While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null

Indeed, if I add a new field to my data class, it might be initialized to null.

So I looked for a solution. I found that if I add a private no-args constructor to the data class, there is enough information for the IDE to flag that the field could indeed be null. An example of this implementation is listed below.

```<code>public void testDataClass1() throws Exception {
    int value1 = 23;
    int value2 = 48;
    final DataClass1Version1 inputClass = new DataClass1Version1(value1, value2);
    final String dataClass1Json = getGson().toJson(inputClass);
    final DataClass1Version2 outputClass = getGson().fromJson(dataClass1Json, DataClass1Version2.class);
    assertEquals(outputClass.getValue1(), value1);
    assertEquals(outputClass.getValue2(), value2);
    assertNotNull("New @NonNull field shouldn't be null.", outputClass.getSomeNewValue());
}
</code>```

DataClass1Version1.java:

```<code>public class DataClass1Version1 {
    private int value1;
    private int value2;

    public DataClass1Version1(int value1, int value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1() {
        return value1;
    }

    public void setValue1(int value1) {
        this.value1 = value1;
    }

    public int getValue2() {
        return value2;
    }

    public void setValue2(int value2) {
        this.value2 = value2;
    }

    @Override
    public String toString() {
        return "DataClass1Version1{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                '}';
    }
}
</code>```

DataClass1Version2.java:

```<code>import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class DataClass1Version2 {
    private int value1;
    private int value2;
    @Nullable
    private String someNullableString;
    //@NonNull
    //private String someNewValue; //you'll get a warning for not initializing this value
    @NonNull
    private String someNewValue = ""; //if you don't initialize this field here, it could be null after json deserialization

    private DataClass1Version2() {
        //adding this constructor caused a warning when someNewValue didn't have an initializer
    }

    public DataClass1Version2(int value1, int value2, @Nullable String someNullableString, @NonNull String someNewValue) {
        this.value1 = value1;
        this.value2 = value2;
        this.someNullableString = someNullableString;
        this.someNewValue = someNewValue;
    }

    public int getValue1() {
        return value1;
    }

    public void setValue1(int value1) {
        this.value1 = value1;
    }

    public int getValue2() {
        return value2;
    }

    public void setValue2(int value2) {
        this.value2 = value2;
    }

    @Nullable
    public String getSomeNullableString() {
        return someNullableString;
    }

    public void setSomeNullableString(@Nullable String someNullableString) {
        this.someNullableString = someNullableString;
    }

    @NonNull
    public String getSomeNewValue() {
        return someNewValue;
    }

    public void setSomeNewValue(@NonNull String someNewValue) {
        this.someNewValue = someNewValue;
    }

    @Override
    public String toString() {
        return "DataClass1Version2{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                ", someNullableString='" + someNullableString + '\'' +
                ", someNewValue='" + someNewValue + '\'' +
                '}';
    }
}
</code>```

The problem with this solution is that I generally use final fields in my data classes and as such, a no-args constructor won't work. What should I do?

While writing this up, I thought of just initializing to some default values and then I guess since Gson uses reflection, it will overwrite those defaults, even though they are final fields. I still want to know what others think. Does this add extra weight to deserialization; if I have a bunch of ArrayLists and I create new instances in the no-args constructor, won't the new instances be instantly replaced with the instance Gson generated?

Here's DataClass2Version2 with final fields and default initializers:

```<code>import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class DataClass2Version2 {
    private final int value1;
    private final int value2;
    @Nullable
    private final String someNullableString;
    @NonNull
    private final String someNewValue;

    private DataClass2Version2() {
        value1 = 0;
        value2 = 0;
        someNullableString = null;
        someNewValue = "";
    }

    public DataClass2Version2(int value1, int value2, @Nullable String someNullableString, @NonNull String someNewValue) {
        this.value1 = value1;
        this.value2 = value2;
        this.someNullableString = someNullableString;
        this.someNewValue = someNewValue;
    }

    public int getValue1() {
        return value1;
    }

    public int getValue2() {
        return value2;
    }

    @Nullable
    public String getSomeNullableString() {
        return someNullableString;
    }

    @NonNull
    public String getSomeNewValue() {
        return someNewValue;
    }

    @Override
    public String toString() {
        return "DataClass2Version2{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                ", someNullableString='" + someNullableString + '\'' +
                ", someNewValue='" + someNewValue + '\'' +
                '}';
    }
}
</code>```

答:
You are looking at the technological solution, but really you need to look at the data.

If you expect a field ABC with a string value, then in your JSON data you can have: Nothing (the field isn't there), null (JSON contains null), an empty string (JSON contains an empty string), any old rubbish (maybe a number, maybe an array), or a non-empty string.

You need to decide how that data should be interpreted. Depending on what you receive for ABC, you can decide that this makes the whole record invalid (for example if there is an array where you expected a string), you might convert a number into a string, you might accept no value or null as an empty string, you might accept no value or null as a null object.

That's the real decision that you need to make. Of course if you declare ABC as @nonnull then any interpretation that makes ABC a null value isn't possible. If your JSON data contains nothing or a null value, you can only decide to interpret this as an empty string, or as an invalid record, since interpreting as a null value isn't possible anymore.


问:
Visual Studio Setup - why is solution explorer on the right?
Every time I install VS (whichever version going back years) it installs with the Solution Explorer on the right.  Now as most UIs have the navigation in a left hand column (and at the top of the viewport) and the content to the right of this navigation this always seems wrong to me.

So I drag the solution explorer to the left of the screen and dock it there.  But I've never seen another developer do this.

Considering how most programmers usually like to customize their environment, adding their favourite text editor, browser, plug-ins, greasemonkey scripts etc why do Visual Studio developers never seem to make this simple UI change?  Does anyone else do this or am I just screaming in the dark?

答:
I just docked it to the left side (after having it on the right side for years) as an experiment. It's strange why I never thought about it until now, because I use a dual-monitor setup for 3 years and I always have VS on the right screen (the browser - I'm a web developer - and other tools, e.g. source control client are on the left screen). The total width of my two screens is a little over 1m, so the Solution Explorer was quite far away on the right side - now it's where the two screens meet.

Another important aspect is that the solutions I'm working with have a lot of projects (with a lot of files), so before, every time I wanted to open another file I had to move the mouse across the screen to right side and then back to the left side on the beginning of a line (or close to that) - now the Solution Explorer is much closer to the beginning of a line.

The funny thing is that the code editor window "feels" wider since the Solution Explorer is on its left side and the code editor now ends with the end of the screen.


答:
Re: How to estimate and stick to it:

When estimating, remember Hofstadter's law as well as this quip: "Everything takes longer than it does". Take a reasonable guess as to how long something should take, then double or triple it before it comes out your mouth. There will be complications, setbacks, distractions, things you forget, etc. Better to under-promise and over-deliver than vice-versa.

On sticking to estimations, do your best to complete your work efficiently. When problems come  up, communicate the delays early. This gives everybody time to adjust their expectations. If your explanation is reasonable, you may be given more time or assistance or have distractions (like a noisy neighbor) removed from your path.

Title: How to become a "faster" programmer?


问:
How to handle multiple "valid after {date}" in a performant way
We work on an Application which displays a duty roster and also some other DateTime related things.

So my Database is full of Relations like in this small Example:

This results in big StoredProcedure to get all Employee Data and it's Date related Data for a given Employee and Day, Month ,Year combination

which looks like this (based on the Example):

```<code>ALTER PROCEDURE Mitarbeiter_Select

    @myDate         AS datetime2(7) = null, -- null represent current
    @EmployeeId     AS int          = null  -- null represents all Employees

AS
    -- declare my intern parameters
    DECLARE @oldDate                AS datetime2(7)= null;

    SET @Wann   = ISNULL(@Wann,GETDATE());

    -- set the previous month
    SET @oldDate= DATEADD(month, -1, @Wann); -- for some calculations i need information from the month before

    --############################# REGION TEMP TABLE ###########################
    -- create my TempTable
    create table #EmployeeToFind
    (
        ID int,
        FirstName nvarchar(MAX),
        LastName nvarchar(MAX)
    )

    create table #EmployeeVacationDays
    (
        RefEmployeeId int,
        YearDays int
    )

    create table #EmployeeManager
    (
        RefEmployeeId int,
        IsManager bit
    )

    --############################# REGION FILL TABLE ###########################

    INSERT INTO #EmployeeToFind
    SELECT  ID,
            Personalnummer,
            FirstName ,
            LastName
    FROM    Employee
    WHERE   ID = ISNULL(@EmployeeId, ID)

    INSERT INTO #EmployeeVacationDays
    SELECT  RefEmployeeId ,
            Days AS YearDays
    FROM    VacationDays OUTERMU
    WHERE   RefEmployeeId = ISNULL(@EmployeeId, RefEmployeeId )
    AND     ValidAfter =    (
                                    SELECT  MAX(ValidAfter )
                                    FROM    VacationDays
                                    WHERE   RefEmployeeId = OUTERMU.RefEmployeeId
                                    AND     (   YEAR(ValidAfter) = YEAR(@Wann)
                                                OR
                                                YEAR(ValidAfter) < YEAR(@Wann)
                                            )
                            )

    INSERT INTO #EmployeeManager
    SELECT  RefEmployeeId ,
            IsManager
    FROM    Manager
    WHERE   RefEmployeeId = ISNULL(@EmployeeId, RefEmployeeId )
    AND     ValidAfter =    (
                                    SELECT  MAX(ValidAfter )
                                    FROM    Manager
                                    WHERE   RefEmployeeId = OUTERMA.RefEmployeeId
                                    AND     (   YEAR(ValidAfter) = YEAR(@Wann) AND  MONTH(ValidAfter)  <= MONTH(@Wann)
                                                OR
                                                YEAR(ValidAfter) < YEAR(@Wann)
                                            )
                            )

    --############################# REGION RESULT SELECT ###########################
    SELECT  #EmployeeToFind.ID,
            #EmployeeToFind.FirstName ,
            #EmployeeToFind.LastName ,
            #EmployeeVacationDays.YearDays ,
            #EmployeeManager.IsManager ,

    -- in our real Procedure we have here also some CASE WHEN ... THEN ... ELSE ... END
    -- Depending on IS NULL/ IS NOT NULL of some Values

    FROM #EmployeeToFind
    left outer join #EmployeeVacationDayson #EmployeeToFind.ID= #EmployeeVacationDays.RefEmployeeId
    left outer join #EmployeeManageron #EmployeeToFind.ID= #EmployeeManager.RefEmployeeId
</code>```

Now my Question is there a way to simplify this?

答:
The question mentions performance, but in the body you ask about simplifying.

The most important things I've done that dramatically improved our worst performing procedures:

Indexes on the join columns

Indexes as needed without consideration of index maintenance overhead.

Ensure column order in compound indexes was in the order as used in where or join.

Ensure we had indexes on foreign keys

Made temp tables permanent tables and created indexes.

Truncate rather than delete when clearing the (now permanent) temp tables.

Rebuild statistics immediately after filling tables.

The above was not pure guess work. Our DBA analyzed logs on how, if, where existing indexes were used and he made suggestions where new indexes might help.


问:
Is HTML5 XHTML 1.0 compliant?
For a school assignment, I wrote up a web-page in HTML5.

After looking over the assignment's requirements again though, I found the line:

• a minimum of three HTML pages complying with at least XHTML 1.0 standards or (better).

I'd really rather not need to add all the ugly tags to the top of the page, and change all my meaningful  and  tags to generic
s, so I tried validating it.

According to the W3C validator, my site checks out when I set it to validate it as XHTML 1.0

According to Validome though, it's not valid, and gives me errors for the lack of appropriate attributes at the top, and errors for each of the HTML5 tags that I used.

That leaves me with the question:

Is HTML5 at least XHTML 1.0 compliant?

The page:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Brendon's Uromastyces Fact Site</title>
    <meta charset="utf-8">
</head>

<body>
    <div id="mainBody">
        <section>

            <header>
                <h1>Brendon's Uromastyces Fact Site</h1>
            </header>
            <h2>
                Welcome to my site dedicated to providing reliable, referenced information about Uromastyces.
            </h2>
            <p>
                My goal in creating this site was to allow fast access to the most important information surrounding
                Uromastyces. Especially regarding issues like the choice of substrate (the bedding that lines the
                bottom of the cage), there is a lot of contradictory information, which can be overwhelming for
                someone new to reptile keeping.
            </p>
            <p>
                Below, as well as to your left, are navigation bars you can use to explore each of the site's main
                topics: information relating to <em>Enclosures</em>, <em>Diet</em>, and general information about
                their <em>Behavior and Life</em>.
            </p>

            <nav class="navBar">
                <ul>
                    <!--    Only 3 of the links are currently valid: "Home" (this page; sample1.html), "Enclosure"
                            (sample2.html fixed up), and "About Me" (the third required page for the exercise)-->
                    <li>Home</li>
                    <li>Enclosure</li>
                    <li>Diet</li>
                    <li>Behavior and Life</li>
                    <li>About Me</li>
                </ul>
            </nav>

        </section>

    </div>

    <aside class="sideBar">
        <!--    This image is currently pretty big. Once I have access to CSS, I can have it automatically adjust the
                size. The width/height attributes seem to be considered deprecated (http://www.tutorialspoint
                .com/html/html_deprecated_tags.htm) in favor of using CSS. I'll have this adjust itself according to
                the screen size down the road to accommodate small screens. My goal will be to have the width of the
                nav bar == the width of the image, and have the height adjusted automatically.-->
        <img src="pascal-cropped-shrunk.jpg" alt="Picture of Pascal">
        <!--    Without being able to do any styling, this is going to sit below the main content body, when ideally it
            would float to the left-->
        <nav class="navBar">
            <ul>
                <!--    Unfortunately, this is copy-and-pasted from above. I'm not sure the best, most maintainable solution
                         would be at this point. If a link is updated, or the menu is changed, I want to ensure that all
                         menus reflect the change.
                         Down the road, I may generate the menus using JS (along with other content that doesn't vary
                          between pages), but that's not an option right now.
                         Also, since I can't arrange the elements yet, both of the nav menus are immediately on top of
                         each other, which is redundant. Later on, one will be a nav bar on the left, and the other a
                         quick access nav bar underneath the site introduction.-->
                <li>Home</li>
                <li>Enclosure</li>
                <li>Diet</li>
                <li>Behavior and Life</li>
                <li>About Me</li>
            </ul>
        </nav>

    </aside>

</body>
</html>
</code>```

Just an update:

The above page was accepted. I ended up using JS to generate the page, but the end result was nearly the same.

答:
XHTML is an XML schema with HTML tags. Any XML document must begin with an <?xml ... declaration, so your example is not XML and not XHTML.

HTML5 and XHTML 1.0 are compatible in the sense that you can easily switch from XHTML to HTML5 by only changing the doctype, but not the other way. Most notably:

HTML5 has a more liberal syntax. It does not require certain tags to be closed. E.g. you have an unterminated  and <meta> tag. In XML, empty tags can be written as .

HTML5 includes many tags that are not present in the older XHTML standard.
IIRC, the elements section, header, aside, nav are not defined in XHTML 1.0.

Title: Is HTML5 XHTML 1.0 compliant?

Body:
For a school assignment, I wrote up a web-page in HTML5.

After looking over the assignment's requirements again though, I found the line:

• a minimum of three HTML pages complying with at least XHTML 1.0 standards or (better).

I'd really rather not need to add all the ugly tags to the top of the page, and change all my meaningful  and  tags to generic
s, so I tried validating it.

According to the W3C validator, my site checks out when I set it to validate it as XHTML 1.0

According to Validome though, it's not valid, and gives me errors for the lack of appropriate attributes at the top, and errors for each of the HTML5 tags that I used.

That leaves me with the question:

Is HTML5 at least XHTML 1.0 compliant?

The page:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Brendon's Uromastyces Fact Site</title>
    <meta charset="utf-8">
</head>

<body>
    <div id="mainBody">
        <section>

            <header>
                <h1>Brendon's Uromastyces Fact Site</h1>
            </header>
            <h2>
                Welcome to my site dedicated to providing reliable, referenced information about Uromastyces.
            </h2>
            <p>
                My goal in creating this site was to allow fast access to the most important information surrounding
                Uromastyces. Especially regarding issues like the choice of substrate (the bedding that lines the
                bottom of the cage), there is a lot of contradictory information, which can be overwhelming for
                someone new to reptile keeping.
            </p>
            <p>
                Below, as well as to your left, are navigation bars you can use to explore each of the site's main
                topics: information relating to <em>Enclosures</em>, <em>Diet</em>, and general information about
                their <em>Behavior and Life</em>.
            </p>

            <nav class="navBar">
                <ul>
                    <!--    Only 3 of the links are currently valid: "Home" (this page; sample1.html), "Enclosure"
                            (sample2.html fixed up), and "About Me" (the third required page for the exercise)-->
                    <li><a href="sample1Fixed.html">Home</a></li>
                    <li><a href="sample2Fixed.html">Enclosure</a></li>
                    <li><a href="diet.html">Diet</a></li>
                    <li><a href="behaviorAndLife.html">Behavior and Life</a></li>
                    <li><a href="page3.html">About Me</a></li>
                </ul>
            </nav>

        </section>

    </div>

    <aside class="sideBar">
        <!--    This image is currently pretty big. Once I have access to CSS, I can have it automatically adjust the
                size. The width/height attributes seem to be considered deprecated (http://www.tutorialspoint
                .com/html/html_deprecated_tags.htm) in favor of using CSS. I'll have this adjust itself according to
                the screen size down the road to accommodate small screens. My goal will be to have the width of the
                nav bar == the width of the image, and have the height adjusted automatically.-->
        <img src="pascal-cropped-shrunk.jpg" alt="Picture of Pascal">
        <!--    Without being able to do any styling, this is going to sit below the main content body, when ideally it
            would float to the left-->
        <nav class="navBar">
            <ul>
                <!--    Unfortunately, this is copy-and-pasted from above. I'm not sure the best, most maintainable solution
                         would be at this point. If a link is updated, or the menu is changed, I want to ensure that all
                         menus reflect the change.
                         Down the road, I may generate the menus using JS (along with other content that doesn't vary
                          between pages), but that's not an option right now.
                         Also, since I can't arrange the elements yet, both of the nav menus are immediately on top of
                         each other, which is redundant. Later on, one will be a nav bar on the left, and the other a
                         quick access nav bar underneath the site introduction.-->
                <li><a href="sample1Fixed.html">Home</a></li>
                <li><a href="sample2Fixed.html">Enclosure</a></li>
                <li><a href="diet.html">Diet</a></li>
                <li><a href="behaviorAndLife.html">Behavior and Life</a></li>
                <li><a href="page3.html">About Me</a></li>
            </ul>
        </nav>

    </aside>

</body>
</html>
</code>```

Just an update:

The above page was accepted. I ended up using JS to generate the page, but the end result was nearly the same.

Body:
XHTML is an XML schema with HTML tags. Any XML document must begin with an <?xml ... declaration, so your example is not XML and not XHTML.

HTML5 and XHTML 1.0 are compatible in the sense that you can easily switch from XHTML to HTML5 by only changing the doctype, but not the other way. Most notably:

HTML5 has a more liberal syntax. It does not require certain tags to be closed. E.g. you have an unterminated <img> and <meta> tag. In XML, empty tags can be written as <img ... />.

HTML5 includes many tags that are not present in the older XHTML standard.
IIRC, the elements section, header, aside, nav are not defined in XHTML 1.0.


问:
Will ECMAScript add classes to JavaScript? What does this mean?
I heard that some sort of class system will be added to JavaScript with ECMAScript and I find that a little confusing, because I've just finished reading a JS book, JavaScript, The Good Parts by Douglas Crockford, where he explained that the lack of classes wasn't a bad thing at all, it was just different. I believe I've seen it explained that any similarity to a class-based language was just to lessen confusion during that era or something like that, to help JS catch on.

From my understanding, JavaScript isn't supposed to have classes, they just aren't part of JS's design. Does ES6 fundamentally change JS functionality or is it just syntax sugar?

答:
The ES6 class syntax does not change the functionality of Javascript at all. It is merely syntax sugar for prototype declarations. Once parsed, it just creates prototype objects which can then be used in an OO fashion the same way manually declared prototype objects have always been used in JS. So, the class syntax doesn't really change anything except make prototype definitions prettier to declare. The resulting objects are no more class-like than what people did manually in ES5.

Here's an example (run only in a browser that supports the ES6 class syntax like Chrome as of Dec 2015).

```<code>// ES6 class syntax
class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    calcArea() {
        return this.height * this.width;
    }
    get area() {
        return this.calcArea()
    }
}

// ES5 equivalent prototype syntax
function Poly(height, width) {
    this.height = height;
    this.width = width;
}

Object.defineProperties(Poly.prototype, {
    calcArea: {
        value: function () {
            return this.height * this.width;
        }
    },
    area: {
        get: function () {
            return this.calcArea();
        }
    }
});

var p1 = new Polygon(10, 20);
var p2 = new Poly(10, 20);
log(p1.area);
log(p2.area);
log(Object.getOwnPropertyNames(Object.getPrototypeOf(p1)));
log(Object.getOwnPropertyNames(Object.getPrototypeOf(p2)));
</code>```

Output in Chrome as of Dec 2015:

```<code>200
200
["constructor","calcArea","area"]
["constructor","calcArea","area"]
</code>```

Working jsFiddle: http://jsfiddle.net/jfriend00/92hhohdc/

Body:
The ES6 class syntax does not change the functionality of Javascript at all. It is merely syntax sugar for prototype declarations. Once parsed, it just creates prototype objects which can then be used in an OO fashion the same way manually declared prototype objects have always been used in JS. So, the class syntax doesn't really change anything except make prototype definitions prettier to declare. The resulting objects are no more class-like than what people did manually in ES5.

Here's an example (run only in a browser that supports the ES6 class syntax like Chrome as of Dec 2015).

// ES6 class syntax
class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    calcArea() {
        return this.height * this.width;
    }
    get area() {
        return this.calcArea()
    }
}

// ES5 equivalent prototype syntax
function Poly(height, width) {
    this.height = height;
    this.width = width;
}

Object.defineProperties(Poly.prototype, {
    calcArea: {
        value: function () {
            return this.height * this.width;
        }
    },
    area: {
        get: function () {
            return this.calcArea();
        }
    }
});

var p1 = new Polygon(10, 20);
var p2 = new Poly(10, 20);
log(p1.area);
log(p2.area);
log(Object.getOwnPropertyNames(Object.getPrototypeOf(p1)));
log(Object.getOwnPropertyNames(Object.getPrototypeOf(p2)));

Output in Chrome as of Dec 2015:

200
200
["constructor","calcArea","area"]
["constructor","calcArea","area"]

Working jsFiddle: http://jsfiddle.net/jfriend00/92hhohdc/


答:
HTML5 has an XML serialization, which is exactly the same elements and semantics as HTML5, just with an XML compliant syntax.

XHTML5 is not exactly XHTML 1.0 compliant, but it is better than XHTML 1.0 and should therefore be good for your purpose. (Obvious depending on the definition of "better", but in the context of versions it is typically just means a newer version or recommendation, which HTML5 is.)

In other words, you should be fine using HTML5-specific elements like , as long as you make sure to use XML syntax (all tags closed and so on).

Your <meta charset="utf-8"> for example should be <meta charset="utf-8" />.

Title: Is HTML5 XHTML 1.0 compliant?

Body:
HTML5 has an XML serialization, which is exactly the same elements and semantics as HTML5, just with an XML compliant syntax.

XHTML5 is not exactly XHTML 1.0 compliant, but it is better than XHTML 1.0 and should therefore be good for your purpose. (Obvious depending on the definition of "better", but in the context of versions it is typically just means a newer version or recommendation, which HTML5 is.)

In other words, you should be fine using HTML5-specific elements like <header>, as long as you make sure to use XML syntax (all tags closed and so on).

Your <meta charset="utf-8"> for example should be <meta charset="utf-8" />.


问:
When > apply a performance and memory profiler?
Based on your experience, when do you need to perform a performance and memory profiler for a web development project in C#?

Today, Im newbie in performance and memory profiling.

答:
Use a memory and performance profiler when you need to find out why your program is running too slow or using too much memory.  It will tell you which specific parts of your code are causing the problem, so that you can focus your efforts specifically on that code.

Further Reading

Beginners Guide to Performance Profiling