问:
Progress bar for unknown number of items
I am working on a survey-based feature in our application and the survey has branching points at any given question depending on the answer given. Each path that a branch can take may not have the same number of questions. So if we evaluated each possible path that can be taken, you may end up with a different number of total questions answered each time.

I've been told a progress bar is required for the survey, however I can't imagine how a progress bar could provide meaningful data in this context. We do not know how many questions must be answered until the survey ends without hindsight. Can anyone recommend a good logical solution to implementing a progress bar for such a feature?

I don't need specifics. The UI system I'm using, the language I'm using, all of that is irrelevant. I want a strictly mathematical solution to this problem, should one exist. If not, then using things like estimations, averaging, or other "guesstimates" are also good but last resorts.

Thanks in advance.

答:
Approach 1:  Subdivide sections.

You've got four sections, each section is thus 25% of the total survey in this model.  If you answer a question at the start of section 1 that leads to the path of "skip all the rest of section 1" that then has you 25% done.

Within each section, you have some questions and maybe other branching paths.  If section 1 has 5 questions, each question in section 1 is then 5% of the total survey... no matter how many questions are in section 2.

easy to calculate

questions have different values

Approach 2: Based on the long case

Lets say you have 100 questions that could be asked.  Each question is 1% of the total.

If you answer question #5 in such a way that it skips to question #10 you go from 5% complete to 10% complete.

easyish to calculate

still possible to have jumps

smoother transitions for each unit done

Note that if you have two paths:

Answer A (5%) -> 3 questions -> C (10%)

Answer B (5%) -> 5 questions -> C (10%)

You've got the situation where while the questions on path A are worth 1%, you will either have non-unit increment questions or a skip (5%, 6%, 7%, 8%, 10%)


答:
Given that it's a feature designed to provide the user with an estimate of time until completion I would suggest determining the 'progress' level by the longest possible number of questions remaining. Unless you have an infinite loop possible in the survey, this will provide reasonable and useful feedback for your users.

If the survey can be up to 100 questions then your progress would be

100-(current_question.longest_dist_to_finish())

At the start this will always be an empty bar and it should get more and more accurate as choices start disappearing.

ContentLicense: CC BY-SA 3.0

Title: Progress bar for unknown number of items

Body:
I am working on a survey-based feature in our application and the survey has branching points at any given question depending on the answer given. Each path that a branch can take may not have the same number of questions. So if we evaluated each possible path that can be taken, you may end up with a different number of total questions answered each time.

I've been told a progress bar is required for the survey, however I can't imagine how a progress bar could provide meaningful data in this context. We do not know how many questions must be answered until the survey ends without hindsight. Can anyone recommend a good logical solution to implementing a progress bar for such a feature?

I don't need specifics. The UI system I'm using, the language I'm using, all of that is irrelevant. I want a strictly mathematical solution to this problem, should one exist. If not, then using things like estimations, averaging, or other "guesstimates" are also good but last resorts.

Thanks in advance.


问:
How to use specific Request Header
I am learning how to work with XMLHttpRequests. I know that request.setRequestHeader() is an important factor. I just don't understand why. It took me a while but I have at least found a list of Headers here and here, but I still don't understand what each one of them does, and what value goes with each. Is there a resource that gives an example and explains what they are for? </p>

答:
A quick search found: http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039

(no offense from the title; it looked like a pretty thorough article) Skip down to "HTTP Headers in HTTP Requests"

Just eyeballing the list, the most important headers are for "content negotiation":

Content-Type Most servers will need this to parse & route your request to the right function:

Content-Type: application/json

Accept Tells the server what it can send back

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Authorization In my work, I usually have to provide an authorization key. But the server will tell you whether you need this or not.

Authorization: Bearer aasdadadadadadsasd

The other ones are either optional, or get added by the browser. You can open the dev console in your browser and look at the network messages going back and forth & do a search on individual headers to see what they mean.

Title: How to use specific Request Header


问:
What are the hardest parts of the C++/C#/Java programming languages?
Just wondered what are the features of the three main programming languages which show you are an 'expert'? Please exclude 'practical' skills such as indenting.

Am I right in saying for C++ the most difficult aspect to master is STL/generics? Java seems much easier as memory is handled for you. I'm not entirely sure on C# either?

I'm trying to use this to guage my current level of ability and what i wish to aim for.

ps this was posted on stackoverflow but got binned due to arguing, please do try to keep it civil as I am really interested in the answers from everyone :)

答:
C - pointers

C++ - pointers and STL/Templates

C# - the gigantic libraries

Java - the gigantic libraries

OwnerDisplayName: tom

ContentLicense: CC BY-SA 2.5


问:
What Is The Process of Creating A Bug Bar?
In my company, we're working on adopting the Microsoft Secure Development Lifecycle, and part of the MSDL process involves establishing security and privacy bug bars at the onset of a project. I've heard the concept of a bug bar prior to MSDL, and I understand that it's essentially a definition of what level/amount of bugs you're willing to accept in a final product, but I've never understood how to creating a bug bar for a project. Are there any well documented processes for establishing bug bars that I can learn from?

I've tried doing some Googling for examples or real world scenarios of projects defining bug bars at the onset of a project, but I can't seem to get any good results or tips on the process of establishing a bug bar. There are MSDL examples of what appear to be completed bug bars, but I'm interested in learning about the process of defining something like this. For example, for those that have done something like this before, have you defined bugs bars in a very specific way (e.g. saying "There shall be no unauthorized file system access: reading from the file system"), or have you taken a deferred approach of saying when we find bugs we'll rate them on a 1 to 5 scale (5 being the most severe), establish now that no bugs above a 3 shall be shipped, and leave your ranking of bugs until they're discovered? I feel like the trying to do the former is a foolish and impossible activity, but the later is prone to bias towards leniency when a project is coming down to the wire.

Can anyone provide me with a well documented approach for defining/creating bug bars?

答:
Let's start with a basic definition for Bug Bar:

Quality gates and bug bars are used to establish minimum acceptable
  levels of security and privacy quality. A project team must negotiate
  quality gates (for example, all compiler warnings must be triaged and
  fixed prior to code check-in) for each development phase. A bug bar is
  a quality gate which is used to define the severity thresholds of
  security vulnerabilities—for example, no known vulnerabilities in the
  application with a “critical” or “important” rating at time of
  release. The bug bar, once set, should never be relaxed.

When a software user files a bug report, they must assign a STRIDE category to the bug, whether the bug is a client or server bug, and what scope the bug affects.  Users can be software developers and QA staff.  STRIDE stands for:

Spoofing

Tampering

Repudiation

Information Disclosure

Denial of Service (DoS)

Elevation of Privilege (EoP)

The relevant "scope" values are

Client - Spoofed trusted UI in common/default scenario

Client - Spoofed trusted UI in specific other scenario

Client - Spoofed UI as part of a larger attack scenario

Server - Spoofed specific user or computer over secure protocol

Server - Spoofed random user or computer over secure protocol

Client - Tampered trusted data that persists after restart

Client - Tampered data that does not persist after restart

From there, a matrix is created that assigns a level of severity to each combination.  The possible values for level of severity are:

Critical

Important

Moderate

Low

None

Example entry in matrix (there can be several such entries):

STRIDE Category: Spoofing

  Scope: Client - Spoofed trusted UI in common/default scenario

Description: Ability for attacker to present a UI that is different from but visually identical to the UI that users must rely
  on to make valid trust decisions in a default/common scenario. A trust
  decision is defined as any time the user takes an action believing
  some information is being presented by a particular entity—either the
  system or some specific local or remote source.

Severity Level: Important

Microsoft claims that they fix all bugs that are higher than "low" importance before deploying.

Further Reading

Add a Security Bug Bar to Microsoft Team Foundation Server 2010

New SDLC: Security Development Life Cycle

ContentLicense: CC BY-SA 4.0


问:
A module which is used by most other modules
I am pursuing object oriented design. So we don't want to use globals but yet sometime we have a module that most other modules use.  This means we have to just pass it to all other modules and this can be literally all modules!

```<code>class Logger
{
public:
    Logger(void);
    ~Logger(void);
};

class Calculator
{
public:
    Calculator(Logger *logger);
    ~Calculator(void);
};

class Taxation
{
public:
    Taxation(Logger *logger);
    ~Taxation(void);
};
</code>```

So the idea is that the Calculator and Taxation modules use the Logger module to log everything. Similarly most other modules will use it too, and logging is required everywhere. Is this method okay or should Logger be global instead?

答:
Avoiding global variables (and singletons, that are global variables in disguise) is a good thing to strive for. The most important is not to think about it as global and singletons being impure OO, that doesn't get you anywhere. The important concept to keep in mind is 'dependencies'. Any dependency that is explicitly injected into the client is loosely coupled. Any dependency that is invisible from the outside of the client is tightly coupled.
Yes, it takes more code to explicitly inject dependencies, but your code ends up being more flexible, more testable and also easier to reason about.

In C++, if you can, inject your dependencies as template parameters. If that isn't an option, consider using std::function. Passing by raw pointer isn't a good idea, but you could consider using a const reference.

B.t.w, a while ago resulting from a linkedin discussion I created a logging library (that later others contributed to) excactly for the reason that in logging libraries the singleton pattern is grocely overused. There is no need to use singletons (or global variables) for things like a logging library.

http://pibara.github.io/libKISSlog/

