答:
I would put this in simpler analogy. If you send a letter you just put an address on envelop and put that in post box. But how is that actually going to the specific address? The PostMan (or the delivery boy) actually know what physical location those few lines written over the envelop turns to (assuming you haven't visited the location personally)

CPU works the same way and uses Memory Address to bring in data it needs to process. Here Memory Refers to RAM (the storage CPU refers to for processing data). CPU also have memory in itself called Registers that it uses for doing processing. And yes Memory Address are ordered and thats why CPU can access them randomly using the Memory Address and not loop through or go one by one to get an item in Memory.

Title: What are memory addresses?


问:
Why are the  and  tags deprecated?
This question came up in one of my college classes. The professor only gave the answer that it was more descriptive, but it seems as though  and  are rather explicit in their meaning and is easier to type than  and .

What were the official arguments for the deprecation of these tags?

答:
The  and  tags originated with the concepts of "bold" and "italic".  The problem is these may be completely meaningless for some user agents.  For instance, what does "italic" sound like in a screen reader for a blind person?

Replacing them with  and  removed the direct link to typographical concepts.  Instead, the user agent can render them however it sees fit.

ContentLicense: CC BY-SA 3.0

Title: Why are the <b> and <i> tags deprecated?

Body:
The <b> and <i> tags originated with the concepts of "bold" and "italic".  The problem is these may be completely meaningless for some user agents.  For instance, what does "italic" sound like in a screen reader for a blind person?

Replacing them with <strong> and <em> removed the direct link to typographical concepts.  Instead, the user agent can render them however it sees fit.


问:
What are memory addresses?
I have more or less 0 knowledge in low-level topics, so forgive my possible ignorance.

I know that in languages such as C, pointers hold 'memory addresses', i.e. strings (or binary data?) written in hex such as 0x52A132F3.

Judging by the term 'memory address', I assume this number actually leads to some place in memory. But I'm having a hard time understanding what a 'place in memory' actually is and how a hexadecimal number can 'lead' to it. (A Java programmer here..)

So two questions:

Do the memory addresses point to places on the CPU itself, or anywhere in the computer?

Is memory 'ordered' in hardware in some way that it makes sense to refer to it using an 'ordinal' number, such as 0x52A132F3? How is memory ordered in hardware, and how and why does it make sense to access it using a numerical value?

答:
On your motherboard, you have a CPU and a bunch of wires (called a bus) that go to your RAM, which comes separately on sticks that are relatively easy to replace.  You can think of the memory address as controlling 32 of those wires.  0x52A132F3 translates to 01010010101000010011001011110011 in binary.  Each 1 means the CPU puts a voltage (1.5 volts for DDR3) onto that corresponding wire, which tells the RAM chip which memory to send back to the CPU.

This is an oversimplification because of things like cache and virtual memory pages, and systems might support more or less than 4Gb of RAM, and so have more or fewer address wires, but it's a useful model for how to think about memory addresses, and simpler embedded systems work that way.

Hexadecimal is used because for a 32-bit number it is always 8 digits including possibly leading zeros.  It's also easy to convert to binary.  Also, you can write cool addresses like 0xDEADBEEF or 0xABBACAFE, which are sometimes useful for debugging.  Mostly you can think of it as an index into a very big array of all the memory on your system.

Title: What are memory addresses?


问:
How to use ViewModels in a layered architecture?
I've got a Java application that is using a layered architecture, we have: presentation layer, business layer and data access layer.
Our business layer uses the models to process the "requests".
We are using the concept of "ViewModel", so every View-Action relation has its View. What is happening is that we have a lot of ViewModels. The number of files are kind of confusing but the real problem is that we are facing a name conflict problem.

This raised some questions:

In this case we are using ViewModels in a layered architecture. Is this approach OK?

Is it normal to face a high number of files?

Is there any naming convention you use to make it clear to which View the model "belong" to?

If a model is exactly the same for two views, should they be shared or should I have two different models that have exactly the same content?

答:
Yes, it is normal to have lots of ViewModels, and yes, naming and namespacing is important. In my apps, I typically create a hierarchy of ViewModels to match my controllers/presenters and actions. For example:

Controllers

ProductsController

OrdersController

ViewModels

Products

ListProductViewModel (assumes a "list" View)

EditProductViewModel (assumes a "edit" View)

Orders

ShowOrderViewModel

CreateOrderViewModel

ViewModels are almost always only data structures with no behavior, and as such, it doesn't matter so much if some of the code is duplicated. To me, it makes it that much easier for someone else to understand and modify than if a ViewModel is shared across views/actions.


答:
The true story is that b and i were first obsoleted, deprecated, cursed, and anatematized as “presentational” in various HTML5 drafts (broadly speaking), but then they realized that these tags are widely used and also generated by many authoring programs. Instead of simply allowing them, they developed contrived new “semantic” definitions for them, to be able to allow the elements but still pretend to be strict about “presentational” markup. The new definitions have varied from one draft to another and are obscure: you can hardly find two people who understand and interpret them the same way.

Sorry, no references. The description above is a result of following the changes and reading the drafts and discussions, often between the lines. They are not explicitly telling the cause. I still think it’s the true story.

The conclusion is: Move on. There’s nothing useful here. The b and i elements do the same thing as they always have: they make the font bold or italic, respectively, with the usual caveats. This is the reality that you should take into account, not the quasischolastic “semantics” that has no impact on browsers, search engines, or other software.

Body:
This question came up in one of my college classes. The professor only gave the answer that it was more descriptive, but it seems as though  and  are rather explicit in their meaning and is easier to type than  and .

What were the official arguments for the deprecation of these tags?


问:
Are mutliple database calls really significant with a network call for a web API?
At one of my employers, we worked on a REST (but it also applies to SOAP) API. The client, which is the application UI, would make calls over the web (LAN in typical production deployments) to the API. The API would make calls to the database.

One theme that recurs in our discussions is performance: some people on the team believe that you should not have multiple database calls (usually reads) from a single API call because of performance; you should optimize them so that each API call has only (exactly) one database call.

But is that really important? Consider that the UI has to make a network call to the API; that's pretty big (order of magnitude of milliseconds). Databases are optimized to keep things in memory and execute reads very, very quickly (eg. SQL Server loads and keeps everything in RAM and consumes almost all your free RAM if it can).

TLDR: Is it really significant to worry about multiple database calls when we are already making a network call over the LAN? If so, why?

To be clear, I'm talking about order of magnitude -- I know that it depends on specifics (machine hardware, choice of API and DB, etc.) If I have a call that takes O(milliseconds), does optimizing for DB calls that take an order of magnitude less, actually matter? Or is there more to the problem than this?

Edit: for posterity, I think it's quite ridiculous to make claims that we need to improve performance by combining database calls under these circumstances -- especially with a lack of profiling. However, it's not my decision whether we do this or not; I want to know what the rationale is behind thinking this is a correct way of optimizing web API calls.

答:
The optimization path presented is simply the wrong way to look at things.

API calls should be atomic.  In other words, I should be able to make 1 web API call to perform the action I want.  Whether that is to fetch data, update a record or whatever.  It should NEVER take more than 1 call to cause the action.  And attempting to leverage transactions across multiple calls should be shunned like the plague.

Sometimes a single action is rather complex.  For example, fetching data which is combined from several sources: again, this should be a single call.  Either the entire thing works or the entire thing fails.

Now, saying that a single API call should only execute one DB query is a bit moronic.  As you've pointed out, the overhead for marshalling the call across the network is often orders of magnitude more expensive in terms of overall time.

I can somewhat understand their statement that a single query runs can faster than several; but this gives a false impression as it ignores the total DB and network load.  Only by profiling the various ways of pulling data out of the DB can you figure out what the problem really is.  I'm sure everyone has a story where a particular query executed 100 times more often than expected killed the system until a proper index was put in place...

Ultimately you aren't going to be able to convince them with just talk.  Set up a test case for both approaches and profile them.  Pay attention to total time to acquire the data you need, amount of network traffic generated, number of and timing of the database calls etc.  Take a holistic approach - meaning that you look at the entire system - and you should end up with plenty of data to either eat crow or show them the golden path.


问:
Why aren't we building and using parallel processors *meant* for general computation?
We all know GPUs are much faster than CPUs for a wide range of applications. When someone asks why we are not just programming for GPUs at all, one of the most common answers is that GPUs are not good for everything - i.e., they fail to do some things that CPUs do easily. Well, no wonder: after all, they are not meant to be used for general computations. GPUs are strongly tied to games and graphical applications, not only having specialized functions for those, but often being advertised for them.

My question is: why, then, aren't we building and using processors that are actually designed for parallel programs?

答:
Other answers are good, but the question reminds me of a past phenomenon in computer graphics (remember that?)

It was called the Wheel of Reincarnation.
It goes like this:

Invent a computer.

Program the computer to do something useful, like draw pictures.

For performance, invent a special processor to off-load the picture drawing.

To improve the special processor, make it more "intelligent" like a computer.

Now even more of the work can be offloaded to the special processor.

Voila', we're back at 1. !

This is still going on, with GPUs, with ever "smarter" browsers, etc.
It seems to happen whenever there's a communication bottleneck between processors, and the redundancy due to separation of responsibilities leads to maintainability problems.

Not to brag (aw, go ahead ) I tried to short-circuit this cycle ages ago by a scheme that automatically manages a remote client without requiring extra code to be written.
I called it differential execution.

The relevance to the current question is that the advantage of having multiple processors adapted to different parts of the job is offset by the need to write separate programs for them, which then produces bugs, rather than just saying what you want.


答:
The  and  tags are essential when you literally require text in 'bold' or 'italic'.

If you're writing an equation in HTML where an italicised 'I ' has a different meaning from a non-italicised 'I' it's important to be able to make that distinction.

I think of them in the same way I think of  or  tags - you can't correctly represent the meaning of an equation without using such 'appearance' tags.

The purist approach would be to use MathML or TeX but browser support isn't there yet...

Body:
The <b> and <i> tags are essential when you literally require text in 'bold' or 'italic'.

If you're writing an equation in HTML where an italicised 'I ' has a different meaning from a non-italicised 'I' it's important to be able to make that distinction.

I think of them in the same way I think of <sup> or <sub> tags - you can't correctly represent the meaning of an equation without using such 'appearance' tags.

The purist approach would be to use MathML or TeX but browser support isn't there yet...


答:
1. Do the memory addresses point to places on the CPU itself, or anywhere in the computer?

No. On all modern operating systems, virtual address spaces are used. Each program has its own address space. Pointer values are addresses in this address space. Addresses in this address space are mapped to physical memory by the OSes memory manager.

This mapping is sparse: only needed addresses are mapped. In addition, some addresses cannot be mapped to physical memory (think segmentation fault or general protection error).

This mapping is volatile: the same address may point to different parts of physical memory at different points in time.

2. Is memory 'ordered' in hardware in some way that it makes sense to refer to it using an 'ordinal' number, such as 0x52A132F3?

Not in a way that a program can rely on. The memory manager can map these addresses in any way it sees fit (see: Virtual Memory).

How is memory ordered in hardware,

Different computers will setup physical memory in different ways. The setup only needs to make sense to the memory manager.

and how and why does it make sense to access it using a numerical value?

The numerical values used by addresses make things easier. Think about arrays, using a numerical address, it's easy lookup the value at a particular index just by adding the base address and index (which is why most languages have arrays starting at 0).

This base address plus index calculation is called offsetting. Offsetting is use to get fields out of a structure, get parameter values of functions, looping, branching, and so much more. I have trouble imagining how computing would be done without numerical addresses.

Title: What are memory addresses?

Body:
I have more or less 0 knowledge in low-level topics, so forgive my possible ignorance.

I know that in languages such as C, pointers hold 'memory addresses', i.e. strings (or binary data?) written in hex such as 0x52A132F3.

Judging by the term 'memory address', I assume this number actually leads to some place in memory. But I'm having a hard time understanding what a 'place in memory' actually is and how a hexadecimal number can 'lead' to it. (A Java programmer here..)

So two questions:

Do the memory addresses point to places on the CPU itself, or anywhere in the computer?

Is memory 'ordered' in hardware in some way that it makes sense to refer to it using an 'ordinal' number, such as 0x52A132F3? How is memory ordered in hardware, and how and why does it make sense to access it using a numerical value?


问:
Sessions in cloud applications dangerous?
We have a django app hosted on heroku. I had a situation:

A user entered an email in a form on page1. If the email existed in
the database he was redirected to Login page otherwise to register
page.

In the register page the form was filled with the same email
entered on page1 using request.session that was populated previously.

I was told it was dangerous as using sessions is not recommended in cloud applications. Is this notion correct both generally, and under above scenario?

答:
"Cloud application" is mainly a commercial buzz word but is, as far as I know not stricly defined. General definition could be "an application with a client on the end-user device, using online servers to do some processing or store somes data". But as a buzz word, in fact nearly all applications nowaday could be called "cloud application" if they use a server.

My point being your question could probably be "are server sessions safe ?".
And in this case the respond is yes, session aren't dangourous by themselves and storing data server side is as safe as your server is.


问:
Are there two type of associations between objects or are there just different representations?
I've been spending some time on 're-tuning' some of my OOP understanding, and I've come up against a concept that is confusing me.

Lets say I have two objects. A user object and an account object. Back to basics here, but each object has state, behaviour and identity (often referred to as an entity object).

The user object manages behaviour purely associated with a user, for example we could have a login(credentials) method that returns if successfully logged in or throws exception if not.

The account object manages behaviour purely associated with a users account. For example we could have a method checkActive() that checks if the account is active. The account object checks if the account has an up-to-date subscription, checks if there are any admin flags added which would make it inactive. It returns if checks pass, or throws exception if not.

Now here lies my problem. There is clearly a relationship between user and account, but I feel that there are actually two TYPES of association to consider. One that is data driven (exists only in the data/state of the objects and the database) and one that is behaviour driven (represents an object call to methods of the associated object).

Data Driven Association

In the example I have presented, there is clearly a data association between user and account. In a database schema we could have the following table:

```<code>-----------------
  USER_ACCOUNTS
-----------------
 id
 user_id
 ----------------
</code>```

When we instantiate the account and load the database data into it, there will be a class variable containing user_id. In essence, the account object holds an integer representation of user through user_id

Behaviour Driven Association

Behaviour driven associations are really the dependencies of an object. If object A calls methods on object B there is an association going from A to B. A holds an object representation of B.

In my example case, neither the user object nor the account object depend on each other to perform their tasks i.e. neither object calls methods on the other object. There is therefore no behaviour driven association between the two and neither object holds an object reference to the other.

Question

Is the case I presented purely a case of entity representation? The association between user and account is always present, but its being represented in different ways?

ie. the user entity has an identity that can be represented in different forms. It can be represented as an object (the instantiated user object) or as a unique integer from the users table in the databases.

Is this a formalised way of recognising different implementations of associations or have I completely lost my mind?

One thing that bugs me is how would I describe the differences in UML or similar? Or is it just an implementation detail?

答:
It s a bit hard to fully understand what is problem actually in :). I think you are a bit mixing some concepts.

Entities representation

At first, all models we are implementing is just a simplification of some real-world objects and environment. Your conceptual entity user corresponds to some real user and contains some attributes we are intresteing in according to application needs. Thus there are some models we have to implement.

Thus, all user defined by DB schema, user defined by class, and probably user defined by some presentation logic is normally present some real-world user. It is only about implementation purposes, we have to store, view and manipulate with user.

On the other hand let's take a look on Single Responsibility Principle. It tells us to use every class or program unit just for certain needs. Using single user (class or program unit) for storage and presentation needs violates this principles.

the user entity has an identity that can be represented in different
  forms. It can be represented as an object (the instantiated user
  object) or as a unique integer from the users table in the databases.

So, the answer is yes.

Associations and dependencies

I think it is more about terminology than about nature of problem. But in general you are right - there are different types of object realtions (especially, I will use other terms  to list it). For example "referencing", "creation", "using", "coordinating", "storing", "inheriting" (!) ....

According to this, user instance references account instance. And A instance uses B instance.

For most cases it is good enough to distinguish just "referencing" and "using". It is what you've just written. It's enough common and abstract to be understood by other person when talking about domain, e.g.

But sometimes, to emphasize some aspects you should describe relations in a way like "A dispatches ensemble of Bs" or "R stores X to database". It's more applicable for specification and modelling.

Is this a formalised way of recognising different implementations of
  associations or have I completely lost my mind?

To call something formalized I suggest to look at UML.

UML and other modelling instruments

One thing that bugs me is how would I describe the differences in UML
  or similar? Or is it just an implementation detail?

There are a lot of UML models (diagrams). Let's take a look at most well-known - Classes and Objects Diagram.

It's interesting that UML allows to present all type of object relations, and moreover allows to decide "is it just an implementation detail".

Martin Fowler describes 3 levels (or point of views) of understanding of Classes Diagram.

Conceptual. Diagram is considered as high-level domain model, independent from implementation.

Specification. Diagram is considered as high-level realization model containing of interfaces.

Implementation. Diagram is considered as low-level technical paper containing interfaces, classes, references, other types of relations.

Is this a formalised way of recognising different implementations of
  associations or have I completely lost my mind?

Yes, you have to fix some point of view and choose appropriate relations set.

For example, let's take a look at Classes Diagram and consider it from an implementation point of view. UML defines 3 type of relations (and propose corresponding means to its designation):

Association

Association corresponds "referencing" between instances.

Dependency

Dependency combines all types of relations such as "using", "creating", "storing", etc.

Inheritance.

Inheritances as a fundamental OOP instrument is presented by UML in a distinct way. It's more about classes than about instances, but also one can say that A instance inherit attributes of B instance. So, that's ok.