In other situations, singletons are often used in resource management scenario's. This blog post on an alternative to global variables and singletons for scarce-resource allocation, may be useful:

http://minorfs.wordpress.com/2013/01/18/raiicap-pattern-injected-singleton-alternative-for-c/

OwnerDisplayName: zadane


问:
Disadvantages of scoped-based memory management
I really like scope-based memory management (SBMM), or RAII, as it is more commonly (confusingly?) referred to by the C++ community. As far as I know, except for C++ (and C), there's no other mainstream language in use today that makes SBMM/RAII their main memory management mechanism, and instead they prefer to use garbage collection (GC).

I find this rather confusing, since

SBMM makes programs more deterministic (you can tell exactly when an object is destroyed);

in languages that use GC you often have to do manual resource management (see closing files in Java, for example), which partly defeats the purpose of GC and is also error prone;

heap memory can also (very elegantly, imo) be scope-bound (see std::shared_ptr in C++).

Why is not SBMM more widely used? What are its disadvantages?

答:
First off, its very important to realize that equating RAII to SBMM. or even to SBRM. One of the most essential (and least known or most under appreciated) qualities of RAII is the fact that it makes 'being a resource' a property that is NOT transitive to composition.

The following blog post discusses this important aspect of RAII and contrasts it to resource amangement in GCed languages that use non-deterministic GC.

http://minorfs.wordpress.com/2011/04/29/why-garbage-collection-is-anti-productive/

Its important to note that while RAII is mostly used in C++, Python (at last the non-VM based version) has destructors and deterministic GC that allows RAII to be used together with GC. Best of both worlds if it were.


问:
Encrypt and decrypt password for a specific application
I have a basic web application where users can login and edit their profile. In the profile they can submit an username and a password for a different application. I'd like to take that password and encrypt it. Later, when I want to connect to that different application I need to decrypt the password.

Is there a common pattern for this scenario? Or some other advice you might have?
Just in case it matters, I want to connect to JIRA without having the user have to submit his password on every request / login to the page.

Thanks, Sven

Update
To make it more clear, I have a web appliction where users can signup/login/etc, this uses a authentication/authorization library (friend) and its all well.
However, from my webapp I want users to connect to a jira instance that they can choose and where they have to provide a username/pw combo which I cannot hash, because I need to send them unhashed to the JIRA instance.

What I am thinking of right now is to display a login dialog to the user as soon as he wants to request his JIRA instance. There he provides his username/password combo for JIRA and I send a REST request to JIRA from the client side, so no user/password is sent to my server.
I get a sessionid back then, which I can use for further requests. What do you think about that approach?

答:
I would suggest two things.

Don't do security yourself unless you really know what you are doing, or are experimenting on a trivial application that real strangers / customers are not going to use.

You should not be storing passwords, even encrypted passwords. Look into 'hashes' and 'salts', 'rainbow tables' and password security. When a user tries to connect, the password they enter should be securely hashed and compared against the hash of the originally set password. As a hash function is one way, even if an attacker got hold of the list of users's hashed passwords they could not recover the original passwords (I say could not, that depends on your implementation of this theory and the compute power of the attacker).

EDIT:

In response to the comments:
I'm not aware of patterns for that, sorry.
In which case I guess you need to be holding the passwords so encrypting them is the best you can do. You could save the encrypted passwords on the users machine, send them to your server encrypted, decrypt them and send them on to authenticate against JIRA using a secure connection. That way even if your server was hacked you wouldn't be storing passwords at your end. If a user's machine is compromised there are worse things that they could do than try to crack your encryption for just one password. When chrome stores user's passwords they aren't that secure but Google have said that they don't want to give people a false sense of security and so they have no plans to improve it.


问:
How do I learn linking compiling, makefile quickly? Any book recommendations?
I'm very good at programming in C++ but when it gets to linking and the other important stuffs I feel very ignorant. I want to learn allegro without wasting time. So please suggest a book or a resource to learn the concepts mentioned above. Thanks a lot in advance.</p>

答:
I want to learn allegro without wasting time.

conflict detected.

if you want to develop a game without wasting time, start with a complete game engine like Quake

[yes, i've used Allegro.]


问:
What is a scalable and practical way to search existence of a group of strings in a huge file
Context: I built an app which generates around 1000 domain names based on user input. I need to check if they are available or not by matching against a huge zone file of parsed domain names which is around 2 GB.

I have an amazon micro instance and cannot store the text file in there due to space constraints.
I am expecting around 100k - 200k and more in search queries per month.

Naive approach (Potentially):
1. Store the text file in dropbox. Then get the contents of the file and search for the strings and spit out the available domain names on the EC2 instance.

I only need to check if domains exist or not. Should I have to store it in a database?

Some Info:  There are currently 100 million dot com names registered according to Verisign.
And my parsed domain names are one on each line.
Like:

GOOGLE

APPLE

FACEBOOK

STACKOVERFLOW etc

What is the best and practical way to deal with the problem? Ideally the checking should take only a few seconds. But I am fine with anything that works at this point.

答:
Should I have to store it in a database?

That would be the simplest solution.  Look for a light-weight (non-transactional) database library.

Another idea would be to convert the zone file into a compressed word list, treating each domain name as a "word".  This will give you better compression, and if you choose the right scheme, you should be able to get fast and accurate lookup without keeping the whole "file" in memory.

A variation on the above would be to treat name components as words, and treat this as free-text search problem.  Build a reverse index, and treat the search for a domain name as a search for a set of words; e.g. "www.example.com" is a search for "www" AND "example" AND "com".  This is significantly more complicated, but it might give better compression overall, and it would allow you to do other queries.

There is a lot of literature on the subject of text search ...

Putting the (original) file into an external file service and fetching / searching it is a poor idea.  It takes a significant amount of time to stream a 2Gb file from one machine to another over the internet ... and you will probably end up paying for the I/O bandwidth you are using.  You would be better off paying up front for storage on the Amazon infrastructure.


答:
a) an indexing engine, like Lucene

b) Bloom filter http://en.wikipedia.org/wiki/Bloom_filter

c) You could use a simple key hashing scheme, and split your domains up by a simple "hash modulo N" to divvy the work across multiple (simple) datastores.

BTW 2GB is tiny. You could easily do the whole thing in memory.

Also, since you've already normalized your strings into a standard format, I'd focus on storing and doing lookups on the hashes of strings rather than the strings themselves.

...

Full disclosure: I'd probably just store them in a database.

Title: What is a scalable and practical way to search existence of a group of strings in a huge file

Body:
Context: I built an app which generates around 1000 domain names based on user input. I need to check if they are available or not by matching against a huge zone file of parsed domain names which is around 2 GB.

I have an amazon micro instance and cannot store the text file in there due to space constraints.
I am expecting around 100k - 200k and more in search queries per month.

Naive approach (Potentially):
1. Store the text file in dropbox. Then get the contents of the file and search for the strings and spit out the available domain names on the EC2 instance.

I only need to check if domains exist or not. Should I have to store it in a database?

Some Info:  There are currently 100 million dot com names registered according to Verisign.
And my parsed domain names are one on each line.
Like:

GOOGLE

APPLE

FACEBOOK

STACKOVERFLOW etc

What is the best and practical way to deal with the problem? Ideally the checking should take only a few seconds. But I am fine with anything that works at this point.


问:
Unit testing, factories, and the Law of Demeter
Here's how my code works. I have an object that represents the current state of something akin to a shopping cart order, stored in a 3rd party shopping API. In my controller code, I want to be able to call:

```<code>myOrder.updateQuantity(2);
</code>```

In order to actually send the message to the third party, the third party also needs to know several things that are specific to THIS order, like the orderID, and the loginID, which will not change in the lifetime of the application.

So when I create myOrder originally, I inject a MessageFactory, which knows loginID. Then, when updateQuantity is called, the Order passes along orderID. The controlling code is easy to write. Another thread handles the callback and updates Order if its change was successful, or informs Order that its change failed if it was not.

The problem is testing. Because the Order object depends on a MessageFactory, and it needs MessageFactory to return actual Messages (that it calls .setOrderID() on, for example), now I have to set up very complicated MessageFactory mocks. Additionally, I don't want to kill any fairies, as "Every time a Mock returns a Mock a fairy dies."

How can I solve this problem while keeping the controller code just as simple? I read this question: https://stackoverflow.com/questions/791940/law-of-demeter-on-factory-pattern-and-dependency-injection but it didn't help because it didn't talk about the testing problem.

A few solutions I've thought of:

Somehow refactor the code to not require that the factory method return real objects. Perhaps it's less of a factory and more of a MessageSender?

Create a testing-only implementation of MessageFactory, and inject that.

The code is pretty involved, here's my attempt at an sscce:

```<code>public class Order implements UpdateHandler {
    private final MessageFactory factory;
    private final MessageLayer layer;

    private OrderData data;

    // Package private constructor, this should only be called by the OrderBuilder object.
    Order(OrderBuilder builder, OrderData initial) {
        this.factory = builder.getFactory();
        this.layer = builder.getLayer();
        this.data = original;
    }

    // Lots of methods like this
    public String getItemID() {
        return data.getItemID();
    }

    // Returns true if the message was placed in the outgoing network queue successfully. Doesn't block for receipt, though.
    public boolean updateQuantity(int newQuantity) {
        Message newMessage = factory.createOrderModification(messageInfo);

        // *** THIS IS THE KEY LINE ***
        // throws an NPE if factory is a mock.
        newMessage.setQuantity(newQuantity);

        return layer.send(newMessage);
    }

    // from interface UpdateHandler
    // gets called asynchronously
    @Override
    public handleUpdate(OrderUpdate update) {
        messageInfo.handleUpdate(update);
    }
}
</code>```