First and second points of view on Class Diagram, as I remember uses only one type of relation unifying both associations and dependencies and is designated like association (no inheritance, of course).

Also, UML proposes Objects Diagram which is same to Classes Diagram, but fits better for runtime modelling needs.

Finally, a choice of a set of relations taken into consideration depends on a context and  point of view. UML provides some ones.


问:
How to use github, branches and automatic releases for version management?
I understand most of the basic Git/Github concepts by now, however I still have trouble understanding the bigger picture.

These are some things that I have managed to get working so far:

Push commits

Work with branches

Integrate Github with Travis CI, a continuous integration system

Via Travis CI, automatically build on every commit to master and put the release as a ZIP on Github under releases.

However I have only worked on alpha/beta versions of projects so far, so I've never seen versioned releases in practice yet.

Thus I want to learn more about versioning, maintaining separate versions, hotfixing the versions, etc.

How would I ensure that the following things happen:

Have different versions of my project, for example version 1.1.0 and 2.0.0

Have the ability to push hotfixes on the versions, sort of bumping the version to 1.1.1 or 2.0.1, etc.

Make a continuous integration system build that version automatically on commit and if succeeds, then publish a release for that specific version.

I am doubting between the following options:

Do I need to use tags for every version? If so, how can a continuous integration system build releases automatically?

Should I create branches for every version? If so, would that not create a whole ton of branches (like an 1.1 and a 2.0 branch, hotfixes go onto that branch of course)

How would I specify the version number? Is it okay to have a configuration file that specifies the version number, or are there smarter ways around it? In this case it would be a Java project, if that matters.

答:
Do I need to use a tag for every version?

No, you don't need to use tags at all. If you want to tag every release, that's fine, or if you want to tag every single time your CI system builds, you could do that too. Tags are essentially just giving a user friendly name to the commit, so that you can easily pull it up and view it later.

Should I create branches for every version?

Sure! Branching is cheap/free in Git, so I take advantage of it every chance I get. You can also merge in and delete branches fairly quickly as well. If you feel that you have to many branches you can always pare them down later with some selective merging. There are a slew of Git branching schemes available as well if you want to use a tried and true scheme.

How would I specify the version number?

Tags are usually the way you specify version number, as it pertains to git. If you're talking about how to version a project, or the best way to do that, you're going to have to do some digging, as it's a fairly opinion based question. Some projects stay in Beta forever, others increment whole number versions like they're going out of style (Looking at you chrome)


答:
Scanning your list I see version as your focus, so...

One way to maintain versions is with branches and merging (or rebasing).

So you have:

```<code>master
</code>```

then you create a branch

```<code>v1
</code>```

then you add more changes to

```<code>master(diff1)
</code>```

then you create a branch

```<code>v3
</code>```

then you add more changes to

```<code>master(diff2)
</code>```

Now:

To update Version 2 you now do

```<code>git checkout v2
git merge master  # for the changes you want to bring into version 2
# rebasing is also an option
# resolve any merge conflicts
# Done.
</code>```

To update version 3

```<code>git checkout v3
git merge master
</code>```

The above is for wholesale updates.

It's probably more likely though that you will want to pick out specific changes for that there is

```<code>git cherry-pick
</code>```

More on cherry picking at http://git-scm.com/docs/git-cherry-pick

Title: How to use github, branches and automatic releases for version management?

Body:
I understand most of the basic Git/Github concepts by now, however I still have trouble understanding the bigger picture.

These are some things that I have managed to get working so far:

Push commits

Work with branches

Integrate Github with Travis CI, a continuous integration system

Via Travis CI, automatically build on every commit to master and put the release as a ZIP on Github under releases.

However I have only worked on alpha/beta versions of projects so far, so I've never seen versioned releases in practice yet.

Thus I want to learn more about versioning, maintaining separate versions, hotfixing the versions, etc.

How would I ensure that the following things happen:

Have different versions of my project, for example version 1.1.0 and 2.0.0

Have the ability to push hotfixes on the versions, sort of bumping the version to 1.1.1 or 2.0.1, etc.

Make a continuous integration system build that version automatically on commit and if succeeds, then publish a release for that specific version.

I am doubting between the following options:

Do I need to use tags for every version? If so, how can a continuous integration system build releases automatically?

Should I create branches for every version? If so, would that not create a whole ton of branches (like an 1.1 and a 2.0 branch, hotfixes go onto that branch of course)

How would I specify the version number? Is it okay to have a configuration file that specifies the version number, or are there smarter ways around it? In this case it would be a Java project, if that matters.

Body:
Scanning your list I see version as your focus, so...

One way to maintain versions is with branches and merging (or rebasing).

So you have:

master

then you create a branch

v1

then you add more changes to

master(diff1)

then you create a branch

v3

then you add more changes to

master(diff2)

Now:

To update Version 2 you now do

git checkout v2
git merge master  # for the changes you want to bring into version 2
# rebasing is also an option
# resolve any merge conflicts
# Done.

To update version 3

git checkout v3
git merge master

The above is for wholesale updates.

It's probably more likely though that you will want to pick out specific changes for that there is

git cherry-pick

More on cherry picking at http://git-scm.com/docs/git-cherry-pick


问:
How to manage client expectations when working with a BDD type framework?
I've recently been investigating SpecFlow and can see the value of it for writing client/stateholder specs which can show a feature's progress however I'm nervous of introducing them to a client...

Imagine a feature:

```<code>Given I'm on the "MyAccount" page
   And I enter "Liath" into the "Name" textbox
When I click "Save"
Then my username should be "Liath"
</code>```

We write these features, show the client a set of red icons and set the developers to work.

If our developer completes the happy path then the icon will go to green and the client will see that feature is complete.

However our developer knows that they've still got to consider things like:

Checking the username to see if it's in use

Checking the username for profanity

Handle errors from the database

Some form of validation to ensure the username uses only valid characters

Clearly if a client sees a row of green lights they will be reluctant to continue paying for the rest of the development, it will look like we're trying to stretch out the work.

What is the value of these tests as a progress indicator if they indicate work is completed long before it is? What techniques would we need to use to give a more accurate example of progress?

答:
You have to come to an agreement on what "done" means for everything you deliver. You can give them a signed letter of agreement, a light, or a smoke-signal and if they think it means something else, you have a problem.  Being concerned with client misconceptions is universal in this business, so the only way to get around it, is to be constantly communicating and educating.

You can deliver all the green lights you want, but when your client looks at the app, they'll either like it or they won't. Hopefully, they'll tell you what they want to change and even better if they pay you for it instead of blaming your for misunderstanding them.

Many developers like showing clients UI sketches instead of working prototypes because they fear the client will think you're almost done and will be reluctant to approve additional billable hours.


答:
You should look at git-flow. It's an excellent (and popular) branching model.

Git Flow Summary

Branching

The main trunks that stay around forever are develop and master. master holds your latest release and develop holds your latest "stable" development copy.

Contributors create feature branches (prefixed with feature/ by convention) off of develop  :

```<code>$ git checkout -b feature/my-feature develop
</code>```

and hotfix branches (prefixed with hotfix/ by convention) off of master:

```<code># hotfix the latest version of master
$ git checkout -b hotfix/hotfix-version-number master

# or hotfix from a specific version
$ git checkout -b hotfix/hotfix-version-number <starting-tag-name>
</code>```

These branches are "disposable", meaning they have a short lifespan before they are merged back to the main trunks. They are meant to encapsulate small pieces of functionality.

Finishing Branches

When a contributor is done with a feature branch, they merge it back into develop:

```<code>$ git checkout develop
$ git merge --no-ff feature/my-feature
$ git branch -d feature/my-feature
</code>```

When they're done with a hotfix branch, they merge it back into  both master and develop so the hotfix carries forward:

```<code>$ git checkout master
$ git merge --no-ff hotfix/hotfix-version-number
$ git checkout develop
$ git merge --no-ff hotfix/hotfix-version-number
$ git branch -d hotfix/hotfix-version-number
</code>```

This is the continuous integration aspect.

Releases

When you're ready to start packaging up a release, you create a release branch from your "stable" develop branch (same as creating feature branches). You then bump the version number in a tag (described below).

Using separate release branches allows you to continue developing new features on develop while you fix bugs and add finishing touches to the release branch.

When you're ready to finish the release, you merge the release branch into both master and develop (just like a hotfix) so that all your changes carry forward.

Tagging

When you create a release branch or a hotfix branch, you bump the version number appropriately in a tag. With vanilla git, that looks like this:

```<code>$ git tag -a <tag-name> -m <tag-description>
</code>```

You'll then also have to push the tags (separately) to your remote repository:

```<code>$ git push --tags
</code>```

It's usually best to use semantic versioning in which your versions take the form major.minor.hotfix. Major bumps are backwards incompatible, whereas minor and hotfix bumps are not backwards incompatible (unless you're in beta, 0.x.x).

Merging

As you saw above, git-flow encourages you to merge branches with the following command:

```<code>$ git merge --no-ff <branch-name>
</code>```

The --no-ff option allows you to maintain all of your branch history without leaving a bunch of branches lying around in the current commit of the repository (so no worries, you won't have a branch for every version).

You're also encouraged to pull with

```<code>$ git pull --rebase
</code>```

So you don't add lots of useless merge commits.

You can configure git to do both of these things by default in your .gitconfig. I'll let you look that one up though ;)

Browsing versions

When someone is looking for a specific version of your codebase, they can checkout the tag by name:

```<code># checkout in detached HEAD to browse
$ git checkout <tag-name>

# OR checkout and create a new local branch (as you might for a hotfix)
$ git checkout -b <new-branch-name> <tag-name>
</code>```

Or, if someone is browsing on github, there is also a "tags" tab in the "branches" dropdown.

Using the git-flow extension (recommended)

My favorite way to use this model is with the git flow extension for git.

(Edit: Louis has recommended the AVH fork which works better with git describe and might be more active now. Thanks Louis. )

The extension automates all the messy parts (like using merge --no-ff and deleting branches after merging) so that you can get on with your life.

For example, with the extension, you can create a feature branch like so:

```<code>$ git flow feature start my-feature-name
</code>```

and finish it like so

```<code># hotfix the latest version of master
$ git checkout -b hotfix/hotfix-version-number master

# or hotfix from a specific version
$ git checkout -b hotfix/hotfix-version-number <starting-tag-name>
</code>```0

The commands for hotfixes and releases are similar, though they use the version number in place of a branch name, like so:

```<code># hotfix the latest version of master
$ git checkout -b hotfix/hotfix-version-number master

# or hotfix from a specific version
$ git checkout -b hotfix/hotfix-version-number <starting-tag-name>
</code>```1

Git flow then creates the version tag for you and kindly reminds you to bump the version in any configuration or manifest files (which you could do with a task manager like grunt).

Hope that helps :) I'm not sure exactly how you'd integrate it all with your Travis CI setup, but I'm guessing githooks will get you there.

Body:
You should look at git-flow. It's an excellent (and popular) branching model.

Git Flow Summary

Branching

The main trunks that stay around forever are develop and master. master holds your latest release and develop holds your latest "stable" development copy.

Contributors create feature branches (prefixed with feature/ by convention) off of develop  :

$ git checkout -b feature/my-feature develop

and hotfix branches (prefixed with hotfix/ by convention) off of master:

# hotfix the latest version of master
$ git checkout -b hotfix/hotfix-version-number master

# or hotfix from a specific version
$ git checkout -b hotfix/hotfix-version-number <starting-tag-name>

These branches are "disposable", meaning they have a short lifespan before they are merged back to the main trunks. They are meant to encapsulate small pieces of functionality.

Finishing Branches

When a contributor is done with a feature branch, they merge it back into develop:

$ git checkout develop
$ git merge --no-ff feature/my-feature
$ git branch -d feature/my-feature

When they're done with a hotfix branch, they merge it back into  both master and develop so the hotfix carries forward:

$ git checkout master
$ git merge --no-ff hotfix/hotfix-version-number
$ git checkout develop
$ git merge --no-ff hotfix/hotfix-version-number
$ git branch -d hotfix/hotfix-version-number

This is the continuous integration aspect.

Releases

When you're ready to start packaging up a release, you create a release branch from your "stable" develop branch (same as creating feature branches). You then bump the version number in a tag (described below).

Using separate release branches allows you to continue developing new features on develop while you fix bugs and add finishing touches to the release branch.

When you're ready to finish the release, you merge the release branch into both master and develop (just like a hotfix) so that all your changes carry forward.

Tagging

When you create a release branch or a hotfix branch, you bump the version number appropriately in a tag. With vanilla git, that looks like this:

$ git tag -a <tag-name> -m <tag-description>

You'll then also have to push the tags (separately) to your remote repository:

$ git push --tags

It's usually best to use semantic versioning in which your versions take the form major.minor.hotfix. Major bumps are backwards incompatible, whereas minor and hotfix bumps are not backwards incompatible (unless you're in beta, 0.x.x).

Merging

As you saw above, git-flow encourages you to merge branches with the following command:

$ git merge --no-ff <branch-name>

The --no-ff option allows you to maintain all of your branch history without leaving a bunch of branches lying around in the current commit of the repository (so no worries, you won't have a branch for every version).

You're also encouraged to pull with

$ git pull --rebase

So you don't add lots of useless merge commits.

You can configure git to do both of these things by default in your .gitconfig. I'll let you look that one up though ;)

Browsing versions

When someone is looking for a specific version of your codebase, they can checkout the tag by name:

# checkout in detached HEAD to browse
$ git checkout <tag-name>

# OR checkout and create a new local branch (as you might for a hotfix)
$ git checkout -b <new-branch-name> <tag-name>

Or, if someone is browsing on github, there is also a "tags" tab in the "branches" dropdown.

Using the git-flow extension (recommended)

My favorite way to use this model is with the git flow extension for git.

(Edit: Louis has recommended the AVH fork which works better with git describe and might be more active now. Thanks Louis. )

The extension automates all the messy parts (like using merge --no-ff and deleting branches after merging) so that you can get on with your life.

For example, with the extension, you can create a feature branch like so:

$ git flow feature start my-feature-name

and finish it like so

$ git flow feature finish my-feature-name

The commands for hotfixes and releases are similar, though they use the version number in place of a branch name, like so:

# Create hotfix number 14 for this minor version.
$ git flow hotfix start 2.4.14

# Create the next release
$ git flow release start 2.5.0

Git flow then creates the version tag for you and kindly reminds you to bump the version in any configuration or manifest files (which you could do with a task manager like grunt).

Hope that helps :) I'm not sure exactly how you'd integrate it all with your Travis CI setup, but I'm guessing githooks will get you there.


问:
What is the middleware pattern?
Here's a Ruby poject that implements the middleware pattern.  From the description, I have no idea what the pattern is, what it's useful for, and why other solutions wouldn't work as well.

What is the middleware pattern, and what are its advantages and drawbacks?

答:
I first came across the middleware 'pattern' in the node.js connect, and latter express, projects: it's just a clear and simple way of writing asynchronous code, where callbacks are slotted into an 'framework' API, each of which is expected to itself accept a callback parameter, which is to be executed when the routine is to return.
In the context of connect, which is an HTTP server application framework, all parts of the request cycle and application logic can be implemented or accessed, with chained callbacks.
Thus in this context, middleware is a self-contained unit of code that provides a service through a predefined API. It could be authentication and authorisation, request file-upload parsing, adjusting view data through an XSLT transform....
I suppose it follows the metaphor of the traditional use of the term, as described in an earlier answer.</p>

Title: What is the middleware pattern?


问:
Content CDNs and dynamic content
I am curious as to how dynamic web applications play with content delivery networks such as cloudflare, amazon cloudfront, etc. I understand the concept of a cdn obtaining a cache of your static pages and then serving those pages from their various servers relative to where the request is coming from. However when it comes to applications that are database heavy that require user sessions, allow for searches, and other user interaction is a cdn still useful?

If the answer is yes, does the cdn crawl your server and create caches of all of the pages that could be created dynamically?

If this is true then how is sensitive data handled? (For example if your application is pulling profile information specific to a user that only that user should have access to.)

答:
CDNs are used mostly for really static content: content which is the same for every or most users, and which will probably stay unchanged for days, weeks or months. CDNs are ideal for CSS files, JavaScript or images: they don't change much, they are usually cached for a year on client side anyway, and when they change, propagating the change to CDNs and clients is painless (using a revision number in the URI, such as global.css?r=514 is one of the ways to do it).

CDNs can also be used for content which is dynamic, but:

Either is identical for every user,

Or stays unchanged for days, weeks or months.

The more the content is dynamic, the less beneficial is the CDN. For example, you can use a CDN for a blog where content changes rarely (say a new blog post per week). While being dynamic, the content is the same for every user and doesn't need to be refreshed too often (for example, caching all blog posts for a hour is OK, because not being able to see the most recent post for an hour is acceptable in this case).

If the content is more dynamic, it is processed directly by the application servers, not the CDNs. By the way, crawling the website would be practically impossible, because the content will change during the crawling process or vary from user to user. For example, there is no way for a CDN to cache my Amazon purchasing page: not only do I need the up-to-date version of the webpage, containing my last purchase I've done five seconds ago, but there is no benefit of having a CDN at this level.