答:
I'm going to agree with @Robert Harvey. Just to be clear: Demeter is reasonable and good programming style. It's the "no mocks from mocks" that strikes me as more of a subjective preference supporting a particular coding style rather than a generally applicable (& well justified) practice. The fairy rule takes out "fluent" interfaces like:

Thing.create("zoom").setDomain("bo.com").add(1).flip().reverse().tuneForSemantics().run();

Kind of an extreme example, but essentially the fairy rule would disallow including that class in any code, because the code would become untestable. But that's a popular paradigm in OO code.

Also, the more general problem is how to mock a factory to return a mock you want to test with. I'm generally shy of using Factories as dependencies, but sometimes it's much better than the alternative. If you end up with

ThirdPartyThing ThirdPartyFactory<ThirdPartyThing>#create()

I don't see how you can get around it. You need a mock to return the mock. So that rule kind of knocks out two really powerful OO design patterns.

I can't think of a way to work around your problem without splitting that method into 2 or 3, pushing long lines up to the client, or else creating a weird stateful wrapper class.

I'd be really interested to see what the alternative looks like.

My answer: your code is fine! Excelcior!

(actually I'm curious about alternatives)

...

Let's take an boundary case: are mocks allowed to return themselves? Technically, they are returning a mock. If not, then that knocks the GoF prototype out, and that's one of the patterns that has held up over time:

```<code>MuActor prototype = ...
...
MuActor actor = prototype.create();
actor.run();
</code>```

so does the rule permit:

```<code>prototype = Mock(MuActor.class);
when(prototype.create()).thenReturn(prototype);
</code>```

Also, the fairy rule pretty much prohibits the use of Monads, because they are based on operation chaining for a particular container type. You could test the Monad type, but you couldn't test code in which the Monad appears.

Body:
I'm going to agree with @Robert Harvey. Just to be clear: Demeter is reasonable and good programming style. It's the "no mocks from mocks" that strikes me as more of a subjective preference supporting a particular coding style rather than a generally applicable (& well justified) practice. The fairy rule takes out "fluent" interfaces like:

Thing.create("zoom").setDomain("bo.com").add(1).flip().reverse().tuneForSemantics().run();

Kind of an extreme example, but essentially the fairy rule would disallow including that class in any code, because the code would become untestable. But that's a popular paradigm in OO code.

Also, the more general problem is how to mock a factory to return a mock you want to test with. I'm generally shy of using Factories as dependencies, but sometimes it's much better than the alternative. If you end up with

ThirdPartyThing ThirdPartyFactory<ThirdPartyThing>#create()

I don't see how you can get around it. You need a mock to return the mock. So that rule kind of knocks out two really powerful OO design patterns.

I can't think of a way to work around your problem without splitting that method into 2 or 3, pushing long lines up to the client, or else creating a weird stateful wrapper class.

I'd be really interested to see what the alternative looks like.

My answer: your code is fine! Excelcior!

(actually I'm curious about alternatives)

...

Let's take an boundary case: are mocks allowed to return themselves? Technically, they are returning a mock. If not, then that knocks the GoF prototype out, and that's one of the patterns that has held up over time:

MuActor prototype = ...
...
MuActor actor = prototype.create();
actor.run();

so does the rule permit:

prototype = Mock(MuActor.class);
when(prototype.create()).thenReturn(prototype);

Also, the fairy rule pretty much prohibits the use of Monads, because they are based on operation chaining for a particular container type. You could test the Monad type, but you couldn't test code in which the Monad appears.


问:
Implement Haskell typeclass with C# interface
I'm trying to compare Haskell's type classes and C#'s interfaces. Suppose there is a Functor.

Haskell:

```<code>class Functor f where
  fmap :: (a -> b) -> f a -> f b
</code>```

How to implement this type class as interface in C#?

What I have tried:

```<code>interface Functor<A, B>
{
    F<B> fmap(Func<A, B> f, F<A> x);
}
</code>```

This is invalid implementation and I'm actually stucked with generic F type that should be returned by fmap. How it should be defined and where?

Is it impossible to implement Functor in C# and why? Or maybe there is another approach?

答:
What you need is two classes, one to model the higher order generic (the functor) and one to model the combined functor with the free value A

```<code>interface F<Functor> {
   IF<Functor, A> pure<A>(A a);
}

interface IF<Functor, A> where Functor : F<Functor> {
   IF<Functor, B> pure<B>(B b);
   IF<Functor, B> map<B>(Func<A, B> f);
}
</code>```

So if we use the Option monad (because all monads are functors)

```<code>class Option : F<Option> {
   IF<Option, A> pure<A>(A a) { return new Some<A>(a) };
}

class OptionF<A> : IF<Option, A> {
   IF<Option, B> pure<B>(B b) {
      return new Some<B>(b);
   }

   IF<Option, B> map<B>(Func<A, B> f) {
       var some = this as Some<A>;
       if (some != null) {
          return new Some<B>(f(some.value));
       } else {
          return new None<B>();
       }
   }
}
</code>```

You can then use static extension methods to convert from IF<Option, B>  to Some when you need to

Body:
What you need is two classes, one to model the higher order generic (the functor) and one to model the combined functor with the free value A

interface F<Functor> {
   IF<Functor, A> pure<A>(A a);
}

interface IF<Functor, A> where Functor : F<Functor> {
   IF<Functor, B> pure<B>(B b);
   IF<Functor, B> map<B>(Func<A, B> f);
}

So if we use the Option monad (because all monads are functors)

class Option : F<Option> {
   IF<Option, A> pure<A>(A a) { return new Some<A>(a) };
}

class OptionF<A> : IF<Option, A> {
   IF<Option, B> pure<B>(B b) {
      return new Some<B>(b);
   }

   IF<Option, B> map<B>(Func<A, B> f) {
       var some = this as Some<A>;
       if (some != null) {
          return new Some<B>(f(some.value));
       } else {
          return new None<B>();
       }
   }
}

You can then use static extension methods to convert from IF<Option, B>  to Some<A> when you need to


答:
I rather think that the syntax of each of those languages you list are not hard to learn at all.  The "hard" part is twofold, in my opinion:

the frameworks that come with them (STL for C++, JRE for Java, .NET Framework for C#) are voluminous and can take a long time to master.

patterns, practices and paradigms.  The three languages you mention are hallmarks of Object-Oriented Programming Languages and we've come a long way since "Cat is a subclass of Animal".  Knowing proper techniques (SOLID, GoF patterns, etc.)

Title: What are the hardest parts of the C++/C#/Java programming languages?

Body:
Just wondered what are the features of the three main programming languages which show you are an 'expert'? Please exclude 'practical' skills such as indenting.

Am I right in saying for C++ the most difficult aspect to master is STL/generics? Java seems much easier as memory is handled for you. I'm not entirely sure on C# either?

I'm trying to use this to guage my current level of ability and what i wish to aim for.

ps this was posted on stackoverflow but got binned due to arguing, please do try to keep it civil as I am really interested in the answers from everyone :)


答:
The major concern here is that mocks can't (or shouldn't) return mocks. This is probably good advice, but talks around a solution: return a real Message. If the Message class is well-tested and passing, you can consider it to be just as friendly as a mock. Perhaps it is even friendlier as it will respond like the real thing because it is the real thing.

What kind of real Messages can you return? Well, you can return a full-fledged real Message, a simplified real Message (wherein well-known defaults are used), or you can return a NullMessage (as in the Null Object Pattern). A NullMessage is just as valid a Message as any other, and can be dropped in anywhere else in your application. Which one to use depends on the complexity of creating and returning a full message.

As to the Law of Demeter, there are multiple concerns here. First, your constructor takes its own builder as a parameter, then extracts elements from it. This is a clear violation of Demeter, and also creates a superfluous dependency. Worse yet, the builder is acting as a mini service locator, masking the real dependencies of the class. The OrderBuilder should create these objects and pass them in as their own parameters.

In order to test this, then, you would pass in a mock MessageFactory, which returns a real Message (either full, simple, or null), and a mock MessageLayer that takes the message. If you use a full or simplified Message, you could get it back from your MessageLayer mock and inspect it for testing assertions.

I would also look at the MessageFactory and MessageLayer as a functionality clump at a different level of abstraction, and so I would extract a MessageSender class that encapsulated that functionality. You could test this class by using a simple mock MessageSender, and shift everything I talked about above into the MessageSender's tests, thereby adhering more closely to Single Responsibility as well.

I see there are really two questions here. There is a specific question of how to test this code, and a general question about mocks returning mocks. The specific question is what I dealt with above to a larger extent, and I have more thoughts at the end of here about it now that some more details have come to light, but there is not really a good answer yet to the general question: Why should mocks not return mocks?

The reason mocks should not return mocks is that you can end up testing your tests rather than testing your code. Instead of just making sure that the unit is fully functional, the test now depends on a whole new piece of code found only in the test case itself (which often is itself not tested). This creates two problems.

First, the test now cannot tell me for sure if the unit is broken or if the interrelated mocks are broken. The whole point of a test is to create an isolated environment where there should be only one cause for failure. A mock on its own is generally very simple and can be inspected directly for problems, but wiring multiple mocks together like this becomes exponentially harder to confirm by inspection.

The second problem is, as APIs change for the real objects, tests may start failing far away since the mocks do not automatically change as well. The Law of Demeter comes into play here, as these are exactly the type of effects following the law avoids. In my tests, I would have to worry about keeping in sync not only the mocks of direct dependencies, but also the mocks of dependencies of dependencies ad infinitum. This has the effect of shotgun surgery on the tests when classes change.

Now, as to the specific question of how to test this particular piece of code, let's break down some assumptions.

Question 1: What are we really testing? While this is an abbreviated portion of the code, we can see three essential activities going on here. First, we have a factory generating a Message. We aren't testing whether the factory is producing the Message, as you're already mocking that out. We're not testing the Message, as it should be tested elsewhere, presumably in a suite of tests for the third-party API that generates the Message. In the second line, we can see from inspection that the method is simply called on the Message and so there is really nothing to test in the second line. Once again, there should be tests elsewhere that make testing this redundant. The third line calls the MessageLayer API, and simply passes through the result. Once again, MessageLayer's API should already be tested elsewhere. This leaves us with essentially nothing to test. There are no direct visible side effects to the external code, and we should not be testing internal implementation. That leads us to the one conclusion that it would be inappropriate to test this code at all. (For more on this line of reasoning, see Sandi Metz's presentation Magic Tricks of Testing, [slides, video])

Question 2: Wait, so then...wha?? Yes, that's right, don't test this at all. Now, as mentioned, this is an abbreviated version of the code. If you have other logic, test that, but encapsulate this into a separate unit (like the MessageSender implementation mentioned above). You can then mock this entire aspect of the code easily, while still having the ability to test other logic.

You are basically using a third-party API directly in your code. Third-party code is notoriously hard to test because it can have these types of dependency issues you have here. Encapsulating it off into a corralled area can make it easier to test your other code, and reduce shotgun surgery if that third-party changes their code (or just changes). While there may still be pain in testing the part that interacts with the third-party API, it is limited to one small facet that you can isolate.

Title: Unit testing, factories, and the Law of Demeter

Body:
Here's how my code works. I have an object that represents the current state of something akin to a shopping cart order, stored in a 3rd party shopping API. In my controller code, I want to be able to call:

```<code>myOrder.updateQuantity(2);
</code>```

In order to actually send the message to the third party, the third party also needs to know several things that are specific to THIS order, like the orderID, and the loginID, which will not change in the lifetime of the application.

So when I create myOrder originally, I inject a MessageFactory, which knows loginID. Then, when updateQuantity is called, the Order passes along orderID. The controlling code is easy to write. Another thread handles the callback and updates Order if its change was successful, or informs Order that its change failed if it was not.

The problem is testing. Because the Order object depends on a MessageFactory, and it needs MessageFactory to return actual Messages (that it calls .setOrderID() on, for example), now I have to set up very complicated MessageFactory mocks. Additionally, I don't want to kill any fairies, as "Every time a Mock returns a Mock a fairy dies."

How can I solve this problem while keeping the controller code just as simple? I read this question: https://stackoverflow.com/questions/791940/law-of-demeter-on-factory-pattern-and-dependency-injection but it didn't help because it didn't talk about the testing problem.

A few solutions I've thought of:

Somehow refactor the code to not require that the factory method return real objects. Perhaps it's less of a factory and more of a MessageSender?

Create a testing-only implementation of MessageFactory, and inject that.

The code is pretty involved, here's my attempt at an sscce:

```<code>public class Order implements UpdateHandler {
    private final MessageFactory factory;
    private final MessageLayer layer;

    private OrderData data;

    // Package private constructor, this should only be called by the OrderBuilder object.
    Order(OrderBuilder builder, OrderData initial) {
        this.factory = builder.getFactory();
        this.layer = builder.getLayer();
        this.data = original;
    }

    // Lots of methods like this
    public String getItemID() {
        return data.getItemID();
    }

    // Returns true if the message was placed in the outgoing network queue successfully. Doesn't block for receipt, though.
    public boolean updateQuantity(int newQuantity) {
        Message newMessage = factory.createOrderModification(messageInfo);

        // *** THIS IS THE KEY LINE ***
        // throws an NPE if factory is a mock.
        newMessage.setQuantity(newQuantity);

        return layer.send(newMessage);
    }

    // from interface UpdateHandler
    // gets called asynchronously
    @Override
    public handleUpdate(OrderUpdate update) {
        messageInfo.handleUpdate(update);
    }
}
</code>```


问:
Do threads delete themselves?
Let's say I was working on a Swing application. Most of it is run on the EDT using SwingUtilities.invokeLater() inside the main method, because I heard (please correct me if I'm wrong) that that's what you need to do with Swing.

However, some parts of it shouldn't run on the EDT. These parts are parts that take long to complete (I assume that this is because long tasks on the EDT will interfere with GUI stuff the EDT should be doing, and thus these kinds of tasks should be run on parallel, on a different thread. Is this assumption correct?)

To do this, when I need to perform a task that takes long to complete and thus can't be run on the EDT like the rest of the program, I create a new thread and run that task inside it.

My question is: When the run() method of that new thread finishes, aka the thread finished it's job. Does it delete itself? Or does it keep existing in the memory?

答:
When the run() method of that new thread finishes, aka the thread finished it's job. Does it delete itself? Or does it keep existing in the memory?

It mostly deletes itself.  The native thread (OS resource) is typically1 destroyed, and the thread stack memory segments (OS resource) are typically deleted.  The thread's thread-locals map, the runnable and some other fields of the Thread object are nulled.

There are some additional (user space) thread descriptors managed by the JVM that are used (among other things) by remote agents.  I'm not sure when they get destroyed, but evidence suggests that they are typically2 destroyed when thread's run() terminates.

The Thread object will continue to exist as long as it is reachable.  So if you want everything to go away when the Thread terminates, don't keep a reference to the Thread or the Runnable.

This is all complicated, and both JVM version and OS specific.  If you really need an accurate answer for the version of Java that you are using, check the source code.

1 - In theory, the JVM could recycle the native threads and thread stack segments.  However it is standard practice for applications to implement thread recycling at a higher level; e.g. using an ExecutorService, ForkJoinPool or third-party thread pool.  For such applications, low level recycling would be redundant and possibly bad for performance.

2 - The evidence is that you don't normally see terminate threads in jstack output.  But the flipside is that if a remote agent is watching a thread, that may delay or prevent the thread descriptor from being removed.

Title: Do threads delete themselves?


问:
Editing Copyright line in Apache2 license.txt
I wish to publish my program under Apache2 license. I have added the    "APPENDIX" part of the license text to the top portion of my source.txt file and edited the copyright year and name.

But when I add the license.txt file in the same archive with sourcecode, should I edit the copyright line wih my name and year? Or should I let the copy of license.txt intact as downloaded from apache site?

答:
Substitute your own copyright name and year - (from Apache license documentation):

To apply the Apache License to your work, attach the following
  boilerplate notice, with the fields enclosed by brackets "[]" replaced
  with your own identifying information. (Don't include the brackets!)
  The text should be enclosed in the appropriate comment syntax for the
  file format. We also recommend that a file or class name and
  description of purpose be included on the same "printed page" as the
  copyright notice for easier identification within third-party
  archives.

```<code>Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</code>```

Body:
Substitute your own copyright name and year - (from Apache license documentation):

To apply the Apache License to your work, attach the following
  boilerplate notice, with the fields enclosed by brackets "[]" replaced
  with your own identifying information. (Don't include the brackets!)
  The text should be enclosed in the appropriate comment syntax for the
  file format. We also recommend that a file or class name and
  description of purpose be included on the same "printed page" as the
  copyright notice for easier identification within third-party
  archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


问:
How deeply programmer should know about internals of database engine?
I am learning SQL Server 2012 along with C#. In the past, I took database class in college, and have good grasp on SQL language and can write queries. However, looking at SQL Server documentation (or Oracle), it appears that DB engine (along with all the technologies that comes with it) are highly complex and are requiring significant time and effort to learn.

Besides writing SQL queries, how deeply should programmer know about internals of database engine ?

答:
Without a sound grasp of database internals, you are bound to misuse it.

Writing SQL which runs, and does its job, but without creating the proper index in the database may work in development, but works very poorly in production, effectively killing your database, and causing bottle-necks.

Identifying a bottle-neck in itself needs a knowledgeable person, since you might (falsely) say - well I've reached the capacity of my DB server, I just need to scale it up... which translates to money loss, and is a very short-term solution.

Performance is not the only problem which may arise - security is a main issue which might not be apparent to the naive developer - O/R mapping and other frameworks made SQL-injection and other database attacks less prevalent, but being unaware of their existence may open up your application to very nasty attacks.

Large-scale DB-oriented projects often have a full-time DBA, whose job is to work with the system architect on the database schema, guiding developers and going over all of their queries, fixing them or adding indexes where needed.

In smaller projects, a team might depend on its own developer's competence for this. This means that you should be able to understand the major guidelines and caveats for using and misusing your database.

If you work in a team, you might want to depend on a team member who is more knowledgeable in the database arena than you, and let him review your SQL queries, and help you design them.

Developers today are expected to be intimately familiar with many technologies, from SQL, noSQL, OS, Web Engines, Mobile, etc. and it is relatively easy to achieve a working prototype in any of these to give a developer the illusion of proficiency, until the same code is faced with production environment, where the true complexity of technology is revealed... you better be prepared!


问:
Epsilon Transitions in an NFA
I'm attempting to teach myself the basics of finite automata and have been exploring the differences between  Deterministic Finite Automata and Non Deterministic Finite Automita.

One thing that pops up quite often in the on-line examples, lectures slides and videos of various CS instructors is the epsilon transition. The problem is none of them do very good job of explaining epsilon transitions. They just kind of pop them out of nowhere as this mysterious property that allows a you to jump from one state to another without reading an input character.

O.K. I get that, but how are these arbitrary jumps facilitated semanticly if we were to create this automata? Take the image below for example. Lets say we are in S0, there are two epsilon transitions to s1 and s4. How is it decided which one to go down. If you go to S1 and do not have an a, can you backtrack and try b? I say this because the arrows do not seem to infer this. Or have I conceived this wrong, could the automata  actually be in both states S1 and S2 concurrently?

Also s3 and s6, have epsilon transitions to s7, so why don't we have two accepting states S3 and s4 instead?

Finally the S2, has two paths that react to a, s5 has two paths that react to b. How does that work in practice. How is the path to follow determined?

When answering please try to limit the use of esoteric mathematics, and if you do use operators and symbols explain each one clearly. I'm not a maths wizz.

答:
Since a few ideas have already emerged in the comments to the question, I try to collect these ideas in an answer.

I think your main source of confusion is that you try to treat a non-deterministic finite automaton as a deterministic one. The epsilon transitions from state s0 indicate that from s0 you can go to {s1, s4}, i.e. to a set that contains both states at the same time. The ambiguity "I can go from s0 to s1 and from s0 to s2, which one should I take?" is resolved by taking both at the same time. To be more precise, the epsilon transition tells you that s0, s1, and s2 are basically the same state: by being in s0 you are already in s1 and in s2 so you can switch to either of them without reading any symbol from the input.

Likewise, you can have an ambiguity if you have two transitions from a state to different states on the same symbol, like for s2 and a in your example. In this case, when in state s2, if you read symbol a you go to {s2, s3}.
What does it mean to be in state {s2, s3}? It means from here you can apply both the s2-transitions and the s3-transitions.

You can always transform a NFA to an equivalent DFA where the states in the DFA correspond to set of states in the original NFA (by applying the powerset construction).

Running an NFA directly would need backtracking while running the corresponding DFA is like running all the different branches of the NFA in parallel (no backtracking is needed): the powerset construction folds all parallel branches together and removes ambiguities.

Title: Epsilon Transitions in an NFA


答:
As deeply as you have time for. There is a lot of fluff these days about being "database agnostic", but unless you like the idea of lowest-common-denominator features defining your best efforts you need to know how your database works. You'll get better results on non-trivial projects if you decide to make your schema and database application agnostic instead of going the other direction.

The last sentence of the previous paragraph flies in the face of just about all Web-2.0 common knowledge. It is worth deciding where your project falls on the "Better is Better" VS "Worse is Better" continuum.

But this does not mean that you should just pick one database to learn about, and what I really mean is that you shouldn't just learn one data paradigm. While fully normalized relational schemas are your best bet for thoroughly understanding your data, they are not workable for many practical applications (but they make an excellent permanent data store from which you can build high-speed warehouses tailored to specific queries later on, if you have the resources). A deliberately denormalized relational schema is usually your backbone, but you often also need a graphing database and -- just as important as your normalized relational schema -- you will probably need to develop a serialization schema (think along the lines of ASN.1 or YAML, not XML, btw -- data, not documents). If you do geographic or spatial data then a GIS-specialized data store can quickly become a must as well. Document databases can also become necessary if you realize one day that what you are doing (or, more realistically, some heavily-loaded aspect of what you are doing) is actually document storage and not record storage.

Having said all that, you will need to understand enough about each to write an intra-db integrity layer (which can be asynchronous, so don't panic) lest they not understand one another. This requires knowing how DBs work.

This sounds like a lot to know, but only because it is. Data is just that important. Sure, you can be like the Web 2.0 guys and kludge your way along... until you hit on a really novel idea and suddenly realize that you can't practically implement your cool idea. Data drives use, not the other way around, and these days its getting shorter and shorter shrift. Don't be the next person who saved a few weeks doing some genuine study of data modeling (in all its forms) only to spend a lifetime of reinventing a data management system that lives only within your one-off project.

It took me a long time to come to this opinion, and my evolution was slow. I didn't need all this knowledge at once; understanding data in a more complete way has come as a side effect of interacting with more interesting aspects of problems that emerged over time as I worked. (In particular, in the process of writing three very large business simulation systems by myself.)

EDIT: It is worth mentioning that the reason I gave special mention to the relational model is that it is possible to simulate any other data model with relational data, but not necessarily possible to simulate every other data model from all of the others. Normalized relational is the most general and therefore the place to start learning how databases and data models work (and these are related ideas with good databases like Postgres, DB2 and Oracle). But pure normalized relational can sometimes be like trying to build a skyscraper with a Swiss Army knife if adhered to religiously. That is why I say you should understand your data in a fully normalized relational way though you may not actually implement it in such a way (or even in a database at all).

In practical terms, if you learn relational data theory thoroughly first you will quickly grok the strengths and compromises inherent in non-relational systems (to include flavor-of-the-week systems) such as CouchDB, AllegroGraph, ObjectDB, etc. and exactly where ORM abstractions fail (IOW, you'll know exactly why 1 class != 1 table && 1 object != 1 row (not even remotely close)) and learn many new things about functional and imperative programming as well.

Title: How deeply programmer should know about internals of database engine?

Body:
I am learning SQL Server 2012 along with C#. In the past, I took database class in college, and have good grasp on SQL language and can write queries. However, looking at SQL Server documentation (or Oracle), it appears that DB engine (along with all the technologies that comes with it) are highly complex and are requiring significant time and effort to learn.

Besides writing SQL queries, how deeply should programmer know about internals of database engine ?


问:
Running a process multiple times at the same time
I have a c++ program with opencv library which takes an image as input and perform pose estimation,color detection,phog. When I run this program from the command line it takes around 4-5sec to complete. It takes around 60%cpu. When I try to run the same program from two different command line windows at the same time the process takes around 10-15 sec to finish and both the process finish in almost the same time. The CPU Usage reaches upto 100%.

I have a website which calls this c++ exe using exec() command. So when two users try to upload an image and run it takes more time as I explained above in the command line. Is this because the c++ program involves high computation and the CPU reaches 100% it slows down? But I read that the CPU reaching 100% is not a bad thing as the computer is using its full capacity to run the program. So is this because of my c++ program or is it something to do with my server(computer) settings? This is probably not the apache server problem because when I try to run it from the command line also it slows down. I am using a quad core processor and all the 4 CPU reaches 100% when I try to run the same process at the same time so I think that its distributed among all the processor. So I have few more questions:

1) Can this be solved by using multithreading in my c++ code?As for now I am not using it but will multithreading make the c++ code more computationally expensive and increase the CPU usage(if this is the problem).

2) What can be the reason of it slowing down? Is the process in a queue and each process is ran only a certain amount of time and it switches between the two process?

3) If this is because it involves high computation will it help if I change some functions to opencv gpu functions?

4) Is there a way I can solve this problems any ideas or tips?

I have inserted the result of top when running one process and running the same process twice at the same time:

Version5 is the process,running it once

Two Version5 running at the same time

Thanks in advance.

答:
I wasn't surprised at the numbers you are reporting after I considered what the program seems to be doing.  It is computationally intensive with a lot of memory data fetches.  The file I/O would be slow in comparison and I don't sense that this is an issue (yet).

Looking at your numbers, I'm thinking you think that 4-5sec x Two should be 8-10 sec.?  I' say realistically the best you could expect would be 9-12 sec., nothing is ideal.  Using my 'mud math' we have 3 sec of CPU more than ~anticipated~.  That's a lot of CPU.

I'd be targeting the memory access contention as my first point of investigation.  Shared core CPU-s will use the same memory bus and access to memory.  They also probably use the same on-chip cache(s) too.  But two processes like this will want to both 'fill' the data cache.  For example, P01 might so some calculations and use 50% of the data cache; then comes P02 who wants 50% of the resources too.  But there won't be 50% available because the operating system needs some and there are other (important) processes like your server, etc.

Anyway the expected outcome is that P02 will evict a significant chunk of P01's resources.  Meaning that P01 will find that it has to go out to the DRAM for some of the data it wants for subsequent calculations.  If I'm at all close, you will get better linear performance by queuing your transformations and running them in sequence.  You could test that in the command shell by putting P01 and P02 in a script:

```<code>P01
P02
</code>```

If the elapsed time comes out under 12 sec. then there is some resource contention involved (not necessarily memory cache). In that case, I recommend using some kind of queue.

At present the (best case) elapsed time for Both clients is: 10sec. (each) because both are slowed down.  If you queue, client one waits 5 sec and client two waits 10 sec. Client 2 is no worse off.  Of course that is not really scalable.  However a transformation queue is scalable if you can enlist one or more back-end machines process jobs from the queue.

Since the transformation is queued the user can do something interesting while the transformation occurs.  That can hold-off a resource contention issue temporarily.

Your other job is to find out what resources is being thrashed.  That may not be easy depending on your machine and low-level tools available.  I'd also be checking on the source code algorithm and optimisations your C++ build uses for the graphics processing.  Some "speed-ups" work fine for single threaded apps by turning off things that you might want to use in multi-threaded situations.

Since your machine is a server, it may not have a graphics CPU.  It might be worth considering some specialised iron to process this stuff.  It usually comes down to how much you want performance and how much you want to expend (time, thinking, money, resources) to get it.

Other things to look at are alternative processing libraries that might be faster or have more suitable configuration options.  Can you re-structure your code to take better advantage of the library's way of doing things?

If you can identify one or more bottle-necks in your transformation code -- This can be done with a C++ profiler -- Then you may be able to run the individual transforms in a staggered fashion so that over all through-put is improved.  That's a big "IF", but worth mentioning.

FIRST though, before committing more than a day more on this; check with your 'business process owner' and find out exactly what the "OK" number of seconds is.  If they say 17-seconds, you are looking good, just queue things up and let the user get-on with something else on the page.

I'll be interested to know if the processes in series is quicker that 2 in parallel.

Good luck

Body:
I wasn't surprised at the numbers you are reporting after I considered what the program seems to be doing.  It is computationally intensive with a lot of memory data fetches.  The file I/O would be slow in comparison and I don't sense that this is an issue (yet).

Looking at your numbers, I'm thinking you think that 4-5sec x Two should be 8-10 sec.?  I' say realistically the best you could expect would be 9-12 sec., nothing is ideal.  Using my 'mud math' we have 3 sec of CPU more than ~anticipated~.  That's a lot of CPU.

I'd be targeting the memory access contention as my first point of investigation.  Shared core CPU-s will use the same memory bus and access to memory.  They also probably use the same on-chip cache(s) too.  But two processes like this will want to both 'fill' the data cache.  For example, P01 might so some calculations and use 50% of the data cache; then comes P02 who wants 50% of the resources too.  But there won't be 50% available because the operating system needs some and there are other (important) processes like your server, etc.

Anyway the expected outcome is that P02 will evict a significant chunk of P01's resources.  Meaning that P01 will find that it has to go out to the DRAM for some of the data it wants for subsequent calculations.  If I'm at all close, you will get better linear performance by queuing your transformations and running them in sequence.  You could test that in the command shell by putting P01 and P02 in a script:

P01
P02

If the elapsed time comes out under 12 sec. then there is some resource contention involved (not necessarily memory cache). In that case, I recommend using some kind of queue.

At present the (best case) elapsed time for Both clients is: 10sec. (each) because both are slowed down.  If you queue, client one waits 5 sec and client two waits 10 sec. Client 2 is no worse off.  Of course that is not really scalable.  However a transformation queue is scalable if you can enlist one or more back-end machines process jobs from the queue.

Since the transformation is queued the user can do something interesting while the transformation occurs.  That can hold-off a resource contention issue temporarily.

Your other job is to find out what resources is being thrashed.  That may not be easy depending on your machine and low-level tools available.  I'd also be checking on the source code algorithm and optimisations your C++ build uses for the graphics processing.  Some "speed-ups" work fine for single threaded apps by turning off things that you might want to use in multi-threaded situations.

Since your machine is a server, it may not have a graphics CPU.  It might be worth considering some specialised iron to process this stuff.  It usually comes down to how much you want performance and how much you want to expend (time, thinking, money, resources) to get it.

Other things to look at are alternative processing libraries that might be faster or have more suitable configuration options.  Can you re-structure your code to take better advantage of the library's way of doing things?

If you can identify one or more bottle-necks in your transformation code -- This can be done with a C++ profiler -- Then you may be able to run the individual transforms in a staggered fashion so that over all through-put is improved.  That's a big "IF", but worth mentioning.

FIRST though, before committing more than a day more on this; check with your 'business process owner' and find out exactly what the "OK" number of seconds is.  If they say 17-seconds, you are looking good, just queue things up and let the user get-on with something else on the page.

I'll be interested to know if the processes in series is quicker that 2 in parallel.

Good luck


问:
Nested CSS styles ~ Where have I seen this concept before?
I can't find this now but I've read it before on various blogs discussing the topic. I'll give an example and hopefully it's clear (albeit it may not clarify anything at all).

Given this piece of markup (arbitrary on purpose):

```<code><div class="myWrapper">

    <img url="someimage.url">

</div>
<div class="yourWrapper">

    <img url="someimage.url">

</div>
</code>```

While the CSS could read like this:

```<code>.myWrapper .img img {border: thin black solid;}
.myWrapper .img {margin:10px;}
.yourWrapper .img img {border: thick red dashed;}
.yourWrapper .img {margin:20px;}
</code>```

It could also be written like this:

```<code>.myWrapper {
  .img {
    margin:10px;
    img {
        border: thin black solid;
    }
  }
}
.yourWrapper {
  .img {
    margin:10px;
    img {
        border: thick red dashed;
    }
  }
}
</code>```

But I can't remember seeing where that was discussed or if it's something in the works. Anybody know what the hell I'm talking about?

And I don't think this is an SO question or I would've put it on SO.

答:
Also, sass and scss support nesting.

Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks...

Body:
I can't find this now but I've read it before on various blogs discussing the topic. I'll give an example and hopefully it's clear (albeit it may not clarify anything at all).

Given this piece of markup (arbitrary on purpose):

```<code><div class="myWrapper">
  <a href="somepage.url" class="img">
    <img url="someimage.url">
  </a>
</div>
<div class="yourWrapper">
  <a href="somepage.url" class="img">
    <img url="someimage.url">
  </a>
</div>
</code>```

While the CSS could read like this:

```<code>.myWrapper .img img {border: thin black solid;}
.myWrapper .img {margin:10px;}
.yourWrapper .img img {border: thick red dashed;}
.yourWrapper .img {margin:20px;}
</code>```

It could also be written like this:

```<code>.myWrapper {
  .img {
    margin:10px;
    img {
        border: thin black solid;
    }
  }
}
.yourWrapper {
  .img {
    margin:10px;
    img {
        border: thick red dashed;
    }
  }
}
</code>```

But I can't remember seeing where that was discussed or if it's something in the works. Anybody know what the hell I'm talking about?

And I don't think this is an SO question or I would've put it on SO.


问:
How should we handle extra cosmetic features in Scrum sprints?
I was reading the Scrum documents and it says that the tasks in Sprint should be "potentially shippable".

I am confused by what this means. Suppose in Sprint 1 the goal was, "user registration form".

How much detail do I need to add for something to be ready to ship? For example:

I can show the simple form with fields without any fancy styling and mark them as done

I can just do client side validation as mark as done but server side is also the option or both

I can also add some jQuery fancy tool tips, hover overs, captcha, colors, labels for the form

Then there is whole lot of styling about how to show error messages on screen

I can do endlessly on one topic. So how do we divide that and when I can think of that as shipping ready.

Or do I need to write each smallest possible thing like showing errors, popup or light box text as subtasks and put them as sprint. This would lead to 1000s of tasks for whole project.

I mean then again if some work for Internet Explorer and some for Firefox then again do I need to divide those as tasks as well. Time has to be spent on them and when manager asks me what you did in that time, I won't have any tasks to tell but in reality they all are part of User registration

答:
It's dependent upon the person setting the requirements, the "product owner." As a programmer, I might be content with an unstyled "registration form" page which simply proves that the business logic in my web services works correctly, and that registering allows you to be authenticated against other resources in the system.  In fact, "potentially shippable," since it doesn't necessarily imply that we're literally going to ship it to a client, could allow this to be the outcome of the first user story on the topic, particularly if the technical team and design team are separate resources with separate backlogs.

On a more mature project, you might ship a "developer-designed" version of the feature, with minimal styling, to a pilot or beta client, but revisit the same feature for both functionality modifications (based upon feedback) and design completion.

The purpose of Agile methodology is to allow your requirements to drive the software development process, rather than the opposite.  Don't fall into the trap of assuming that one description of the methodology is the True and Only Orthodox Requirement.  Easier said than done, of course, particularly if you're in a large organization where Scrum has become an excuse for imposing chaos on the development team.


问:
Should a large company standardize engineering tools across all teams internationally?
I've been thinking a lot about the problem of standardization across large companies.  For me, the answer is pretty clear: do not arbitrarily standardize on tools just because that's what everyone else does.  It's counter-productive.

I'm thinking about source control, bug tracking and testing tools primarily.  It seems so obvious to me that I can't really think of many good counter-arguments.  Some I've thought of :

Easier sharing between teams

Easier for IT to manage

(1) is definitely true if different teams are working on the same codebase/product.  But in cases where one team doesn't work directly with the code I don't think is a valid reason.

(2) is just kind of pisses me off if that's really an argument.  The limitations placed on programmers, I believe, is more burdensome than any extra work piled on to IT.  But I'm not an IT guy.

I'm hoping for some better arguments than those.

答:
There is a lot of effort wasted on tool wars. In a really large company, no one can ever "win" and I do not see any benefit in really trying.

"Make it easier to swap resources" - I have never seen this happen once in my company. People make this argument but the actual realized benefits are very, very small. Usually resources aren't "swapped" anyway, and if they are then it doesn't take long to learn most of these systems.

"Easier for IT" I can't see this argument anymore, since we have a relatively small SDLC tools team that supports pretty much every major vendor product there is for tens of thousands of users (across all tools).

Many individual teams are more productive than they were a few years ago when there were fewer tool chains and many of them were optimized for different platforms than what any given particular team was actually using; or the infrastructure had to be local (cough ClearCase cough) and most of the company couldn't even use them.


问:
Difference between Optimization and Scalability?
If I quote a paragraph from Wikipedia about Optimization:

In computer science, program optimization or software optimization is
  the process of modifying a software system to make some aspect of it
  work more efficiently or use fewer resources. In general, a computer
  program may be optimized so that it executes more rapidly, or is
  capable of operating with less memory storage or other resources, or
  draw less power.

And about Scalabilty:

Application scalability refers to the improved performance of running
  applications on a scaled-up version of the system.

What's the difference? They both end up improving the performance of the system. Are they the same, if so, why are their names different?

答:
They are different.

Scalability, generally, refers to when the expected throughput is several orders of magnitude larger.

For example, if I write the a website which keeps track of my finances, and I want to optimize it for speed, I might decide to keep ALL the data in memory. This means my website can respond more quickly - it does not have to get the data off disk (let's forget, for the moment, what happens when my server is rebooted).

For one user, this might be highly optimized. However, it lacks scalability; when my website reaches 1,000,000 users, keeping all that data in memory is no longer an option.

Most scalability issues come up when a system is divided over several servers.

Things behave differently in large volumes: databases may no longer fit onto a single server; do you shard your database, or do you replicate it? If you split your website over several servers, do you use several identical servers, do you separate static data from dynamic data, do you keep specific large assets on a content distribution network (CDN)? How will that effect your website? Do you use load balancing switches, or load balancing DNS?

What happens if a server goes down? If you have one server, no matter how optimized it is, it means an outage; this is fine for 1 or 5 or 10 users, but for Google? Google, at any given time, WILL have servers down. It is no longer a matter of "a drive has failed, page a sysadmin to fix it", but "add it to the list; the failed drive replacement engineer will trundle his cart around in a few minutes". It might not be worth for Google to use RAID, since they have an "redundant array of inexpensive servers".


答:
Optimization is the process of making existing something more efficient, while doing the same operations. This can mean take less processing time for the same operation. It could mean taking less memory. It could mean taking less disk space. Optimization sometimes involves making trade-offs, like using more memory in exchange for faster processing.

Making things scalable means doing more of the same things. Further, it means doing more of the same things in an efficient manner. Searching for some item in your pocket is quick and easy. Searching for that same item in your house is harder. Searching for that same item when it could be anywhere in the world is super hard. Scalability is how drastically that sort of thing gets harder. "More" or better scalability means that searching all over the world is relatively only a little harder than searching in your pocket.

Like optimization, scalability can have a variety of targets. Sometimes the scalability target is processing time, like the search example. Sometimes it is database size. Sometimes it is memory consumption. Sometimes it's as simple as being able to show more stuff on the screen without driving your users nuts.

So in short, optimization is the act of making a single operation more efficient. Making things scalable is making that operation capable of doing more in a more efficient way.

Or if you could think of how an operation behaves for a series of inputs as a curve: optimization is lowering one point of the curve; making something scalable is lowering the slope of the curve.

Title: Difference between Optimization and Scalability?

Body:
If I quote a paragraph from Wikipedia about Optimization:

In computer science, program optimization or software optimization is
  the process of modifying a software system to make some aspect of it
  work more efficiently or use fewer resources. In general, a computer
  program may be optimized so that it executes more rapidly, or is
  capable of operating with less memory storage or other resources, or
  draw less power.

And about Scalabilty:

Application scalability refers to the improved performance of running
  applications on a scaled-up version of the system.

What's the difference? They both end up improving the performance of the system. Are they the same, if so, why are their names different?


问:
Should Libraries Use Events or a Set Action
I'm building a small reusable library for two systems our company manages.

Something that I've been caught up on is whether I should expose a set of properties of type Action<T> for events such as Completed, Aborted, ExceptionOccured, or if I should use the Event<T> T : EventArgs methodology.

In practice another internal library will be consuming this information and handling the display of information to the user. The library's classes will be instantiated within a single thread and wouldn't be consumed by anything outside of its owner.

To me it seems more along the lines of if I only need to notifications are only ever going to be consumed by one object then it doesn't matter, however for completeness, and due to the fact that I as the library auther have little control over how another developer implements this, I should use the Event method due to it's broader ability to handle events.

EDIT (sample code):

@Robert Harvey, I read that post when searching for reasoning on picking one over the other. I understand the answer in context to that question, but I'm not sure how it relates to using the event keyword or the simple assigning of a property.

@Fabio Marcolini, I understand that I'm using the word event to describe what is happening. What I'm trying to answer is that if using the event structure is preferred to simply executing a delegate property.

Here are the properties that I use to define the event actions:

```<code>public Action<WorkflowInstallerCompletedEventArgs> InstallCompleted;

public Action<System.Activities.Activity, WorkflowInstallerActivityCompletedEventArgs> ActivityCompleted;

public Action<System.Activities.Activity, WorkflowApplicationAbortedEventArgs> InstallAborted;

public Func<System.Activities.Activity, WorkflowApplicationUnhandledExceptionEventArgs, UnhandledExceptionAction> UnhandledExceptionDuringInstall;
</code>```

The idea would be to invoke one of them in this manner:

```<code>  if (this.InstallCompleted != null)
    this.InstallCompleted(new WorkflowInstallerCompletedEventArgs(logs));
</code>```

Now until @svick's comment I would've said that you could only have one Action (or Func) assigned to each property.

Example implementation:

```<code>  WorkflowInstaller installer = new WorkflowInstaller(activity, new TestVariablesCollection()) { ActivitiesRunSequentially = true };
  installer.AddInstallActivity(activity2);

  installer.InstallCompleted = (e) =>
  {
    Log[] logs = e.Logs.ToArray();
    string test = SerializationHelper<Log>.Serialize(logs.FirstOrDefault());
    try
    {
      logOutputFromRun = SerializationHelper<Log[]>.Serialize(logs);
    }
    catch (Exception ex)
    {

    }
    syncEvent.Set();
  };
  installer.InstallAborted = (a, e) =>
  {
    Assert.Fail("Unexpected abort during the install.");
    syncEvent.Set();
  };
  installer.UnhandledExceptionDuringInstall = (a, e) =>
  {
    Assert.Fail("Unexpected exception during the install.");
    syncEvent.Set();
    return System.Activities.UnhandledExceptionAction.Terminate;
  };

  installer.StartInstallation();

  syncEvent.WaitOne();
</code>```

The answer to my question may not be a definitive this way or that way, but more of best practice or generally accepted approach. I'm really trying to expand my horizons when it comes to creating code that is acceptable to a wider audience.

答:
If it's truly meant to be a library, then you should be using Events.  For the reasons Fabio mentioned (nomenclature and looking at existing .NET libraries), as well as the practice that consumers should not have to know or care about each other.

What do I mean by this last statement?  Well, consider the following case, where you are using a shared instance of WorkflowInstaller installer:

Class 1 wants to implement your event/action as an Action:

```<code>installer.InstallCompleted = (e) => { /* do something */ );
</code>```

Now, Class 2 also wants to implement your event/action as an Action:

```<code>installer.InstallCompleted = (e) => { /* do something else */ );
</code>```

Well, now Class 2 has just overwritten the handler of Class 1.  The action from Class 1 will never get called, causing unexpected behavior.

Implemented as an event, however, this would instead be:

Class 1 implements the event:

```<code>installer.InstallCompleted += (e) => { /* do something */ };
</code>```

Class 2 implements the event:

```<code>installer.InstallCompleted += (e) => { /* do something else */ };
</code>```

Now, of course, we can get around the overwrite in the Action case by checking if any implementation is already in place:

Class 2 implements the action:

```<code>if (installer.InstallCompleted == null)
{
    installer.InstallCompleted = (e) => { /* do something else */ };
}
else
{
    var existingAction = installer.InstallCompleted;
    installer.InstallCompleted = (e) => { existingAction(e); /* do something else */ };
}
</code>```

So you see, we can get around it, but we are forcing consumers to be aware of any other consumers.  We are making a larger coding effort on anyone down the line.  This is kind of counter to the reason for making a library in the first place.

On a final note, with all the above being said, it doesn't particularly matter as much in your case, as you've said that both the library and consumers will be internal to your workspace.  However, as you've already said, in the interest of completeness, I would recommend events.

Body:
If it's truly meant to be a library, then you should be using Events.  For the reasons Fabio mentioned (nomenclature and looking at existing .NET libraries), as well as the practice that consumers should not have to know or care about each other.

What do I mean by this last statement?  Well, consider the following case, where you are using a shared instance of WorkflowInstaller installer:

Class 1 wants to implement your event/action as an Action:

installer.InstallCompleted = (e) => { /* do something */ );

Now, Class 2 also wants to implement your event/action as an Action:

installer.InstallCompleted = (e) => { /* do something else */ );

Well, now Class 2 has just overwritten the handler of Class 1.  The action from Class 1 will never get called, causing unexpected behavior.

Implemented as an event, however, this would instead be:

Class 1 implements the event:

installer.InstallCompleted += (e) => { /* do something */ };

Class 2 implements the event:

installer.InstallCompleted += (e) => { /* do something else */ };

Now, of course, we can get around the overwrite in the Action case by checking if any implementation is already in place:

Class 2 implements the action:

if (installer.InstallCompleted == null)
{
    installer.InstallCompleted = (e) => { /* do something else */ };
}
else
{
    var existingAction = installer.InstallCompleted;
    installer.InstallCompleted = (e) => { existingAction(e); /* do something else */ };
}

So you see, we can get around it, but we are forcing consumers to be aware of any other consumers.  We are making a larger coding effort on anyone down the line.  This is kind of counter to the reason for making a library in the first place.

On a final note, with all the above being said, it doesn't particularly matter as much in your case, as you've said that both the library and consumers will be internal to your workspace.  However, as you've already said, in the interest of completeness, I would recommend events.


答:
Optimization is an Internal factor, where Scalability is an External factor.

Think about it like if you learn a new skill about doing a certain thing that makes you X times faster than before, then you've optimized yourself in doing that specific action; However if you ask your friend to join and help you about that thing instead -- in order to speed up the process, then that's scaling-up.

So basically optimization increases the efficiency of the process to finish more tasks while using the exact same resources as were available before, but scalability simply increases the resources in order to get more things done.


问:
Why does the boolean type in C++ support ++ but not --?
Why does the operator -- not exist for bool whereas it does for operator ++?

I tried in C++, and I do not know if my question apply to another language. I will be glad to know also.

I know, I can use the operator ++ with a bool. It makes any bool equal to true.

```<code>bool b = false;
b++;
// Now b == true.
</code>```

Why can't we use the operator -- in an opposite way?

```<code>bool b = true;
b--;
// Now b == false;
</code>```

It is not very useful, but I am curious.

答:
To understand the historical significance of this question, you must consider the case of the Therac-25. The Therac-25 was a medical device that delivered radiation to cancer patients. It was plagued with bad programming practices that contributed to its poor safety track record (with multiple deaths attributed to it).

http://courses.cs.vt.edu/professionalism/Therac_25/Therac_1.html

(go to the bottom of page 3)

Every pass through the Set-Up Test routine increments the upper
  collimator position check, a shared variable called Class3. If Class3
  is nonzero, there is an inconsistency and treatment should not
  proceed. A zero value for Class3 indicates that the relevant
  parameters are consistent with treatment, and the beam is not
  inhibited.

...

During machine setup, Set-Up Test will be executed several hundred times since it reschedules itself waiting for other events to
  occur. In the code, the Class3 variable is incremented by one in each
  pass through Set-Up Test. Since the Class3 variable is 1 byte, it can
  only contain a maximum value of 255 decimal. Thus, on every 256th pass
  through the Set-Up Test code, the variable overflows and has a zero
  value. That means that on every 256th pass through Set-Up Test, the
  upper collimator will not be checked and an upper collimator fault
  will not be detected.
       The overexposure occurred when the operator hit the "set" button at the precise moment that Class3 rolled over to zero. Thus Chkcol was
  not executed, and F$mal was not set to indicate the upper collimator
  was still in field-light position. The software turned on the full 25
  MeV without the target in place and without scanning. A highly
  concentrated electron beam resulted, which was scattered and deflected
  by the stainless steel mirror that was in the path.

The Therac-25 used something like the equivalent of operator++ on a bool. However, the programming language they used was not C++, and their data type was not bool. Unlike the guarantee in C++, however, a regular integer type simply keeps going up. Their data type was the equivalent of uint8_t.

C++ decided to keep the operator++ around for people used to programming like this, but instead of incrementing the value, it simply sets it to true to prevent things like this.

Note that operator++(bool) is deprecated.

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf

Annex D of C++14:

D.1 Increment operator with bool operand

  The use of an operand of type bool with the ++ operator is deprecated (see 5.3.2 and 5.2.6).


问:
UX designers working one Sprint ahead
Our UX designers usually have a story in Sprint X that the developers will implement in Sprint X+1 (The UX designers and the devs/testers are on one team). I think this makes sense because if you don't have screen mockups and clear specifications you can't really estimate the work during Sprint Planning.

However in Scrum you are only supposed to have user stories that provide value to the user. In our case the UX design stories don't provide such value (they are more like a backlog grooming activity). Also usually Scrum coaches don't recommend having complete specifications before the start of the Sprint, a recommendation which I find hard to understand.

So do you see any disadvantages in our approach? It seems to work for us, but it goes somewhat against Scrum principles.

答:
I like it, for two reasons:

it seems to work for you; it's hard to argue with success!

the UX team takes the story and starts the conversation early - and
conversations are kind of the point of stories

Title: UX designers working one Sprint ahead


问:
How to completely avoid business logic in DAL?
In our ASP.NET MVC application, we try really hard to separate concerns to each layer (we use DDD). Nevertheless, it seems that we can't avoid having at least some business logic in DAL.

For instance, there are named objects, where business requirement is that each name must be unique (but the name isn't a key). If there is a request to create new named object, the service checks whether some object with that name exists in repository, if it doesn't, factory creates new object and repository persists it (we use EF for repositories and stored procedures for query objects).

The problem is with race conditions - if two requests come concurrently (it's unlikely, but possible), both requests want to create new object under the same name, in this case both checks come out negative and two objects with the same name would be created. So far, we handle that with constrains in SQL database, so if something like this happens, an exception is thrown in repository - but this approach is simply wrong, since such requirement is strictly business requirement and it shouldn't bubble to persistence layer; if we change such requirement, e.g. that names become case sensitive, such constrain would also have to be changed, etc.).

How to implement such scenario correctly? Thanks.

答:
I would do it like this:

```<code>public class NamedObjectRepostiory
{
    private IDataStore _dataStore; // this is just a wrapper around Entity Framework to make it more testable

    public NamedObjectRepostiory(IDataStore dataStore)
    {
        _dataStore = dataStore;
    }

    public void Save(NamedObject namedObject)
    {
        // This is basically a transaction scope/DbContext instance.  You can inject the IDataSession
        // rather than the IDataStore if you want scope to be managed by your DI
        // container, e.g. session per HTTP request, which is a common pattern
        using (var session = _dataStore.GetSession()) {
            if (session.Set<NamedObject>().Any(x => x.Name == namedObject.Name))
                throw new Exception("Cannot have 2 NamedObjects with the same name.");

            // save data...
        }
    }
}
</code>```

No unique constraint needed (assuming that all writes go through the application, which they pretty much have to if you're doing DDD).

OwnerDisplayName: Robert Goldwein

Body:
I would do it like this:

public class NamedObjectRepostiory
{
    private IDataStore _dataStore; // this is just a wrapper around Entity Framework to make it more testable

    public NamedObjectRepostiory(IDataStore dataStore)
    {
        _dataStore = dataStore;
    }

    public void Save(NamedObject namedObject)
    {
        // This is basically a transaction scope/DbContext instance.  You can inject the IDataSession
        // rather than the IDataStore if you want scope to be managed by your DI
        // container, e.g. session per HTTP request, which is a common pattern
        using (var session = _dataStore.GetSession()) {
            if (session.Set<NamedObject>().Any(x => x.Name == namedObject.Name))
                throw new Exception("Cannot have 2 NamedObjects with the same name.");

            // save data...
        }
    }
}

No unique constraint needed (assuming that all writes go through the application, which they pretty much have to if you're doing DDD).


答:
Within a department I can see this making sense.  There should be a central store rather than a bunch of different systems to look up bugs or code.  Does it help to have to look in a handful of different bug tracking systems to find issues?  I don't think so, but I don't think all the departments uniformly should be forced onto the same system as that may not make sense.

At the same time, I'd argue that departments are a reasonable threshold for how far a set of tools should go.  For example, I have worked where IT had one bug tracking system and Product Development had something else.  Same for source control and languages.

Title: Should a large company standardize engineering tools across all teams internationally?

Body:
I've been thinking a lot about the problem of standardization across large companies.  For me, the answer is pretty clear: do not arbitrarily standardize on tools just because that's what everyone else does.  It's counter-productive.

I'm thinking about source control, bug tracking and testing tools primarily.  It seems so obvious to me that I can't really think of many good counter-arguments.  Some I've thought of :

Easier sharing between teams

Easier for IT to manage

(1) is definitely true if different teams are working on the same codebase/product.  But in cases where one team doesn't work directly with the code I don't think is a valid reason.

(2) is just kind of pisses me off if that's really an argument.  The limitations placed on programmers, I believe, is more burdensome than any extra work piled on to IT.  But I'm not an IT guy.

I'm hoping for some better arguments than those.


问:
Does heavy JavaScript use adversely impact Googleability?
I've been developing the client-side for my web-app in JavaScript.

The JavaScript can communicate with my server over REST (HTTP)[JSON, XML, CSV] or RPC (XML, JSON).

I'm writing writing this decoupled client in order to use the same code for both my main website and my PhoneGap mobile apps.

However recently I've been worrying that writing the website with almost no static content would prevent search-engines (like Google) from indexing my web-page.

I was taught about this restriction about 4 years ago, which is why I'm asking here, to see if this restriction is still in-place.

Does heavy JavaScript use adversely impact Googleability?

答: The best idea is building your website and the checking Google cache. See what google shows on it's text only cache. This is the most simpliest answer as well as most useful answer you should care about if you understand.</p>


问:
Best books on the theory and practice of software architecture?
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.

答:
If you are using .net check out these two...(there are web app versions also)

Microsoft .NET: Architecting Applications for the Enterprise (Microsoft)

Professional Enterprise .NET (Wrox Press)