Note that since the primary goal of a CDN is to be close to the users (i.e. a user from New Delhi shouldn't be waiting for a server in Nevada to process his request), the same technique is used for large sites as well: dynamic requests are often processed by servers which are close enough to the users, when the company can afford building several data centers around the world.

Title: Content CDNs and dynamic content


问:
Open Source Service Discovery
I'm trying to wrap my head around this article on OSS service discovery and I'm having a tough time seeing the forest through the trees.

In that article, the author poses the main problem for service discovery:

The problem seems simple at first: How do clients determine the IP and port for a service that exist on multiple hosts?

But I'm not even sure what this means/implies. When talking about service discovery, what exactly are we talking about here? Is this like, if we want to connect to a database, we might need a host and port number defined somewhere, like:

```<code>host=mydatabase01.example.com
port=9300
</code>```

??? Is this what the author is talking about, and is what is implied by "service discovery"?

If so, wouldn't the (obvious) solution be to just put a web service in front of everything? That way, clients don't care about what specific host/port they're connecting to, they just make RESTful calls to, say, http://my-data-service.example.com.

It can't be this simple, as that article goes on to talk about things like ZooKeeper and Eureka, which seem to be very complex beasts. I'm clearly missing something; if so, can someone provide a specific, concrete use case of what is meant when we talk about "service discovery"?

答:
I'm the author of the article.

The context for the post is really around distributed systems and specifically service oriented architectures (SOA).  The solutions are usually used at larger software as a service (SaaS) providers where they have many backend services that are used to provide their service offering.

As an example, many SaaS providers have a way to login to their system. In a SOA, you might have an authentication service in the backend that handles login requests.  It's fairly common to have a web layer in front of those backend services that actually serves up the login page and handles the login HTTP requests.  That layer would delegate the login request to the authentication service.  It may also delegate other functions to other services on the backend.  Those backends might provide an HTTP based API or something else but it's commonly a service spread across multiple hosts.

Why can't you put a web service in front of everything?

You can and that's commonly done.  The service discovery aspect comes in when trying to keep http://my-data-service.example.com pointing to the right hosts when services are down, failing, being upgraded, scaled up, etc.

If my-data-service.example.com is just a round-robin DNS entry, and you have three instances providing the service and one goes down, you'll have some failed requests while that host is brought back online.  With DNS, you also have TTLs to consider so clients that have cached those entries will continue to try the downed host until the TTLs expire and it refreshes.  If you are adding hosts, you'll have to wait for the TTLs to expire as well before it starts to service requests.

An alternative is to point my-data-service-example.com to a load balancer or have your client applications implement some load balancing themselves.

This presents a new problem:

How do you keep the backend hosts configured in your load balancer up to date?

In an environment like AWS, hosts can be brought up and down frequently and their IPs can change.  If you are using docker, IPs and ports are usually different when a new container is started.  Trying to keep this configured manually is usually not possible in these kinds of environments... especially when you have multiple services and hundreds or thousands of hosts.

To keep a load balancer automatically up to date, you need some form of dynamic service discovery.

This usually entails having:

A registry to keep track of what is up/down, it's locations, etc.,

A registration process to register service locations when they are online

A discovery process to discover services and keep routing information up to date.

The original article describes how different companies have implemented those components in different ways.  There are many other ways to do it as well.

For a more concrete example, I wrote another post showing one way do service discovery with docker using etcd and haproxy.  That might be helpful to understand the context of the article.

Title: Open Source Service Discovery


问:
How to avoid redundant code in designing inheritance in C++
Say I have a Base class called Car and it has 3 derived  classes say Ford, Honda and  Audi.

The issue is, all three derived classes have exactly same code but minor difference in calling member functions of  their respective engines (these engines have separate class).

For example, Ford class calls code which is exactly same as other two  classes  but do call something like ford_engine-> start(),  ford_engine->clean() etc.

```<code>//ly  honda  calls   honda_engine->start()   honda_engine->clean();

//ly  Audi calls audi_engine->start()  audi->clean();
</code>```

Now here the issue is, it has redundant code in all three places with minute difference. How can I have code at one place, most  probably in base class and all derived classes use same code?

答: The idea is to add a read only protected member variable (i.e. a protected property) engine to your superclass. Then, redefine the accessor in the subclasses to return the proper engine instance. Your code become this->getEngine()->start() and so on.


问:
Is 'design with types first' ultimately the same as 'design with interfaces first'?
In Object Oriented Programming, we're taught to think in terms of Polymorphism (the idea that the implementation is decoupled from  the interface - and that it makes sense to think of the interface first).

This is expressed by Eric Gamma (author of Gang of Four Design Patterns Book)

Program to an interface, not an implementation

Later we learned that this is a way of solving The Expression Problem.

Other languages such as Clojure address 'The Expression Problem' using protocols.

Now coming out of Scala (and perhaps influenced by Haskell) we're seeing a design movement that says "Design your Types First". When I heard that - I thought I'd heard it before.

My question is: Is 'design with types first' ultimately the same as 'design with interfaces first'?

答:
In Java-like languages, interfaces describe object types, classes describe abstract data types. "Design with interfaces first" is not the same as "design with types first", simply because in a Java-like language classes (and primitives) are also types (but not object types). So, "design with interfaces first" really just means "do OO".

However, "design with types first" doesn't exactly mean what you think it means. The idea is that you use types to model your problem domain and let the types drive the design and development. It's more analogous to TDD in that sense: in TDD, the tests tell you what to do next, they tell you what to do, they tell you how to do it, they tell you what your design is, they tell you how to structure your code, and they tell you when you are done.

I would call it maybe Type-Driven Development (which conveniently and confusingly can also be abbreviated to TDD), because you use types in the same way that you use tests in TDD. It's not about designing with types first, it's about the types driving everything – designing them first is merely a prerequisite for that.


答:
Do I need to use tags for every version?

If by "version" you mean a set of files that make up a release or a release candidate, then I strongly recommend tagging every version. If you need to refer to version 1.2.7 down the road, do you want to hunt for a commit's hash or just use the version number?

Also if you use git describe to record build information somewhere (as I do), then using tags allows it to provide much nicer output.

If so, how can a continuous integration system build releases automatically?

A continuous integration system could build releases irrespective of how you use tags. You could tell it to build a release on the basis of a commit's hash. Tags make your life easier.

Should I create branches for every version? If so, would that not create a whole ton of branches (like an 1.1 and a 2.0 branch, hotfixes go onto that branch of course)

I don't see branching as being a "per-version" thing. I have a couple projects where my versions are all commits on the master branch. I don't need anything more complicated than this for now because neither project is at the stable stage and there is no need to support older versions long term. But let's say I release 1.0, 1.1, 1.2, then I release 2.0 and I still have to support the 1.0 series with security fixes, etc. Then I'd certainly have a branch to put the maintenance releases on for the 1.x series.

How would I specify the version number? Is it okay to have a configuration file that specifies the version number, or are there smarter ways around it? In this case it would be a Java project, if that matters.

Having a single source for your version number, like a configuration file, is the best way as it prevents fat finger errors that could otherwise occur if you have to update numbers in a number of places. I'm speaking from... hmm... embarrassing experience. You release 1.3 only to find that the software still reports that it is version 1.2. Oops!

In another answer, mxdubois recommended gitflow to you. If you do decide to use gitflow, I'd recommend using the AVH edition. The original version is no longer actively maintained. One notable difference is that the AVH edition performs release merges that allow git describe to work intelligently. The original version performs the merge in a way that trips git describe.


问:
Release management software
We've got a reasonably good release management process.  However large parts of it are manual tasks, i.e. Promoting builds to QA, deploying builds to internal groups, tracking releases, etc.

The builds and tests are all automated with CruiseControl.

Can anyone recommend some good release management / continuous deployment tools that I can use to automate the rest of our process?

答:
I'm not too familiar with CruiseControl, but many of these manual tasks can be automated within a CI tool.  I've used Hudson in the past, but I suspect CruiseControl will do it just fine.

If you work from trunk, create a "Promote build to QA" and a "Deploy to internal group" job, possibly with some sort of audit information.  This might call out to a Maven, Capistrano, or Fabric script (depending on your environment) to do the deed.  This doesn't require any special work - just a job that calls a shell script, possibly with some variables.

If you work in feature branches, you'll need to create a "Promote build to QA" or "Deploy to internal group" action on the builds being built against your feature branch.  This might require you to make a plugin for your CI system.  You might be able to use a job like above, but the job runner will need variables (like branch name or build number).

I'm not sure what you mean by tracking releases, but I've used two methods with CI tools in the past to keep track of when releases have gone out.  The first is making the release a Hudson job, which means you get a history of job runs (with output).  You can associate useful version data to the build in Hudson, so you can see at a glance which builds went out when.  The second is using a callback in your deployment process.  When the deployment is complete (or even if not), make a callback to your CI tool (or some other release tracker) that reports on the result (in Hudson, using either an external process monitor, or by triggering a build remotely).

Hope that helps.

ContentLicense: CC BY-SA 2.5

Title: Release management software


问:
What licenses are compatible with MASM32's license requirements?
The MASM32 documentation clearly states that the GPL violates MASM32's license, and therefore cannot be applied to projects built with MASM32.

The MASM32 project cannot be used to create open source software or any other project under any form of licence that requires the user of the MASM32 project to surrender the rights they are afforded under the MASM32 licence. In particular the MASM32 licence completely excludes projects licenced under the GNU organisation's published GPL licence and/or variants.

However, no guidance is given on what licenses are MASM32 compatible.  My best guess based on the general push for freedom and not restriction in the MASM32 license is that the MIT license would be compatible.  However, I'm not a lawyer.  Anyone else gone down this path already and figured out which licenses are able to be used with MASM32?

答:
```<code>#include <ianal.h>
</code>```

There are some key points in the MASM32 license that are in conflict with a number of different open source licenses.

Users of the MASM32 project must be willing to accept the full and unconditional responsibility for the software that they write using the MASM32 project.

This would seem to run counter to projects that are licensed under BSD and similar permissive licenses.  For example, from the BSD 2-clause license

This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

Converted to sentence case for ease of reading

Licenses such as Apache would not run into this problem.

Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

The key points that hit the GPL are enumerated in the "What you CANNOT do with the MASM32 Project"

The MASM32 Project is not an item of trade or commerce. It cannot be either purchased or sold.

The MASM32 Project cannot be re-licenced or made subordinate to any other form of licence.

None of its components or source code are redistributable.

You cannot use the MASM32 Project to write software for Non-Microsoft Operating Systems.

You cannot use the MASM32 Project to write any form of illegal software.

The project does not authorise the use of the Microsoft Trademark in your software or claims that your software is certified by Microsoft.

Note that points 4 and 5 specially run counter to the GPL which, I would assume, contends that writing malicious software (its defined in the license) is one of the freedoms that is protected by its license.

Furthermore, the MASM32 license doesn't require the distribution of the source.

Thus, it seems to read that a license that doesn't categorically disclaim warranty, or impose additional requirements on the author of the code (must distribute source upon request), or has some copyleft attached to the license.

Note, that this reading could be completely off.  From the license page:

The MASM32 project cannot be used to create open source software or any other project under any form of licence that requires the user of the MASM32 project to surrender the rights they are afforded under the MASM32 licence. In particular the MASM32 licence completely excludes projects licenced under the GNU organisation's published GPL licence and/or variants.

A valid reading of this is "nope, no open source licenses at all" in which case its the default you own it, 'nuff said license only.

The only authoritative source for this can come from a lawyer or Steve Hutchesson (the credited author of the license page).

OwnerDisplayName: Brian Knoblauch

Body:
#include <ianal.h>

There are some key points in the MASM32 license that are in conflict with a number of different open source licenses.

Users of the MASM32 project must be willing to accept the full and unconditional responsibility for the software that they write using the MASM32 project.

This would seem to run counter to projects that are licensed under BSD and similar permissive licenses.  For example, from the BSD 2-clause license

This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

Converted to sentence case for ease of reading

Licenses such as Apache would not run into this problem.

Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

The key points that hit the GPL are enumerated in the "What you CANNOT do with the MASM32 Project"

The MASM32 Project is not an item of trade or commerce. It cannot be either purchased or sold.

The MASM32 Project cannot be re-licenced or made subordinate to any other form of licence.

None of its components or source code are redistributable.

You cannot use the MASM32 Project to write software for Non-Microsoft Operating Systems.

You cannot use the MASM32 Project to write any form of illegal software.

The project does not authorise the use of the Microsoft Trademark in your software or claims that your software is certified by Microsoft.

Note that points 4 and 5 specially run counter to the GPL which, I would assume, contends that writing malicious software (its defined in the license) is one of the freedoms that is protected by its license.

Furthermore, the MASM32 license doesn't require the distribution of the source.

Thus, it seems to read that a license that doesn't categorically disclaim warranty, or impose additional requirements on the author of the code (must distribute source upon request), or has some copyleft attached to the license.

Note, that this reading could be completely off.  From the license page:

The MASM32 project cannot be used to create open source software or any other project under any form of licence that requires the user of the MASM32 project to surrender the rights they are afforded under the MASM32 licence. In particular the MASM32 licence completely excludes projects licenced under the GNU organisation's published GPL licence and/or variants.

A valid reading of this is "nope, no open source licenses at all" in which case its the default you own it, 'nuff said license only.

The only authoritative source for this can come from a lawyer or Steve Hutchesson (the credited author of the license page).


问:
Common techniques to integrate social media login to a website that requires account registration
I have developed websites where users would register with a username of their choice and an entry would be created in a database table that holds their username and some sort of salted password. They would then use this account to interact with the services that the site provides.

Now I am interested in providing the ability to sign up an account using facebook, twitter, and basically anything else that might be popular. However, I don't know how to integrate the login workflow into my system.

I have read the docs for Facebook Login but am still not sure how I would integrate it with my user-account design.

This is how my own registration workflow works

Choose username/password

Create an entry in the "users" table

Authenticate by checking the username and see if the password matches

With facebook login, they would ideally simply click a button that says "login with facebook" and they would authenticate with their facebook credentials. However, I don't know where I would go about creating a user to associate with their facebook identity.

So my question is...

What is a common way to use facebook (or other social media such as twitter or linkedin) to register an account into the system? I would like to manage all users uniformly, so no matter how they choose to register an account, they would all be handled in a single users table where I could do queries and associations without having to worry about how the account was created or how they logged in.

答:
Using server side Facebook api a typical workflow can be:

User click in "login with Facebook"

A popUp window with the Facebook login appears

The user put his Facebook username and password and click submit

You receive a callback from Facebook with a token.

With this token you go to Facebook auth service
(https://graph.facebook.com/oauth/access_token with your concrete parameters), you receive and access_token.

with this access_token you can get the user information, user id in Facebook, username, email, picture, etc,etc.

With this information you can check if this user already exists in your system or create a new one if is the fist time.

This is the typical Oauth2 workflow, very confusing the first time you use it. The good thing is that other social networks like LinkedIn, Twitter or Google+ use a very similar approach based in Oauth (with some differences for example in the way you express the concrete permissions you want and some other details).

Another option its to use the Facebook js api to do the login, this option its explained in the Facebook docs: https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.1 (the option with FB.login() it's in my opinion easier and cleaner). The problem with this approach its that it's not very standard and each provider can have very different approaches. (and if you use a lot of login providers you need to load a lot of js libraries only for login).


问:
What is convention based framework?
I'm reading about ColdBox, and I came across this word.

So what is meant by convention based framework?

答:
Like BitOff mentions, it means what others convention over configuration.  This seems to be confirmed by the ColdBox home page.

Basically, this means that instead of having configuration files describing details about a project - where to find files, which classes to instantiate, which URLs map to which classes, and so forth - the framework provides good defaults that allow you to just put the files and classes and methods in the right place and be done with it.

Title: What is convention based framework?


问:
In layman's terms, what is left recursion?
According to one page on code.google.com, "left recursion" is defined as follows:

Left recursion just refers to any recursive nonterminal that, when it produces a sentential form containing itself, that new copy of itself appears on the left of the production rule.

Wikipedia offers two different definitions:

In terms of context-free grammar, a non-terminal r is left-recursive if the left-most symbol in any of r’s productions (‘alternatives’) either immediately (direct/immediate left-recursive) or through some other non-terminal definitions (indirect/hidden left-recursive) rewrites to r again.

"A grammar is left-recursive if we can find some non-terminal A which will eventually derive a sentential form with itself as the left-symbol."

I'm just barely starting out with language creation here, and I'm doing it in my spare time.  However when it comes down to selecting a language parser, whether left recursion is supported by this parser or that parser is an issue that immediately comes up front and center.  Looking up terms like "sentential form" only leads to further lists of jargon, but the distinction of "left" recursion almost has to be something very simple.  Translation please?

答:
A rule R is left-recursive if, in order to find out whether R matches, you first have to find out whether R matches. This happens when R appears, directly or indirectly, as the first term in some production of itself.

Imagine a toy version of the grammar for mathematical expressions, with only addition and multiplication to avoid distraction:

```<code>Expression ::= Multiplication '+' Expression
            || Multiplication

Multiplication ::= Term '*' Term
                 || Term

Term ::= Number | Variable
</code>```

As written, there's no left-recursion here — we could pass this grammar to a recursive-descent parser.

But suppose you tried to write it this way:

```<code>Expression ::= Expression '*' Expression
            || Expression '+' Expression
            || Term

Term ::= Number | Variable
</code>```

This is a grammar, and some parsers can cope with it, but recursive descent parsers and LL parsers can't — because the rule for Expression begins with Expression itself. It should be obvious why in a recursive-descent parser this leads to unbounded recursion without actually consuming any input.

It doesn't matter whether the rule refers to itself directly or indirectly; if A has an alternative that starts with B, and B has an alternative that starts with A, then A and B are both indirectly left-recursive, and in a recursive-descent parser their matching functions would lead to endless mutual recursion.

Body:
A rule R is left-recursive if, in order to find out whether R matches, you first have to find out whether R matches. This happens when R appears, directly or indirectly, as the first term in some production of itself.

Imagine a toy version of the grammar for mathematical expressions, with only addition and multiplication to avoid distraction:

Expression ::= Multiplication '+' Expression
            || Multiplication

Multiplication ::= Term '*' Term
                 || Term

Term ::= Number | Variable

As written, there's no left-recursion here — we could pass this grammar to a recursive-descent parser.

But suppose you tried to write it this way:

Expression ::= Expression '*' Expression
            || Expression '+' Expression
            || Term

Term ::= Number | Variable

This is a grammar, and some parsers can cope with it, but recursive descent parsers and LL parsers can't — because the rule for Expression begins with Expression itself. It should be obvious why in a recursive-descent parser this leads to unbounded recursion without actually consuming any input.

It doesn't matter whether the rule refers to itself directly or indirectly; if A has an alternative that starts with B, and B has an alternative that starts with A, then A and B are both indirectly left-recursive, and in a recursive-descent parser their matching functions would lead to endless mutual recursion.


问:
What properties does an object oriented language have?
I'm currently working on a game and wanted to add some scripting support. Due to trying to keep the entire codebase in managed c# (Excluding Monogame), I am using a custom language for the scripting (No managed only implementations of Lua exist...except AluminumLua which is incomplete).

In such a language, basic provisions would need to exist. These would include:

Objects / Properties / Variables

floats and strings

Functions

Conditionals

Loops

Am I missing any major parts of a basic object oriented language?

EDIT:
As comments have pointed out, I would be far better finishing the incomplete implementation of Lua for C# rather than designing my own language...which is what I am going to do. However, I am still curious what the properties of an object oriented language are. So, what properties does an OO language have?

Some definitions of object orientation (again, decided in the comments):

Combining the state of an object with it's behavior.

An object oriented language is is a method of combining the state of an object (it's properties) with behavior (functions).

Object orientation is defining data (like a C struct) and providing specific methods to interact with it (the function ChangeValue), rather than give the person using that code the ability to change any part, including 'internal' components.

Object orientation is just a way to sort the data (that will be represented in binary) more clearly to a programmer and protecting against incorrect use (e.g. setting a char instead of a byte into a function).

答:
The core idea behind object-oriented programming is the encapsulation and information hiding of data and functions that operate on that data within objects. Rather than building an open data structure (think traditional C struct) and passing a pointer around to functions, you put the functions in the structure and call those functions directly.

Everything else builds on these core concepts, but if I had to name the bare minimum that makes an OO language, encapsulation and information hiding are it.

encapsulation means some structure contains data and functions: they are contained by the object.

Information hiding is the idea that an object's data is not directly accessible on the outside. It must be manipulated or used via its functions.

There are other features that are not core OO concepts but extend them in a way that is useful and are often included:

Inheritance: an object may extend another object, inheriting its data and functions and providing new ones. This is tied to the Liskov substitution principle where a subclass must be able to take the place of a superclass. The idea here is that by extending a superclass, a class can define additional behavior or even change the superclass implementation as long as it adheres to the contract of its interface.

Polymorphism: related to inheritance, where subclasses have different behavior in accordance with a common interface. The idea is that (at least with static polymorphism, commonly found in Java, C# and C++) if you need an object that does something, you can take an object with a given interface and expect different behavior based on its implementation and you don't care what the implementation is.

Many languages add more and more features, but these are the basics.


问:
What are memory addresses?
I have more or less 0 knowledge in low-level topics, so forgive my possible ignorance.

I know that in languages such as C, pointers hold 'memory addresses', i.e. strings (or binary data?) written in hex such as 0x52A132F3.

Judging by the term 'memory address', I assume this number actually leads to some place in memory. But I'm having a hard time understanding what a 'place in memory' actually is and how a hexadecimal number can 'lead' to it. (A Java programmer here..)

So two questions:

Do the memory addresses point to places on the CPU itself, or anywhere in the computer?

Is memory 'ordered' in hardware in some way that it makes sense to refer to it using an 'ordinal' number, such as 0x52A132F3? How is memory ordered in hardware, and how and why does it make sense to access it using a numerical value?

答:
mailing a letter is by far the best way to describe this, you have a name, number, street, town, zip code, maybe a suite number or other depending on where you live.

The letter leaves your house with all of this information on it and the post offices pick apart these items first leaving your house then some first level inspection to broadly figure out is it leaving this post office, is it leaving this town, etc.  a number of decisions and sorts along the way to get it to the postal person for that street/area and they sort it by house then deliver it.

The processor and the programmer (you indirectly but with a significant amount of help from the operating system) are you in your house, you have some reference material (your address book) of addresses to things (well lets say the operating system does not necessarily you) some of these things are just ram some are peripherals or control and status registers, etc.  there is some boundary in the processor or outside where this flatish address space lives, that boundary is your yard between your house and your mailbox on the curb.  the address is tossed onto this bus and then the postman takes over, layers of logic pick apart the address to determine where it needs to go back into the chip or out to peripherals or memory on the board.

So generically yes address can point to things in the cpu and to things outside the cpu.  Hardware designers generally dont like to make the work excessively difficult so usually one or a chunk of consecutive bits in the address are used to route the transaction.  some high bits might determine on chip or off for example and then some next bits down might determine ram from peripherals, and then once routed to a periperhals some more bits down may determine where in the peripheral.  there are also generally gaps do an lspci and look at the address ranges, just because a peripheral wants 32MB doesnt mean it has 32mb worth of individual things to talk to, it is just a nice power of 2 for logic to make decisions on once at the peripheral they may be wasteful if they choose with those bits for accessing a small number of things or efficient.

again the operating system, layered itself, has directly or indirectly the knowledge about that board and processor and generally hides it from you, you normally dont just poke a uart register, you instead call a function at the application layer which calls kernel functions which then eventually get to those registers that make the signals wiggle on the uart or whatever interface.  mmus if you have one virtualize addresses so that your application or every application may feel like it starts at some address like 0x0000 and has 0x000 to N bytes of memory to itself so that all programs can be compiled the same way but a translation in hardware and software (operating system) convert your 0x1234 address to some other address before it hits that magic boundary where it leaves the house and hits the mailbox in the post office domain where they just follow the rules for delivery same way every time (hardware).

Title: What are memory addresses?


答:
Few, if any, open-source licenses are usable. I can pretty firmly say that the MIT/X11 license, the Apache license, all forms of the BSD license, the Creative Commons - Attribution licenses, and the Mozilla Public License are all incompatible with the statements of the MASM32 license as all require some kind of "acknowledgement of origin" or "credit" to someone as part of their terms.

A little less firmly, I could say that use of MASM32 is basically incompatible with the Open Source Definition, as the tenets of the OSD include "No Discrimination Against Fields of Endeavor" (MASM32's idea of "illegal software" falls afoul of this) and "License Must be Technology-Neutral" ("only write software for Windows" falls afoul of this). This is a fuzzy, lawyer-requiring situation (I'm not one) — if your project is distributed under an OSD-compatible license, does the fact that MASM32's license prevents building it under certain situations void your license? Someone could in theory fork your code, remove the dependency on MASM32, and continue to distribute it under your license. I won't speculate.

But in my opinion using MASM32, or encouraging its author by taking its ludicrous demands seriously, constitutes bad form, even if you think you can work around them.

Title: What licenses are compatible with MASM32's license requirements?

Body:
The MASM32 documentation clearly states that the GPL violates MASM32's license, and therefore cannot be applied to projects built with MASM32.

The MASM32 project cannot be used to create open source software or any other project under any form of licence that requires the user of the MASM32 project to surrender the rights they are afforded under the MASM32 licence. In particular the MASM32 licence completely excludes projects licenced under the GNU organisation's published GPL licence and/or variants.

However, no guidance is given on what licenses are MASM32 compatible.  My best guess based on the general push for freedom and not restriction in the MASM32 license is that the MIT license would be compatible.  However, I'm not a lawyer.  Anyone else gone down this path already and figured out which licenses are able to be used with MASM32?


答:
properties of object oriented language are:

--> encapsulation
--> abstraction
--> Inheritance
--> polymorphism

Main Thing is Object and Classes

Any thing in Object oriented language converted into Objects

Title: What properties does an object oriented language have?

Body:
I'm currently working on a game and wanted to add some scripting support. Due to trying to keep the entire codebase in managed c# (Excluding Monogame), I am using a custom language for the scripting (No managed only implementations of Lua exist...except AluminumLua which is incomplete).

In such a language, basic provisions would need to exist. These would include:

Objects / Properties / Variables

floats and strings

Functions

Conditionals

Loops

Am I missing any major parts of a basic object oriented language?

EDIT:
As comments have pointed out, I would be far better finishing the incomplete implementation of Lua for C# rather than designing my own language...which is what I am going to do. However, I am still curious what the properties of an object oriented language are. So, what properties does an OO language have?

Some definitions of object orientation (again, decided in the comments):

Combining the state of an object with it's behavior.

An object oriented language is is a method of combining the state of an object (it's properties) with behavior (functions).

Object orientation is defining data (like a C struct) and providing specific methods to interact with it (the function ChangeValue), rather than give the person using that code the ability to change any part, including 'internal' components.

Object orientation is just a way to sort the data (that will be represented in binary) more clearly to a programmer and protecting against incorrect use (e.g. setting a char instead of a byte into a function).


问:
Any OOP design pattern that is somewhat representative of all of the SOLID OOP design principles at play?
I'm trying to teach an object oriented design principles course (on SOLID) at a training institute. I also want to teach the students a few OOP design patterns such as factory, singleton and one other. I know there is no 1 to 1 match between SOLID principles and OOP Design patterns, but I want to introduce the students a pattern that is sort of inclusive of all the SOLID design principles at play.

Any ideas?

I'm really trying to fit in the observer pattern but want to keep it conforming with all the SOLID principles.

答:
One of the most popular design pattern among the community here is the strategy pattern. And yes, if you build some example code around this pattern, you can demonstrate all the SOLID principles:

S = is fulfilled when each strategy subclass is only responsible for exactly one task, and the "context" class does not take responsibilities which belong into the strategy classes

O = you can add new strategies afterwards ("open for extentions") without the need to change the internals of the context ("closed for modifications")

L = this means to implement the strategy subclasses correctly with the semantics defined by the strategy interface, not changing the semantics in any of the subclasses. LSP would not be fulfilled when a subclass implements the strategy interface in a manner which breaks the parts of the context using the strategy.

I = is fulfilled when the strategy base class offers only a small, single-purpose interface (like the one "execute" method)

D = the context relies completely on the abstract strategy interface, it gets the concrete strategy "injected" from outside (for example, at construction time) and does not make any assumptions about, for example, a fixed set of subclasses, or the availability of specific subclasses.

Note that the pattern itself does not guarantee your code to be SOLID, it is more that the SOLID principles help you to implement the pattern correctly. You may consider to show your students not only correct examples for applying the SOLID principles, but also counter-examples in context of a strategy pattern, showing code which breaks each of the five principles. Or even better: make this an exercise for them.

ContentLicense: CC BY-SA 4.0


问:
In Agile, should I create a code-review task?
My team uses Agile as a development approach. Currently, each task has four states which are todo, in progress, testing, and done.

We've just started doing code reviews, and I wonder if I need to create a code-review task or I should add time for code-review to the estimation?

答:
Reviews are part of the work that needs to be done to bring a task to completion, just like implementation and testing. For that reason, the review effort should be included in the estimation for the task.

As you already have different states for implementation and testing, it makes sense to add an additional state to indicate that the code for a task is being reviewed.

On a side note, if you find that implemented tasks often can't be picked up immediately for review or testing (because the other team members are busy on other tasks), you might want to add kanban-like "waiting states" to your tasks, like "ready for review" and "ready for testing". This can make it clear if there might be a bottleneck in the review and/or test phases, by having a pile up of tasks in the "ready for" states. It also means that the one who wrote the code doesn't have to assign a reviewer/tester (or ask around for one), but anyone with a spare moment can pick up a pending review/test task.


答:
We have used both. When you have a seperate review task you can assign time to that task and it is visible for everybody. But you get a lot of tasks on the board. We use a whiteboard with post-its so real estate is limited, being somewhat of a disadvantage.

At the moment we use a seperate state for review. This is less of a hassle when updating for a new sprint. An we use it also to have the code functional reviewed. In our team another developer does the technical code review and the domain specialist does a functional review.

For now a seperate state is our favoured method.

Title: In Agile, should I create a code-review task?

Body:
My team uses Agile as a development approach. Currently, each task has four states which are todo, in progress, testing, and done.

We've just started doing code reviews, and I wonder if I need to create a code-review task or I should add time for code-review to the estimation?


问:
Should an object query its owner?
I have a World

```<code>class World:
    def __init__(self):
        self.size = 10
        self.n_busStops = 10

        self.busStopMatrix = SpatialGraph(self.size, self.n_busStops, 1.0)
        self.buses = [Bus([0,1,2,3,4,5,6,7,8,9])]
</code>```

Now each of the buses are going to move around the world, dropping off and picking up passengers.

The bus contains information about its route. When it gets to its next stop, it needs to query the busStopMatrix to find out how many passengers there are there, and how far away the next stop on its route is.

Is it a good idea for an object to query its parent like this? If so, what is this design pattern called?

Something like:

```<code>class World:
    def __init__(self):
        self.size = 10
        self.n_busStops = 10

        self.busStopMatrix = SpatialGraph(self.size, self.n_busStops, 1.0)
        self.buses = [Bus([0,1,2,3,4,5,6,7,8,9], owner =self)]

class Bus:
    def __init__(self, route, parent):
        self.route = route
        self.currentStop = route[0]
        self.parent = parent
    def move(self):
        ifAtDestination():
            pickUpPassengers(self.parent.getPassengersAtStop(currentStop))
</code>```

I otherwise can't think how the Bus can get information about the world it is in. The alternative I can think of is that the route is made up of references directly to the BusStops, so it can directly query them.

eg.

```<code>class World:
    def __init__(self):
        self.size = 10
        self.n_busStops = 10

        self.busStopMatrix = SpatialGraph(self.size, self.n_busStops, 1.0)
        self.buses = [Bus([busStopmatrix.getAllStops()])]

class Bus:
    def __init__(self, route):
        self.route = route
        self.currentStop = route[0]

    def move(self):
        ifAtDestination():
            pickUpPassengers(currentBusStop)
</code>```

答:
You have one quite elegant way to do it also which consists in providing your Bus class with a function in the constructor to retrieve the passengers:

```<code>class World:
def __init__(self):
    self.size = 10
    self.n_busStops = 10

    busStopMatrix = SpatialGraph(self.size, self.n_busStops, 1.0)
    self.buses = [Bus([0,1,2,3,4,5,6,7,8,9], owner = self.getPassengersAtStop)]

class Bus:
    def __init__(self, route, passenger_function):
        self.route = route
        self.currentStop = route[0]
        self.passenger_function = passenger_function
    def move(self):
        ifAtDestination():
            pickUpPassengers(self.passenger_function(currentStop))
</code>```

This way, you don't really depend on the name of a function or whatever and Bus is unaware of the World class.

Title: Should an object query its owner?

Body:
You have one quite elegant way to do it also which consists in providing your Bus class with a function in the constructor to retrieve the passengers:

class World:
def __init__(self):
    self.size = 10
    self.n_busStops = 10

    busStopMatrix = SpatialGraph(self.size, self.n_busStops, 1.0)
    self.buses = [Bus([0,1,2,3,4,5,6,7,8,9], owner = self.getPassengersAtStop)]

class Bus:
    def __init__(self, route, passenger_function):
        self.route = route
        self.currentStop = route[0]
        self.passenger_function = passenger_function
    def move(self):
        ifAtDestination():
            pickUpPassengers(self.passenger_function(currentStop))

This way, you don't really depend on the name of a function or whatever and Bus is unaware of the World class.


问:
Should I store x,y coordinates as an array, a class object, or two variables?
I have a MyObject which has an x and y coordinate.

as far as I can see, I can store it in three ways:

```<code>class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class MyObject:
    def __init__(self, x, y):
        self.position = [x, y]

class MyObject:
    def __init__(self, x, y):
        self.position = Coord(x,y) #Coord class created elsewhere
</code>```

Is there a best practise either way for this ?

Where I'm thinking this is relevant, is when passing these coordinates into other methods:

eg.

```<code>myObj = MyObject(0,0)
searchLocation(myObj.x, myObj.y)
searchLocation2(myObj.position)
</code>```

答: I think that the third implementation of MyObject is the best since it separates the object from the 2D math of the coordinate system. ( you can implement a complete math library for the coordinates and it is completely independent from the objects you create ). Now in order to make the objects more flexible you could create functions that take either two numbers for x and y or a Coord object and be prepared to add more as your system grows.</p>


答:
Yeah it depends how much of a "first class citizen" the position is. If lots of other objects consume or produce it and/or there's behaviour to do with positions you want to capture/enforce (as per Gus's answer), then you're probably better off making it its own class.

If you do go for making it its own class, you should definitely move away from taking the x and y elements in the constructor to MyObject and instead make it take a Position object. There's probably no reason why MyObject should be aware of what a Position object needs to be constructed, at least not obviously from the example given (though I accept there may be reasons to not do this in some situations).

Title: Should I store x,y coordinates as an array, a class object, or two variables?

Body:
I have a MyObject which has an x and y coordinate.

as far as I can see, I can store it in three ways:

```<code>class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class MyObject:
    def __init__(self, x, y):
        self.position = [x, y]

class MyObject:
    def __init__(self, x, y):
        self.position = Coord(x,y) #Coord class created elsewhere
</code>```

Is there a best practise either way for this ?

Where I'm thinking this is relevant, is when passing these coordinates into other methods:

eg.

```<code>myObj = MyObject(0,0)
searchLocation(myObj.x, myObj.y)
searchLocation2(myObj.position)
</code>```