问:
Approaches to get stats like average latency in last N seconds
I am receiving messages with latency information (LI, {date, latency}).

For statistical reasons: (I am open to approx. approaches, stats monitor will be updated in 6-60 seconds)

I want to monitor (A=Average) average latency in last 60 seconds for incoming messages

I want to monitor (R=Rate) count of messages exceeding threshold (T) / count of messages in last 60 seconds for incoming messages

And also I should generate an alert if messages exceeding the threshold T within an interval 0<I<2048 seconds (last I seconds) have a count greater than C.

I=0 means from the beginning (not a sliding window)

If an alert is created then I will reset the counters and interval.

What data structures and algorithms do you recommend for above problem? (My message receiving rate is 400 messages per second)

答:
In the case I=0 (from beginning), the fastest way to compute the average values is this way. You should quantize your data in intervalls to discrete values like

0ms-1ms = 1

1ms-2ms = 2

...

40ms-50ms = k

50ms-70ms = k+1

...

>5000ms = n (also for never responded)

The more unlikely the measured latency value is in real world, the wider should be the intervall. Inserting a latency value into this map is like this:

discreteLatencyCount[indexForDiscreteLatency(measuredLatency)]++;

Average latency is then calculated by:

avg=0.0

for(i=1 to n) { avg+=weightOfDiscreteLatencyFor[i]*discreteLatencyCount[i]; }

weightOfDiscreteLatencyFor[] is for simple solutions the mid of the intervall or depends on your statistic distribution - Try to record a fairly large dataset and tune the values to minimize the real difference for this dataset.

Count messages is then calculated by:
 * count=0;
 * for(i=1 to n) { count+=discreteLatencyCount[i]; }

working with fixed sliding windows works like this too, but you will have to subtract the outgoing events (which are leaving the sliding window) from your counters. This implementation is a good solution, if you need a fast (or constant time) computation of avg and count.

But it is depending on your case whether this solution is good enough for you. Instead you could also use ready solutions like a round robin database instead. Please also consider locking issues in multithread environments.

I came to this solution after a colleage in the telco industry teased me with this question a few years ago and then he told me they implemented it this way too, after presenting this solution.


问:
How do you usually compile C/C++ source code ? (Large code bases)
It's been quite some times since I began learning C and C++ but I've been very limited only to the Windows platform and the Visual Studio environment. Recently, I wanted to look into some open source C/C++ projects, so I downloaded a few but I was frustrated because I didn't know how to compile those software. Then I had to learn about all those g++ and make stuff and still I only have very limited knowledge in those subjects.

Having been used to an environment like Visual Studio, where you can write the code, hit the play button and boom you're all good to go, it was hard for me to compile a program with the command line at first.

So my question is, if you're a C/C++ developer, how do you compile your code ? How do you compile relatively large code bases ? What are the tools that you use ? Do you use IDEs or simply text editors ? What is the compiler that you use ? Do you build your applications from the command line ? What is the OS that you usually compile on ?

SideNote: My linux knowledge is zero.

答:
At least for free software on Linux, you usually use some builder like make. You could use some other builder program, like scons or omake

For some (mostly historical) reasons, the Makefile may be generated by utilities like autoconf or cmake; these generators also deal with configuration issues (e.g. they disable some features of the software if a dependency is missing). Some frameworks also provide their own Makefile generators, e.g. qmake for Qt

PS. Recent GNU make 4  has a lot of new features (plugins and guile scriptability) which are worthwhile (and probably could IMHO remove the necessity of generating Makefile-s).

When building large C++ code base, I recommend using command line utilities (notably make), because you understand more what is really happening. Also, a lot of large C++ code bases are sometimes using specialized C++ code generators (e.g. the GCC compiler has a dozen of them, internal to it). There are good reasons to sometimes generate some C++ code (perhaps with a simple awk or python script), e.g. some headers or constants, etc.

To build many GNU -or other- large free software bases -at least on Linux-, you generally don't need to understand all the details of their building. Usually, a README or an INSTALL text file explains how to do that, and it is often -for software using autoconf-  (but not always) as simple as running the three commands

```<code> ./configure
 make
 sudo make install
</code>```

You might prefer to run make install DESTDIR=/tmp/installdir/ then copy the /tmp/installdir with e.g. sudo cp -va /tmp/installdir/ /

For software using cmake, building them is often as simple as

```<code>mkdir build
cd build
cmake ..
make
sudo make install
</code>```

The pkg-config is also a useful utility, since it gives the compilation and linking flags useful with some packages.

Large software may be difficult to build because of the dependency hell (which is an issue for every large software, on any operating system). Linux distributions are done to manage with it.

I guess that these free software are often easier to build on Linux than on Windows (which I don't know and never use). BTW, I strongly recommend you to install Linux and learn it, because it is fun and made of free software (whose source code you can study, improve, and contribute to).

Very large or foundational free software like the GCC compiler, the GNU glibc, the Linux kernel are tricky to build (because nearly everything depend upon them). So start building some easier free software from source code. See sourceforge or github to find some.

Some languages or frameworks have their own installer or package manager or builder. For example, ocaml has opam

BTW, notice that all IDE (including Visual Studio on Windows) are just editors with some graphical interface to run the C++ compiler on the command line. So it is better to understand what is really happening, by knowing how to run the compiler thru commands.

ContentLicense: CC BY-SA 3.0

Body:
At least for free software on Linux, you usually use some builder like make. You could use some other builder program, like scons or omake

For some (mostly historical) reasons, the Makefile may be generated by utilities like autoconf or cmake; these generators also deal with configuration issues (e.g. they disable some features of the software if a dependency is missing). Some frameworks also provide their own Makefile generators, e.g. qmake for Qt

PS. Recent GNU make 4  has a lot of new features (plugins and guile scriptability) which are worthwhile (and probably could IMHO remove the necessity of generating Makefile-s).

When building large C++ code base, I recommend using command line utilities (notably make), because you understand more what is really happening. Also, a lot of large C++ code bases are sometimes using specialized C++ code generators (e.g. the GCC compiler has a dozen of them, internal to it). There are good reasons to sometimes generate some C++ code (perhaps with a simple awk or python script), e.g. some headers or constants, etc.

To build many GNU -or other- large free software bases -at least on Linux-, you generally don't need to understand all the details of their building. Usually, a README or an INSTALL text file explains how to do that, and it is often -for software using autoconf-  (but not always) as simple as running the three commands

 ./configure
 make
 sudo make install

You might prefer to run make install DESTDIR=/tmp/installdir/ then copy the /tmp/installdir with e.g. sudo cp -va /tmp/installdir/ /

For software using cmake, building them is often as simple as

mkdir build
cd build
cmake ..
make
sudo make install

The pkg-config is also a useful utility, since it gives the compilation and linking flags useful with some packages.

Large software may be difficult to build because of the dependency hell (which is an issue for every large software, on any operating system). Linux distributions are done to manage with it.

I guess that these free software are often easier to build on Linux than on Windows (which I don't know and never use). BTW, I strongly recommend you to install Linux and learn it, because it is fun and made of free software (whose source code you can study, improve, and contribute to).

Very large or foundational free software like the GCC compiler, the GNU glibc, the Linux kernel are tricky to build (because nearly everything depend upon them). So start building some easier free software from source code. See sourceforge or github to find some.

Some languages or frameworks have their own installer or package manager or builder. For example, ocaml has opam

BTW, notice that all IDE (including Visual Studio on Windows) are just editors with some graphical interface to run the C++ compiler on the command line. So it is better to understand what is really happening, by knowing how to run the compiler thru commands.


问:
Writing code with language features yet to come in mind
In C#6, we will (most likely) have the nameof operator, a very useful operator for the ArgumentNullException pattern:

```<code>public void M(T x) {
    if (x == null) {
        throw new ArgumentNullException("x"); // change "x" to nameof(x)
    }
}
</code>```

However, C#6 is not yet released, and code using nameof won't be compiled by the stable versions of the compiler.

The nameof is only an example, where the difference in readability is very tiny. This question is not only about this case, but the general case.

Is it worth (or at which point of improvement is it worth) signaling on the code that piece of code could be changed to be better (more readable/better performance/any other metric) in a future version of the language/compiler? What kind of signal is better at this job (just a comment, a TODO comment, an issue in the project management, etc)?

答:
Beware of uncertainty. A given feature may be released or not: it may be postponed, or simply dropped. Also, migrating to the new version of a language and framework is not an easy task. For instance, in Microsoft's community, this sometimes requires a new version of Visual Studio, which may have a very substantial cost for a company.

If you still want to signal a possible improvement, think about what you'll do when the new version of the language is released. Would you:

Walk through the whole code base and modify the thing everywhere you can?

Or do nothing and wait until you maintain a specific piece of code to use the new language feature?

In the first case, a TODO comment or a ticket looks appropriate, but you may also consider doing nothing, since you'll be browsing the whole code base anyway.

In the second case, put a simple comment for the maintainers.


问:
Do algorithms depend on computer architectures?
I read somewhere (forgot which book it is) that algorithms are independent of computer architectures. Some even say algorithms are themselves computation (machines?)?

On the other hand, books on parallel programming have chapters on parallel algorithms. It seems like parallel algorithms depend on parallel architectures?

I think I miss some big pictures? Thanks.

答:
In general, algorithms are designed to some particular problems at while minimizing some measure of "cost".  Historically, many algorithms were designed on the assumption that the relative costs of common operations would be relatively similar on many architectures, and thus some typical machines would run one algorithm would run better than another, then on most typical machines the former algorithm would, at worst, be only slightly inferior to the latter.  As time has gone by, such an assumption doesn't hold as well as it used to.

For example, it used to be that the number of times a program needed to read things from memory was considered more important than the locations of things to be read.  Reading things that were located near each other in memory was somewhat cheaper than reading things that were far apart, but not outrageously show.  As main-CPU speeds have increased at a rate far in excess of memory speeds, however, the importance of access sequence has significantly increased.  It's possible to have one program execute ten times as many instructions as another and yet still run faster, if the 95% of the former program's memory fetches generate L1 cache hits and a majority of the latter program's memory fetches generate cache misses.

Additionally, certain kinds of concurrency-related algorithms make various assumptions about when data written to memory by one processor core will be "seen" by other cores.  Many processors have various ways that they can read and write memory, with varying costs and guarantees about visibility.  Some algorithms will work very well on architectures that can satisfy visibility requirements "for free", but poorly on others where the instructions necessary for those guarantees are expensive.  Indeed, on some architectures certain concurrency-related algorithms could only be guaranteed to work by limiting execution to a single time-shared CPU core (which would of course defeat the point of using a concurrent algorithm).


答:
A lot of answers are missing the fact that an algorithm can be defined in terms that are either abstract from or in direct, literal relation to an architecture.  An algorithm has to be unambiguous, but there's still room for it to be more or less specific.

An algorithm for converting a string to all-caps can be easily described in pseudocode that is architecture-independent.  But at the same time, nothing is stopping you from describing an algorithm for converting a string to all-caps specifically on an x86 architecture.  All it takes is a x86 Assembly homework assignment.  (You can still do this in pseudocode - just pseudocode relating to that architecture!)  Just the fact that the problem is specifically for doing this on an x86 architecture doesn't mean you no longer have an algorithm to solve it.

It depends on the problem the algorithm is defined to solve.  The algorithm is architecture-independent if the problem it solves is architecture-independent (and assuming that this isn't undone by the way the algorithm is described or put together).  The problem can be either a theoretical, blackboard one, or it can be in terms of a very specific architecture.  In the latter case, the algorithm, in turn, would be limited to working with that architecture.

Title: Do algorithms depend on computer architectures?

Body:
I read somewhere (forgot which book it is) that algorithms are independent of computer architectures. Some even say algorithms are themselves computation (machines?)?

On the other hand, books on parallel programming have chapters on parallel algorithms. It seems like parallel algorithms depend on parallel architectures?

I think I miss some big pictures? Thanks.


答:
Since you say that approximations will work for you, what I would do is that I would pick a time interval like 1 second and I would treat it as a quantum.  I would record all information of interest from every event happening during the quantum, and at the end of the quantum I would summarize everything that happened and discard the details in preparation for recording information about the next quantum.

The summaries generated for each quantum would be stored in a queue for running average calculations. A time quantum of one second and a historicity requirement of 2048 seconds would mean that your queue would only need to be up to 2048 entries long.

You appear to be willing to afford ten times the computing resources that are necessary to tackle the problem, so you can certainly compute averages from scratch if you wish, (advice: do it for testing anyway,) but if you care for a highly efficient algorithm for sliding window average calculations, it is as follows:

Let there be a queue Q of length N which can grow up to M.  For the first M insertions, N grows from zero until it reaches M; after that, each insertion causes an item to be tossed from the other end, so that N never exceeds M.

Let there be a running total T initialized to 0.

Each time item I is inserted (possibly causing item X to be tossed) :

Add the value of I to T.

If N == M (meaning, X is being tossed) then Subtract the value of X from T.

The new average is T/N.

So, the running average can be computed without revisiting all values in the queue, that is, in O(1) instead of O(N).

Title: Approaches to get stats like average latency in last N seconds

Body:
I am receiving messages with latency information (LI, {date, latency}).

For statistical reasons: (I am open to approx. approaches, stats monitor will be updated in 6-60 seconds)

I want to monitor (A=Average) average latency in last 60 seconds for incoming messages

I want to monitor (R=Rate) count of messages exceeding threshold (T) / count of messages in last 60 seconds for incoming messages

And also I should generate an alert if messages exceeding the threshold T within an interval 0<I<2048 seconds (last I seconds) have a count greater than C.

I=0 means from the beginning (not a sliding window)

If an alert is created then I will reset the counters and interval.

What data structures and algorithms do you recommend for above problem? (My message receiving rate is 400 messages per second)


问:
DB Schema for a questionnaire - Different output from different combinations of responses
A user is required to complete a questionnaire - answering the questions in various categories.

Depending on the responses from the user, the user will be presented with a number of recommendations.

A recommendation could have a 1:1 relation with the question asked.

A recommendation could be made based on either one, or another question being answered. (Either, Or)

Some recommendations will be made based upon responses from say 3 of 9 questions. e.g. recommendation 1 will be shown when 3 from a set of questions are answered positively.

I am looking for assistance with somehow creating a generic lookup so that based on the user's responses, I can make the recommendations.

Questions may be added and removed, similarly, recommendations may be added and removed. I need to keep the system quite generic and extensible.

Schema so far:

```<code>CREATE TABLE `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `order` int(11) NOT NULL DEFAULT '10',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `questions` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category_id` int(10) unsigned NOT NULL,
  `question` text COLLATE utf8_unicode_ci NOT NULL,
  `order` int(11) NOT NULL DEFAULT '10',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `recommendations` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `recommendation` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```

答:
Most people in production are painfully forced to keep things simple as the data size grows. There is normal form and non normal form in design and real world is a different animal. So you may not want a five table join in production.

So in non normal form, one table. It is important to isolate the data changes so you are not forced to change the structure of the tables in production because of client functionality shift. Can use XML, HTML or other format like JSON. The goal here is to keep the structure simple and yet flexible as client needs are always changing.

A good check is to always write out your select statements to match your business functionality and simplify your tables accordingly. Business rules in the master design will clarify the relationships.

Without a full context a complete answer is futile with your question.


问:
The difference between (-(a*b)) and ((-a)*b)
One of our teachers said that there is just one example that there is a difference between (-(a*b)) and ((-a)*b). He said by using two's complement you can find one.

I am trying to find this example. Can anyone please help me?

Thanks in advance

答:
Two's complement represents numbers in the range -(2**(N-1)) .. (2**(N-1))-1, where N is the number of bits.

For example, 16-bit 2's complement represents -32768 .. 32767.

If the product of A and B is 32768, the first expression will overflow, because 32768 cannot be represented before being negated, while the second expression will do fine because it generates the negative maximal number directly.

Two's complement has the drawback in certain computations that it truncates toward negative infinity.  One's complement truncates toward zero (or negative zero).  This is important in certain applications (details are very company-proprietary to a previous employer), and I believe this is at least part of the reason Seymour Cray used one's complement on the CDC 6600 and its follow-ons.


问:
Why does C use the asterisk for pointers?
I'm just now learning about C.

I find it odd that the creators chose the asterisk (*) as the symbol for pointers rather than a symbol that actually looks like a pointer (->).

Considering how confusing dereferencing and function pointers can be, is there a historical, or even practical, reason for using the asterisk?

答:
I was asked by a student if & and * were chosen because they were next to each other on the keyboard (something I had never noticed before). Much googling led me to B and BCPL documentation, and this thread. However, I couldn't find much at all. It seemed like there were lots of reasons for * in B, but I couldn't find anything for &.

So following @MichaelT's suggestion, I asked Ken Thompson:

From: Ken Thompson < ken@google.com >

near on the keyboard: no.

  c copied from b so & and * are same there.

  b got * from earlier languages - some assembly,

  bcpl and i think pl/1.

  i think that i used & because the name (ampersand)

  sounds like "address." b was designed to be run with

  a teletype model 33 teletype. (5 bit baud-o code)

  so the use of symbols was restricted.


答: What you seem to need is an additional table mapping questions to a question group and another mapping question groups to recommendations. Based on that data, you could query the questionnaire and find all question groups that it completely matches. From this, you can derive your recommendations.</p>

Title: DB Schema for a questionnaire - Different output from different combinations of responses

Body:
A user is required to complete a questionnaire - answering the questions in various categories.

Depending on the responses from the user, the user will be presented with a number of recommendations.

A recommendation could have a 1:1 relation with the question asked.

A recommendation could be made based on either one, or another question being answered. (Either, Or)

Some recommendations will be made based upon responses from say 3 of 9 questions. e.g. recommendation 1 will be shown when 3 from a set of questions are answered positively.

I am looking for assistance with somehow creating a generic lookup so that based on the user's responses, I can make the recommendations.

Questions may be added and removed, similarly, recommendations may be added and removed. I need to keep the system quite generic and extensible.

Schema so far:

```<code>CREATE TABLE `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `order` int(11) NOT NULL DEFAULT '10',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `questions` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category_id` int(10) unsigned NOT NULL,
  `question` text COLLATE utf8_unicode_ci NOT NULL,
  `order` int(11) NOT NULL DEFAULT '10',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `recommendations` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `recommendation` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```


答:
My experience is that beyond having a Makefile (or sometimes cmake :-(), it varies according to the personal tastes of the individual.  Personally, I use a editor that runs from the command line (xterm), and have editor macros (created over a couple of decades) that more or less imitate many of the features of an IDE without the baggage.  For instance, one keypress runs make (after saving all open files), dumps the output into a file which I see in the editor, then another keypress on an error line takes me to the originating line in the source.  (And this works for other things, like LaTeX documents.)  Other people like to use vi(m), emacs, or other tools.

The common core is that almost everything I've seen builds from a Makefile.  If the project is intended for wide distribution, that may be generated by autoconf tools.  (Or cmake &c.)  However, if you like IDEs, Wikipedia has a long list that run in Linux: https://en.wikipedia.org/wiki/Category:Linux_integrated_development_environments  I've no experience with any of them, other than a short (and unpleasant) stint with Eclipse - and that some years ago, so it may well have improved.

Title: How do you usually compile C/C++ source code ? (Large code bases)

Body:
It's been quite some times since I began learning C and C++ but I've been very limited only to the Windows platform and the Visual Studio environment. Recently, I wanted to look into some open source C/C++ projects, so I downloaded a few but I was frustrated because I didn't know how to compile those software. Then I had to learn about all those g++ and make stuff and still I only have very limited knowledge in those subjects.

Having been used to an environment like Visual Studio, where you can write the code, hit the play button and boom you're all good to go, it was hard for me to compile a program with the command line at first.

So my question is, if you're a C/C++ developer, how do you compile your code ? How do you compile relatively large code bases ? What are the tools that you use ? Do you use IDEs or simply text editors ? What is the compiler that you use ? Do you build your applications from the command line ? What is the OS that you usually compile on ?

SideNote: My linux knowledge is zero.


答:
Algorithms are a sequence of steps. They don't depend on what is (or isn't) executing them.

However, the time complexity of an algorithm can depend on what is executing it. That's why detailed analysis of an algorithm requires a "model of computation", such as a random-access machine.

Whether or not memory is randomly accessible certainly affects how long your algorithm takes to run, and most algorithms assume this is the case whereas in reality most architectures don't satisfy this condition.


问:
Is a programming language a set of programs or a set of instructions?
From Structured Computer Organization by Tanenbum

A program is  a sequence of instructions describing how to perform a
  certain task.

When trying to see a programming language as a formal languages added with semantics, I heard that a programming language is a set of valid programs (valid according to the syntax and other aspects of the language).

When reading Structured Computer Organization by Tanenbum, I understood that a programming languages is a set of instructions, from

Each machine has a machine language, consisting of all the instructions that the machine can execute.

So I wonder if a programming language is a set of programs or a set of instructions? Thanks.

答:
computer program is a sequence of instructions, written to perform a specified task with a computer (by Wikipedia)

It has nothing to do with programming language. it's just the definition of program.

What is programming language?

A programming language is a language (like English language, Persian, Arabic, etc), it has syntax and semantic (syntax: valid sentences and invalid sentences). The meaning of the sentences (semantic), however, depends on the listener (computer). if you want to communicate with computer it should understand what you mean (machine language). However, you can use a high-level programming language and a compiler or an interpreter which translate your language to the machine language.

Is programming language a set of programs it accepts?

It's another definition of a language, and mainly concerns the syntax. It says a programming language is all the programs which are valid in that language.

For example English language is all the texts (infinite) which are according to English words and grammar. But you can't guarantee, these text have any meaning as you read them. However, if we include semantic accuracy (which is meaningful related to the target audience, for example computer) then yes that sentence is true.


问:
When should I use a precondition and when to include another use-case to provide those conditions?
For example, suppose 'Borrwoing a book' a use case:

I can figure out two description for it:

Description one:

Precondition: The member to access this use-case should be already logged in.

OR EVEN Precondition: The book id should be specified.

Enter the book id

....

Description two:

Include the Login use-case

OR Include the Search the book by title use-case

Enter the book id

....

However here, it seems the first approach is better, but is there any general rule for it?
Could they be two way for writing a use-case?

答:
Use cases should already identify the type of user (a logged-in user is a type of user, as is an administrator or some other role like sales clerk).

As a logged in user, I need the ability to request a book by title.


问:
Start to understand an existing project for beginner programmer
I want to understand an existing project to improve myself more, but I am not sure if the project would be overwhelming for me or not. I am not sure if I am capable of understanding it. I even think that I will fail. When I look at projects at a glance, it makes me feel scared to see thousand line of codes.

I don't even know where to start reading code. Do I have to follow by debugging or is there something else?
Can you please guide me in this situation? I am totally getting confused at the start.

Edit : A few thing to specify about my question.

I know C# language and I have learned some WEB technologies like ASP.NET, MVC 2, and Web Forms but I am sure there still will be many thing which I don't know. I label myself as beginner but it is just because of a lack of professional experience in this area. But my OOP understanding is good enough. I am wanting to improve myself on WEB, so I am looking for WEB projects like blog engines which are simpler than others for starting.

答: My favorite key when working with a project that I've either had from inception to deployment or just looking at an example is F12.  In most IDEs I'm aware of, it traces the object, method, or other bit of code to its source if it's user-defined.  System language files display a header/interface, depending on which language you're working with.  If the files are organized well, F12 will show you an order by which methods travel through the stack, which helps superbly with debugging.</p>


问:
Is having source code for a Go project outside GOPATH a bad idea
I am working on a new project using Go, and we are all new to Go. We are following the standard go directory structure, and having all code under

$GOPATH/src/github.com/companyname/projectname

which is also the root of a git repository

The standard recommended path layout does seem a bit strange, especially if we are working on a multi-language project, e.g. a Go based rest/http backend, and an html/javascript front-end. In that case I would probably want my project structure to look like this:

```<code>/
  doc/
  src/
    server/
      main.go
      module1/
        module.go
    client/
      index.html
  Makefile
</code>```

But is it actually necessary to have the code placed inside the GOPATH?

As an attempt I created a small program where the source code was outside the GOPATH. I could easily split the project into packages, so the main package could reference a foo package in a foo/ folder using import "./foo".

As far as I can see, there are two things this disallows me:

Other code cannot import this code. This is not a problem as we are building a service specifically for the company.

I cannot use go install to install it. This is not a problem either. The build pipeline installs the tool.

It does however allow the build server to not have its workspace be located inside the GOPATH

Is such an approach discouraged? If so, why so?

Are there other negative side effects than the two I have listed?

Bear in mind that this is a private project for a company, not public open source code.

Detaching the actual project from the GOPATH seems tempting, but one should be careful in breaking the rules when you are on the Shu stage

答:
(disclaimer: I like designing stuff like this but I'm new to Go, I haven't tried it in practice)

Idea: Why not both?

There are two polar options available if you take symlinking into account:

(A) Code in src, symlinked to workspace

```<code>/
  doc/
  src/
    server/
      projectname/
    client/
      index.html
  go_workspace/
    src/
      companyname/
        projectname -> ../../../src/server/projectname
      github.com/
        someone/
          library/
    bin/
    pkg/
  Makefile
</code>```

(B) Code in workspace, symlinked to src

```<code>/
  doc/
  src/
    server/
      projectname -> ../../go_workspace/src/companyname/projectname
    client/
      index.html
  go_workspace/
    src/
      companyname/
        projectname/
      github.com/
        someone/
          somelib/
    bin/
    pkg/
  Makefile
</code>```

I'd lean towards "A" because:

all your sources live close together physically,

projectname can easily have its own repo, or you can have one repo for your whole project,

you can keep whole go_workspace unversioned and initialize it through a make step (using godep then symlinking the project)

Body:
(disclaimer: I like designing stuff like this but I'm new to Go, I haven't tried it in practice)

Idea: Why not both?

There are two polar options available if you take symlinking into account:

(A) Code in src, symlinked to workspace

/
  doc/
  src/
    server/
      projectname/
    client/
      index.html
  go_workspace/
    src/
      companyname/
        projectname -> ../../../src/server/projectname
      github.com/
        someone/
          library/
    bin/
    pkg/
  Makefile

(B) Code in workspace, symlinked to src

/
  doc/
  src/
    server/
      projectname -> ../../go_workspace/src/companyname/projectname
    client/
      index.html
  go_workspace/
    src/
      companyname/
        projectname/
      github.com/
        someone/
          somelib/
    bin/
    pkg/
  Makefile

I'd lean towards "A" because:

all your sources live close together physically,

projectname can easily have its own repo, or you can have one repo for your whole project,

you can keep whole go_workspace unversioned and initialize it through a make step (using godep then symlinking the project)


问:
How to automatically connect letters into words?
I would like to connect letters into meaningful words? E.g.

input:

```<code>T E ST IN G WE B A P P LIC AT IO N S
</code>```

output:

```<code>TESTING WEB APPLICATIONS
</code>```

what kind of task is this? A task in NLP, or just some string operation?
What kinds of NLP task(s) are involved?

Are there software programs that I can use to do the job?

What are some programming libraries that I can call to do the job?

note that:
my original text not shown here is a mixture of space-separated letters and words, and are there software programs or programming libraries that can find out and take advantage of the existing words?

答:
You definitely need NLP. For example:

```<code>EX P ER T S E XC H A NG E
</code>```

may either mean

```<code>EXPERT SEX CHANGE
</code>```

or

```<code>EXPERTS EXCHANGE
</code>```

depending on context.

Body:
You definitely need NLP. For example:

EX P ER T S E XC H A NG E

may either mean

EXPERT SEX CHANGE

or

EXPERTS EXCHANGE

depending on context.


答:
Actually this is not an AI problem, this is pure programming question solved by dynamic programming.

If you simply want to connect the tokens into a list of correctly spelled words then you proceed as follows (Top down style dynamic programming):

```<code>public class Connector {

    public static void main(String[] args) {

        List<String> tokens = new ArrayList<String>(); // input
        Connector connector = new Connector();

        @SuppressWarnings("unused")
        List<String> ret = connector.connect(tokens);
    }

    Map<Integer, List<String>> cache;
    List<String> tokens;

    public List<String> connect(List<String> tokens) {
        this.cache = new HashMap<Integer, List<String>>();
        this.tokens = tokens;
        List<String> ret = connect(tokens, 0);
        return ret;
    }

    List<String> connect(List<String> tokens, int start) {
        if (cache.containsKey(start)) {
            return cache.get(start);
        } else {
            List<String> results = new ArrayList<String>();
            connectHelper(tokens, start, results);
            cache.put(start, results);
            return results;
        }
    }

    void connectHelper(List<String> tokens, int start, List<String> results) {
        int n = tokens.size();
        for(int i = start + 1; i < n; i++) {
            String part = concat(tokens, start, i);
            if (dictContains(part)) {
                List<String> restParts = connect(tokens, i);
                for(String oneRestPart : restParts) {
                    results.add(part + " " + oneRestPart);
                }
            }
        }
    }

    static private String concat(List<String> tokens, int low, int hi) {
        StringBuilder sb = new StringBuilder();
        for(int i = low; i < hi; i++) {
            sb.append(tokens.get(i));
        }
        return sb.toString();
    }
}
</code>```

Title: How to automatically connect letters into words?

Body:
I would like to connect letters into meaningful words? E.g.

input:

```<code>T E ST IN G WE B A P P LIC AT IO N S
</code>```

output:

```<code>TESTING WEB APPLICATIONS
</code>```

what kind of task is this? A task in NLP, or just some string operation?
What kinds of NLP task(s) are involved?

Are there software programs that I can use to do the job?

What are some programming libraries that I can call to do the job?

note that:
my original text not shown here is a mixture of space-separated letters and words, and are there software programs or programming libraries that can find out and take advantage of the existing words?

Body:
Actually this is not an AI problem, this is pure programming question solved by dynamic programming.

If you simply want to connect the tokens into a list of correctly spelled words then you proceed as follows (Top down style dynamic programming):

public class Connector {

    public static void main(String[] args) {

        List<String> tokens = new ArrayList<String>(); // input
        Connector connector = new Connector();

        @SuppressWarnings("unused")
        List<String> ret = connector.connect(tokens);
    }

    Map<Integer, List<String>> cache;
    List<String> tokens;

    public List<String> connect(List<String> tokens) {
        this.cache = new HashMap<Integer, List<String>>();
        this.tokens = tokens;
        List<String> ret = connect(tokens, 0);
        return ret;
    }

    List<String> connect(List<String> tokens, int start) {
        if (cache.containsKey(start)) {
            return cache.get(start);
        } else {
            List<String> results = new ArrayList<String>();
            connectHelper(tokens, start, results);
            cache.put(start, results);
            return results;
        }
    }

    void connectHelper(List<String> tokens, int start, List<String> results) {
        int n = tokens.size();
        for(int i = start + 1; i < n; i++) {
            String part = concat(tokens, start, i);
            if (dictContains(part)) {
                List<String> restParts = connect(tokens, i);
                for(String oneRestPart : restParts) {
                    results.add(part + " " + oneRestPart);
                }
            }
        }
    }

    static private String concat(List<String> tokens, int low, int hi) {
        StringBuilder sb = new StringBuilder();
        for(int i = low; i < hi; i++) {
            sb.append(tokens.get(i));
        }
        return sb.toString();
    }
}


问:
Can I use GPL software in a commercial application
I have 3 questions about the GPL here:

If I use GPL software in my application, but don't modify or distribute it, do I have to release my application under the GPL?

What if I modify some software that my application uses. Then do I have to release my application under the GPL, or can I just supply the modified software under the GPLs terms.

And what if I use GPL software, but don't modify it, can I distribute it with my application?

My case in point is, I have a PHP framework which I use the GeSHi library to highlight some output.

Because GeSHi is GPL, does my framework have to be GPL?

Can I modify GeSHi for particular use cases of my application if I supply the modifications back to the GeSHi maintainers?

Can I redistribute my framework with GeSHi?

答:
Disclaimer: I am not a lawyer and I haven't read either version of the GPL in a while, so this answer might be legally inaccurate.

If you release/distribute software containing GPL'd components (such as statically linked libraries), your software must be covered by the GPL. (This is the impression given for version 2; version 3 may be different.)

If you release/distribute software using LGPL'd libraries, your software doesn't need to be covered by the GPL, but the libraries must retain the LGPL.

Modification of [L]GPL'd components suggests contribution back to the creator/maintainer. I'm not clear on how that affects your product's licensing.

ContentLicense: CC BY-SA 2.5


问:
advantage of having multiple REST web services
I have a application designed using Spring REST service. the application has two REST projects:

Web

Core

Web has html, JavaScript and Java classes (ajax calls this REST). These Java classes in turn call the core project again through REST service.

What is the advantage of having them in two separate projects instead of one?

答:
An application design like this might be advantageous if you take the broader infrastructure into account.

Possibly, your Core project serves more than one other project and combines common business logic across your application infrastructure. Then it might make sense to have it as a separate web application rather than compiled into the same application. You could have an entire infrastructure, that consists of small web projects, that call each other using REST services.

This is commonly referred to as a Microservices Architecture. In short, having this allows centralized logic, easy updates of the individual parts of the infrastructure and each part of the infrastructure to use different technology, while all work together.

If on the other hand, the Web project is the only user of the Core project you really have some wasteful overhead, unnecessary complexities and cause for error introduced into that application.


问:
The meaning of 'fully traversable namespaces' in JavaScript
During research into architecture of single page applications, I came across the following resource by Mikito Takada, written around 2013: http://singlepageappbook.com/

In his introduction he distinguishes between architecture (conceptual parts of the application including the view and model) and asset packaging (how the application is divided into files and modules). In the context of discussing asset packaging, he mentions fully traversable namespaces as an example of bad packaging practice.

I would guess this phrase described a situation where all code could access all code. However he also separately mentions global code and global names as examples of bad practice, leaving me struggling to differentiate between global code and fully traversable namespaces.

Would anybody be kind enough to define what is meant by a fully traversable namespace or generally correct my understanding of these terms?

Thankyou

答:
From reading the cited work I think you are right in assuming the authour is referring to global namespaces as bad practice and they are using fully traversable namespaces as an example of something you should not do as it is under the column "Messy and random".

I have not heard this term before and the book does not specify exactly what it is supposed to mean.

I would say that the point they are trying to make is that you can get at all aspects of the program, functions and variables of an object and its prototype object from anywhere else. In Java there is the idea of access modifiers with public, private, package protected, and protected modifiers that limit module's access to other parts of the program. Javascript doesn't handle access this way.

The authour states that by using the Javascript Global object "Every piece of code is made global by default" and contrasts this with "Implementation details are inaccessible outside the package". I believe this is a bit misleading as Javacsript functions do provide a new scope and do not expose 'every piece of code'.

Javascript uses the block syntax, but unlike other languages that enclose blocks of code within braces, Javascript does not limit scope to within these sections. The generic advise of declaring variables as close to the code that will use it becomes a problem in Javascript. You can limit scope within Javascript functions and modules.

The main point the authour is trying to make is good; when using Javascript be careful to understand what scope your variables are in, and partitioning your code into sensible units is a good idea for readability / maintainability.


问:
What to do when time estimation goes wrong?
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

答:
Time-based estimates are guesses about the future, and that will always fail in the long run. It's a pointless battle you can't win.

Stop estimating in days and start using relative estimation instead. Here is a simple example:

Assign a number to each task. The toughest task may be 10 and the easiest task 1.

Start programming to complete your tasks.

After one week, stop your work and sum all completed tasks' numbers. Lets say you end up with 14. That's your weekly velocity.

Next week, repeat the process again. I bet your velocity will change, but not much. After a few weeks with this, your velocity should be pretty stable and that is what we are aiming for. Now you can start making plans with confidence. Pick tasks that sums up to your velocity and your PM can be quite certain it will be completed as promised. That is how you should tackle your project leaders.


问:
Is there a standard file for building a settings window?
I've made GUI settings windows for a lot of files, but it's always been the same way I make a regular GUI content window. I want to dynamically produce one that will be parseable to show standard GUI elements (a possibly hierarchical set of panes containing widgets like checkboxes, dropdowns, lists, text fields, etc.).

I'm hoping for something like what this XML I just whipped up implies is possible:

<settings>
    <settings-pane name="food">
        <options name="sandw">
            <options name="bread">
                <single-select name="type">
                    <option name="white"/>
                    <option name="wheat"/>
                </single-select>
                <number name="count" min="2" max="10"/>
            </options>
            <multiple-select name="fill" min="1" max="2">
                <option name="cheese"/>
                <option name="pb"/>
                <option name="jelly"/>
                <option name="groundBeef"/>
            </multiple-select>
        </options>

        <options name="drinks">

        </options>
    </settings-pane>

    <settings-pane name="furniture">

    </settings-pane>

</settings>
```

Of course, I could use something like this, but I want to be sure that whatever I use is standardized, not only so that anyone can come in and use/inspect my files, but also so I know it's been tested and will work in unforeseen cases.

答: What you're probably looking for is a PropertyGrid.  Winforms has one native.  You can find one for WPF here.  There are several available for HTML5.</p>


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

If you can't understand the code, why you think the comments are your solution?

I don't know his programming style, but I admit that if the name of functions and variables are misleading, it makes understanding a code very hard. But if names and functions or even the organization of the program (classes, methods, properties...) are so that make the code understandable, then the code actually will talk to you by itself.

You'd better ask him for the program architecture and if you want to request him for something, request for some more meaningful names for functions; that is more convenient for him to do.


问:
Why is base-for-all-objects discouraged in C++
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?

答:
Because what would that object have for functionality? In java all the Base class has is a toString, a hashCode & equality and a monitor+condition variable.

ToString is only useful for debugging.

hashCode is only useful if you want to store it in a hash-based collection (the preference in C++ is to pass a hashing function to the container as template param or to avoid std::unordered_* altogether and instead use std::vector and plain unordered lists).

equality without a base object can be helped at compile time, if they don't have the same type then they cannot be equal. In C++ this is a compile time error.

the monitor and condition variable is better included explicitly in a case by case basis.

However when there is more that it needs to do then there is a use-case.

For example in QT there is the root QObject class which forms the basis of thread affinity, parent-child ownership hierarchy and signal slots mechanism. It also forces use by pointer for QObjects, However many Classes in Qt don't inherit QObject because they have no need for the signal-slot (particularly the value types of some description).

ContentLicense: CC BY-SA 4.0


答:
Whenever you build tall inheritance hierarchies of objects you tend to run into the problem of the Fragile Base Class (Wikipedia.).

Having many small separate (distinct, isolated) inheritance hierarchies reduces the chances of running into this problem.

Making all of your objects part of a single humongous inheritance hierarchy practically guarantees that you are going to run into this problem.

Title: Why is base-for-all-objects discouraged in C++

Body:
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?


问:
Home project & work project sharing common library under development
Those of us who do software development not only for a living, but also as a hobby, have probably encountered the following scenario:

Say, there is a project at work called WorkApplication on which you work together with a number of colleagues. And suppose that this application is making use of a library called SharedLibrary which is under development, meaning that there will be refactoring done on SharedLibrary, and any such refactoring must cascade to WorkApplication, so that WorkApplication always compiles and runs.

Obviously, for this to work, whenever someone opens WorkApplication in their IDE, they must also open SharedLibrary.

In Visual Studio parlance, this would make both WorkApplication and SharedLibrary "projects" under the same "solution".

In IntelliJ IDEA parlance they would be "modules" under the same "project".

In Eclipse parlance, they would be "projects" under the same "workspace".

Now, suppose that you also have a home project HomeApplication that you play with at home, (alone,) in which you also want to use SharedLibrary. (Suppose that the workplace does not mind if you use SharedLibrary for your own stuff, just as you don't mind if the workplace benefits from work that you put on SharedLibrary while working at home.)

Naturally, whenever you refactor SharedLibrary you want this to cascade not only to WorkApplication, but also to HomeApplication.  Suppose that you are the only developer responsible for SharedLibrary, so your colleagues are unlikely to ever modify it, so you do not have to worry about SharedLibrary ever being refactored by someone who knows nothing about HomeApplication.  What you want to make sure is that whenever you refactor SharedLibrary, regardless of whether you are doing it in the context of work or hobby, both WorkApplication and HomeApplication will always be updated.

How do you juggle these three entities so as to keep everything updated?

The problem seems to be that different parts of the solution/project/workspace will need to be in different source code repositories: WorkApplication and SharedLibrary need to be in the repository of your workplace, while HomeApplication needs to be in your home repository.

I am not sure how to mix multiple source code repositories under the same solution/project/workspace. Can it be done?  Has anyone tried it?  Does it work? What problems are common?

I can imagine scenarios where you forfeit the benefits of version control system operations from within the IDE, and instead you do all your updating/committing using external tools, each time separately for each repository, but can it somehow be done from within the IDE?

I do not want to tie this question to any specific IDE, but let me just mention that the IDE that interests me most is IntelliJ IDEA. (Unfortunately, I find the VCS-related options of IntelliJ IDEA to be very confusing. It seems like I might be able to define multiple VCS servers within the same project, but it is not clear how.)

答:
You may think in terms of packages, which makes the location of the source irrelevant.

For instance, if you work with C#, your shared library can be published as a NuGet package. When you refactor the library, you don't cascade anything immediately to work application; instead, you publish a new version of the package, and when you're ready, you migrate the work application to the new version, like you would do if, for instance, Microsoft releases a new version of Entity Framework (you wouldn't put EF's source in your code base and ask Microsoft's developers to cascade their changes to your business apps, right?).

This is a publisher-consumer relation. You provide a free (eventually open source) package to your company which acts as your customer. They are free to update their apps to the new versions of your package, or to stay using the obsolete versions if they want to.

The fact that you work in this company is irrelevant: imagine yourself acting as a consultant who knows extremely well the concerned package and so deals with its actual implementation within the product.

Mixing home-grown projects with your work as source level is not a good idea.

If you host them separately (i.e. your personal library remains in your personal repository on your home server), this is problematic for the company, since:

There is no guarantee whatsoever that they will be able to access the source forever. What if you decide to remove it or to shut down your home server? Even loss of internet connectivity is problematic: at least developers should be able to access the corporate repository if it is hosted in the same building.

If you host them together, this creates a different set of issues:

The company may enforce specific rules you don't want to follow for your personal project, such as style guidelines. The company may require a specific code coverage, or linter-compliant code, or simply that any committed code is reviewed by your pairs. Those standards, normal in corporate environment, shouldn't apply to your personal project.

Even worse, the company may not require something right now, but set a new quality requirement one day. What would you do? Modify your personal library to match? Remove the library from the source code?

Some managers may not understand what you're doing and find it awkward. In the worst case, they may consider that you are spending your time working on your own project at work, which can be perceived very bad.

In the previous point, I mentioned updating your personal project to match company standards. What if your boss notices you are working on that (and so on your own project), while you're expected to solve bugs for the next release scheduled for the next week?

Intellectual property could be another concern. In many cases, the code within your corporate repository is the property of the company. You may find yourself unable to use, change or distribute your own project if you leave the company. More generally, everything may seem fine between you and your employer, and it is, until the relation becomes a mess and should be dealt by lawyers.

The publisher-consumer model solves all four problems:

The company knows they will be able to access the current version of your package forever. Removing a package from NuGet is possible, but very hard.

You don't have to follow any third-party rules and standards. This is your project, so your rules.

There is no way to blame you for working on your personal projects at work. They are clearly separate.

You keep the intellectual property of your project, and set the license of your taste. Again, your project, your rules.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
In general, I prefer camelCase.  However, that is because most of my career, I've working in languages and environments where the style guides normally recommend camelCase.  (Java, ECMAScript, C++).  You, being a PHP person, are likely to have the opposite preference.

That said, when you go beyond threeOrFourWords, or if you use initialisms likeXmlForExample, it stops being so readable.

That is why emacs gives us glasses-mode.


答: Because there are no functions shared by all objects. There's nothing to put in this interface that would make sense for all classes.</p>


问:
What is the relationship between scope and namespaces in Python?
In many resources I found "scope" and "namespaces" are used interchangeably, which seems a bit confusing since they mean different things.

Scope defines the region of the code where a name is available.

The LEGB rule defines the way names are looked up.

Namespace is a place where you look up names.

Then I read:

"names are bind to a namespace according to where they are assigned..." (which I believe is the deal with scopes in lexical scoping).

"functions add an extra namespace layer to your programs" [ref.] (don't they add a extra local scope?)

"all the names assigned inside a function definition are put in the local scope (the
namespace associated with the function call)."

"global scope—that is, a namespace in which variables created (assigned) at the top level of the module file live."

*all of the quotes are from learning python 5th edition ch17

Are namespaces in Python the way scopes are implemented? Are they the same thing? Can anyone enlighten me?

答:
There is an excellent article on Python namespaces here. To quote the relevant part to answer your question about the reference between scopes and namespaces:

A scope refers to a region of a program from where a namespace can be accessed without a prefix.

For example, imagine a simple die-rolling program:

```<code>import random  # 'random' is in module namespace

def roll(sides=6):  # 'roll' is in module namespace, 'sides' is in roll's
    return random.randint(1, sides)  # both 'random' and 'sides' are in scope here

# but sides can't be accessed out here
</code>```

roll has its own namespace, but the names in the module's namespace are also in scope.

Body:
There is an excellent article on Python namespaces here. To quote the relevant part to answer your question about the reference between scopes and namespaces:

A scope refers to a region of a program from where a namespace can be accessed without a prefix.

For example, imagine a simple die-rolling program:

import random  # 'random' is in module namespace

def roll(sides=6):  # 'roll' is in module namespace, 'sides' is in roll's
    return random.randint(1, sides)  # both 'random' and 'sides' are in scope here

# but sides can't be accessed out here

roll has its own namespace, but the names in the module's namespace are also in scope.


问:
Trade-off between locality and repetition
Let me explain what I mean by locality and repetition. The current crop of configuration management tools decouple the configuration from everything else even when it is somewhat detrimental to do so. One case where it is detrimental is in application configuration. I believe that application configuration should live in the same repository as the application itself instead of some other repository or a chef cookbook or a puppet module. Better yet the actual chef cookbook or puppet module should be alongside the application and the build system can figure out how to package the whole thing so that the deployment mechanism can be as simple as possible.

One problem with this set up is that it can lead to a lot of repetition because several packages are likely to use similar or even exactly the same chef cookbooks and puppet modules but instead of being in some central location these cookbooks and modules are now duplicated in each application repository. The instinctive thing to do in this case is to factor out the commonality and put it in its own repository but I think this is incorrect because it introduces non-locality. Now to understand how the application works across its entire lifecycle you have to chase down dependencies in some other place and sometimes it is not clear at all where this other place is because of the separation between operations and product development.

So what is the correct trade-off here? I think non-locality makes things more magical than they need to be and enforcing locality leads to unnecessary repetition.

答:
At least in the case of Puppet, you should Google the following:

Puppetfile (like Gemfile but for Puppet)

r10k

"control repo"

Hiera

The proper composition of a control repo to be consumed by r10k will solve 90% or better of the issues you've mentioned above. Your custom application can then be deployed with another component level Puppet module and be instantiated with all of the right data/config.

Other configmgmt tools have more or less similar tools and concepts but I cant pretend to be an expert on them.

As to Docker, you could make your deployment artifact an image built with Puppet rather than a package deployed by Puppet but you will eventually run into similar issues of providing correct settings for your environment and then you'll be looking at having to add something like etcd or Consul or ZooKeeper to the mix and...yes...that's also complicated.

Sorry I can't provide more detailed examples. Mobile. :)


问:
Perrin sequence help c++
Hey everyone I am trying to write a recursive function for a perrin sequence where it returns the nth term that a user enters which is:

```<code>P(0) = 3, P(1) = 0, P(2) = 2,
</code>```

and

```<code>P(n) = P(n − 2) + P(n − 3) for n > 2.
</code>```

The sequence of Perrin numbers starts with

```<code>3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39 ...
</code>```

I know I should put some sort of code in here but I am totally lost. We just learned recursive functions this week and I cannot figure out how to do this.

答:
This could be a good way to start with TDD.

First write method p in that way it returns 3 if argument is equal to 0

You assert that via checking if p(0) == 3

run the program

Then you modify method p that it returns 0 if argument is equal to 1

You assert that via checking if p(1) == 0

run the program (you might guessed it)

Then you modify method p that it returns 2 if argument is equal to 2

You assert that via checking if p(2) == 2

run the program (you might guessed it already)

Small hint: all checks/test must be okay - not in a series, but all together.

Yeah you did it the first part for the first three numbers.

then you modify the method to enter a special branch if n is larger than 2

Now comes the interesting part what to return here?

write a test which asserts that p(3) == 3

try something to make it return the value 3

maybe plainly return p(0)

run the program (you might guessed it already too)

write a test which asserts that p(4) == 2

you fail, now try something else

return the sum of p(n-2) and p(n-3)

run the program (did that?)

assert more values....

run the program (you should know that now.)

Title: Perrin sequence help c++


答:
This problem is called word segmentation or text segmentation, and it has been extensively studied.

Note that in languages such as Chinese, Japanese, and Korean, all text in a sentence normally appears with no whitespace.  Word segmentation is therefore a prerequisite for machine interpretation of CJK text.


问:
How were assemblers created straight from binary?
How did these earlier programmers know what combinations of binary produced certain results? Is there a way I can create an assembler from binary today?</p>

答:
Every microprocessor has an instruction set.  Each instruction corresponds to a specific binary code.  You can find out which binary code corresponds to which processor instruction by reading the specification sheet for the microprocessor.

From there, it's simply a matter of specifying the binary codes in the right order to produce the desired result.


答:
In fact Microsofts early C++ compilers and libraries (I know about Visual C++, 16 bit) had such a class named CObject.

However you have to know that at that time "templates" were not supported by this simple C++ compiler so classes like std::vector<class T> were not possible. Instead a "vector" implementation could only handle one type of class so there was a class that is comparable to std::vector<CObject> today. Because CObject was the base class of nearly all classes (unfortunately not of CString - the equivalent of string in modern compilers) you could use this class for storing nearly all kinds of objects.

Because modern compilers support templates this use case of a "generic base class" is no longer given.

You have to think about the fact that using such a generic base class will cost (a little) memory and runtime - for example in the call to the constructor. So there are drawbacks when using such a class but at least when using modern C++ compilers there is nearly no use case for such a class.


答:
Chef solves this problem by using dependency management (Berkshelf) and by applying cookbook patterns. Using the Environment cookbook pattern, you are encouraged to store your cookbook WITH your application (and this does NOT result in duplicated cookbooks, because any library / base / dependent cookbooks will be resolved with the dependency management tool.)

When it comes to application deployment, your cookbook should be able to search your binary repository, find the install package, download it, and install it. Doing this allows you to correctly separate the builds of your application and of your configuration automation.

More importantly, here's what not to do:

Build a docker image by hand and call it good "because Docker". Doing this is just as bad as having magical VM templates (and of course, nobody at your organization will understand how they were built, and that makes them difficult to update, etc). If you're going to use containerization, build the images with the automation.

Store everything in git-submodules, or build the entire repository. Instead make sure you're using dependency management and do well-versioned releases of all your software, including your configuration automation.

Overuse dependency management tools and break your code out into a million layers of abstraction. You really don't need a base, base, base cookbook. Just keep it simple with a few layers as necessary, refactor as you go.

Pretend that your configuration management solution is an "install script". It's not, it's an all-inclusive way to describe the state of your servers.

Build your cookbook with your application in the same build process. You do not want to do new builds of a large application when all you need is just to package up the cookbook. Instead, builds should be able to happen in parallel, especially if you have a large, distributed team.

Title: Trade-off between locality and repetition

Body:
Let me explain what I mean by locality and repetition. The current crop of configuration management tools decouple the configuration from everything else even when it is somewhat detrimental to do so. One case where it is detrimental is in application configuration. I believe that application configuration should live in the same repository as the application itself instead of some other repository or a chef cookbook or a puppet module. Better yet the actual chef cookbook or puppet module should be alongside the application and the build system can figure out how to package the whole thing so that the deployment mechanism can be as simple as possible.

One problem with this set up is that it can lead to a lot of repetition because several packages are likely to use similar or even exactly the same chef cookbooks and puppet modules but instead of being in some central location these cookbooks and modules are now duplicated in each application repository. The instinctive thing to do in this case is to factor out the commonality and put it in its own repository but I think this is incorrect because it introduces non-locality. Now to understand how the application works across its entire lifecycle you have to chase down dependencies in some other place and sometimes it is not clear at all where this other place is because of the separation between operations and product development.

So what is the correct trade-off here? I think non-locality makes things more magical than they need to be and enforcing locality leads to unnecessary repetition.


问:
How are ASCII code associations actually stored and retrieved?
I was reading about compilers and was given an example of creating a basic compiler that recognizes escape sequences without referencing ASCII.

Somebody suggested that once I compile a piece of code with ASCII numbers, I can then recompile a different snippet of code without actual reference to the
ASCII number, and can instead use the escape character explicitly.

I'm confused at how you can get from the ASCII number, to an actual escape sequence, there seems to be a missing step somewhere in the explanation.

答:
The puzzle becomes quite a bit easier once yo understand a fundamental truth about data storage in computers. The truth is this:

Characters do not exist.

Computers cannot deal with characters. Printer drivers, video outputs, teletypes etc. can generate shapes of letters and therefore provide the necessary illusion that someone is writing something for you to read, but it's an illusion nevertheless. Fundamentally, computers store numbers and nothing else. In order to manage letters, words and texts, a common Encoding has to be agreed on by all users, and it is this character encoding that associates, e.g.,  A with 65.

It follows that the encoding has to be chosen, implemented and adhered to long before you write a compiler. Every program that is to print user-readable output must be able to store a 65 and rely on the convention that the O.S. display driver will show an "A" in its place, etc. In other words, whatever operating system you write a compiler on already has a convention for associating numbers with characters, and the new-written compiler will simply use the same convention that all existing programs do.

In the case of escape sequences, it's often something like "a \n should correspond to a newline character, a \r to a carriage return character". Those two characters are - by the already existing convention - 10 and 13, so it's enough to simply put those constants in to do the right thing. The compiler doesn't know these values anymore than a text editor does. An editor accepts the number 65 (as sent by the keyboard driver when you press "A") and stores it on disk, and later it retrieves it from disk and the display driver simulates an "A" on the screen in its place. This works because the keyboard driver and the display driver agree on how to interpret the numbers in your text file.

It's the same with a compiler and the language runtime. Programming with characters works because the compiler accepting your source code and the runtime and I/O hardware that run your executable agree on how to map characters to numbers and back. If you port a compiler to a different platform with a different character encoding (rare today but a common task when compilers were invented), this will always involve at least some hackery to adapt this mapping.  (This is one of the times where you realize just how lucky we are that such fundamental issues have largely been standardized and our generation can usually forget about them - but the issues are still there, and compiler writes need to understand them.)


问:
When to use a nosql database such as mongodb over mysql?
I'm new to the concept of nosql databases and have never used it. Based on what I've read and the little that I've understood I still don't see how they can be particularly useful if you can't make references between data, if there's no concept of foreign key.

How would I forexample query something simple as 'find all the comments posted by this user', 'find all photos that belong to an album entity' etc.

Do nosql systems move away from the static relational data-model but still let you keep track of such references, is there something analogous to foreign keys that you can utilize in queries?

答:
In some cases, you won't need foreign keys. For instance:

Find all the comments posted by this user

can be as simple as loading the comments part of a document corresponding to a user. This is called denormalization: instead of having two sets with a join, you have one document and everything you need is inside the document. One query, no joins, better performance.

But in some circumstances, this may lead to data duplication, so linking from one to another document could be suitable. In this case, you may be interested by MongoDB normalization, foreign key and joining, Database References page and especially DBRefs feature.


问:
Is TDD the best software development philosophy?
Question:

Why not just use BDD-style acceptance tests and do away with unit tests, integration tests, functional tests and all other tests?

I have been doing some research into the differences between different types of testing as well as different software development philosophies.

Looking at the list of software development philosophies and reading about different types of testing lead me onto a research to find out why we use unit tests, integration tests and functional tests if we have acceptance tests.

I hate to be the one to kill the holy cow but I feel like if you have acceptance tests in a BDD-style environment like given, when, then then you don't really need any other tests since you will be delivering exactly what functionality is required by the business anyway with just acceptance tests.

Some arguments for using unit, integration and functional tests:

Unit tests ensure things at a lower level are correct: Who cares? if the business is happy with what they've received, then what difference does it make?

Unit tests speed up long-term development time: Is it really worth the trade-off?  Where there is code there are bugs, tests are not exempt from this. The time spent writing and debugging 5,000 unit tests vs. the time debugging 50 acceptance tests seems like an obvious choice?

Unit tests/TDD ensures good architecture: No they don't. Each unit test is a design decision and is extremely vulnerable to overall poor architecture.

Integration tests ensure the overall performance is accurate and optimal: Why can't this be just another Then condition in acceptance tests? Why not just use selenium within the acceptance tests?

Functional tests ensure that output is as expected: Acceptance tests enhance this by providing an answer at build time rather than waiting for potentially incorrect results.

TDD ensures that when changes are implemented, nothing else breaks in the process: Acceptance tests will ensure this too since everything's based on business requirements/features.

答:
Acceptance tests act at a very different level than, say, unit tests.

A unit test is very precise: it deals with one method, sometimes a part of a method. This makes it a perfect choice for regression testing. You make a change. A test fails while it passed during the previous commit. Great, you can easily pinpoint the source of the regression both in time (from commit N-1 to commit N) and space (this method of this class).

With acceptance tests, good luck if some start to fail. One bad change may cause one acceptance test to fail, or maybe ten tests, or a hundred. When you look at those hundred tests turning red without giving any hint about the location of the bug, the only thing which comes to mind is to revert to previous commit and start over.

Imagine acceptance tests as tests which consider the system as a black-box and which test a feature of the system. The feature may involve thousands of methods to be run, may rely on a database, a message queue service, a few dozen of other things. An acceptance test doesn't care how much stuff is being involved, and don't all the magic which happens behind the scenes. This also means that multiple acceptance tests may rely on the same method, which in turn means that a regression in a single method often leads to several failed acceptance tests. I had cases where a regression caused suddenly approximately fifty system and acceptance tests to fail, without giving any hint about the location of the bug.

Unit tests consider the system as a white-box. They are aware of the concrete implementations, and test a specific method, not a feature. By using mocks and stubs, unit tests achieve enough isolation to not being affected by the world: if the method works, the tests succeed. If the method has a regression, those tests fail. If another method somewhere in the code base doesn't work, those unit tests still pass.

Imagine the following diagram which represents methods calling other methods:

Unit testing can be represented this way:

For example, unit tests U3 and U3′ are not affected by bugs in method 6, because it is replaced by a stub. Nor is it affected by the regressions in method 2, because the stub 5 doesn't rely on method 2. In the same way, U8″ doesn't care about method 7, because 9 is a stub and doesn't rely on 11 which in turn uses 7.

Imagine you make a commit and your CI informs you that U8′ now fails. Where would you search for the problem?

In U8′. Maybe the code it tests is correct, but the test is not. This happens, for instance, when requirements change: you change the code but forget to reflect the change in the tests.

In method 8. There could be a regression.

In stub 9. Maybe you implemented a change in code and in tests, but forgot to change the stubs.

On the other hand, you are sure the problem is not with method 11 or method 7.

Now this is how acceptance or system tests would look like:

Imagine you make a commit and your CI informs you that A/S2 failed. Guess where is the problem? Much more difficult, isn't it.

Obviously, another aspect is that, as I described above, a small change can cause many acceptance tests to fail. For instance, a regression in method 7 may lead to A/S1 and A/S2 to fail. With unit tests, a regression in method 11 may cause U11 to fail, but will not affect, for instance, U8.

This leads to a huge benefit: the time you spend locating regressions. I've seen programmers who, when a regression is found, simply revert the source to the latest working commit and start over, because the code is a mess, and they don't enjoy spending hours debugging, hoping to find the origin of the problem. This is unfortunate, especially when commits are done not as frequently as they can be.

With unit tests, you don't waste all this time. They simply tell you that you have an issue with a given method in a given class, so you can focus your attention to the concerned method right after you discover the regression.

Unit tests ensure things at a lower level are correct: Who cares? if the business is happy with what they've received, then what difference does it make?  [...]

Have you worked with really bad projects where you can't make a change without breaking at least ten things in random locations?

Unit tests don't magically solve this problem. However, you should care that things are correct at lower level. Quick hacks have a substantial maintenance costs. On the other hand, if the only thing programmers have are acceptance tests (and tight deadlines; and no insensitive to do their job correctly), when an acceptance test fails because somewhere, the font should be 12px, but appears to be 10px, they may eventually just end up writing:

```<code>this.font = 12;
</code>```

and wait until testers get back to them telling that now, the font is 12px in situations where it should be 14px.

Unit tests speed up long-term development time: Is it really worth the trade-off? Where there is code there are bugs, tests are not exempt from this. [...]

Tests won't magically make bugs go away. However, practice shows that writing a test, checking that it fails, then implementing the feature and checking that the test passes appeared to be a practice which generally leads to less bugs.

Similarly, why would anyone do code reviews? Reviewers are not exempt from lack of attention, and there are plenty of cases where a bug is missed by several reviewers and maintainers. This being said, you get more bugs without code reviews than with them.

Is it worth it? For your personal small app, not really. For business-critical code, yes, indeed.

Unit tests ensure good architecture: No they don't. [...]

They do, somehow. By forcing to test methods in isolation, you force programmers to rethink coupling. Unit testing usually leads to short methods, classes which do one and one only thing (Single responsibility principle), dependency injection, etc.

A 4000 LOC method which relies on a few hundred other methods and requires access to the database is impossible to unit test (while it is perfectly normal to add acceptance tests to such method).

In Going TDD in the middle of the project, I describe specifically this sort of projects. Bad architecture led to the case where it was practically impossible to add unit tests later. If unit tests were considered from the beginning, it would reduce the disaster. The code would still be bad (since written by the same programmers who were fine writing a 400 LOC spaghetti method), but not that bad.

Integration tests ensure the overall performance is accurate and optimal [...]

Don't know. Never heard of that. Performance should be checked by tests corresponding to the performance non-functional requirements.

Functional tests ensure that output is as expected [...]

Don't know.

TDD ensures that when changes are implemented, nothing else breaks in the process: Acceptance tests will ensure this too since everything's based on business requirements/features.  [...]

No, this is the role of regression testing. TDD's purpose is mainly to avoid writing tests which are not testing anything. This is why in TDD, the test should fail before you implement a feature: otherwise, either the test is wrong, or you actually don't need the feature.

Body:
Acceptance tests act at a very different level than, say, unit tests.

A unit test is very precise: it deals with one method, sometimes a part of a method. This makes it a perfect choice for regression testing. You make a change. A test fails while it passed during the previous commit. Great, you can easily pinpoint the source of the regression both in time (from commit N-1 to commit N) and space (this method of this class).

With acceptance tests, good luck if some start to fail. One bad change may cause one acceptance test to fail, or maybe ten tests, or a hundred. When you look at those hundred tests turning red without giving any hint about the location of the bug, the only thing which comes to mind is to revert to previous commit and start over.

Imagine acceptance tests as tests which consider the system as a black-box and which test a feature of the system. The feature may involve thousands of methods to be run, may rely on a database, a message queue service, a few dozen of other things. An acceptance test doesn't care how much stuff is being involved, and don't all the magic which happens behind the scenes. This also means that multiple acceptance tests may rely on the same method, which in turn means that a regression in a single method often leads to several failed acceptance tests. I had cases where a regression caused suddenly approximately fifty system and acceptance tests to fail, without giving any hint about the location of the bug.

Unit tests consider the system as a white-box. They are aware of the concrete implementations, and test a specific method, not a feature. By using mocks and stubs, unit tests achieve enough isolation to not being affected by the world: if the method works, the tests succeed. If the method has a regression, those tests fail. If another method somewhere in the code base doesn't work, those unit tests still pass.

Imagine the following diagram which represents methods calling other methods:

Unit testing can be represented this way:

For example, unit tests U3 and U3′ are not affected by bugs in method 6, because it is replaced by a stub. Nor is it affected by the regressions in method 2, because the stub 5 doesn't rely on method 2. In the same way, U8″ doesn't care about method 7, because 9 is a stub and doesn't rely on 11 which in turn uses 7.

Imagine you make a commit and your CI informs you that U8′ now fails. Where would you search for the problem?

In U8′. Maybe the code it tests is correct, but the test is not. This happens, for instance, when requirements change: you change the code but forget to reflect the change in the tests.

In method 8. There could be a regression.

In stub 9. Maybe you implemented a change in code and in tests, but forgot to change the stubs.

On the other hand, you are sure the problem is not with method 11 or method 7.

Now this is how acceptance or system tests would look like:

Imagine you make a commit and your CI informs you that A/S2 failed. Guess where is the problem? Much more difficult, isn't it.

Obviously, another aspect is that, as I described above, a small change can cause many acceptance tests to fail. For instance, a regression in method 7 may lead to A/S1 and A/S2 to fail. With unit tests, a regression in method 11 may cause U11 to fail, but will not affect, for instance, U8.

This leads to a huge benefit: the time you spend locating regressions. I've seen programmers who, when a regression is found, simply revert the source to the latest working commit and start over, because the code is a mess, and they don't enjoy spending hours debugging, hoping to find the origin of the problem. This is unfortunate, especially when commits are done not as frequently as they can be.

With unit tests, you don't waste all this time. They simply tell you that you have an issue with a given method in a given class, so you can focus your attention to the concerned method right after you discover the regression.

Unit tests ensure things at a lower level are correct: Who cares? if the business is happy with what they've received, then what difference does it make?  [...]

Have you worked with really bad projects where you can't make a change without breaking at least ten things in random locations?

Unit tests don't magically solve this problem. However, you should care that things are correct at lower level. Quick hacks have a substantial maintenance costs. On the other hand, if the only thing programmers have are acceptance tests (and tight deadlines; and no insensitive to do their job correctly), when an acceptance test fails because somewhere, the font should be 12px, but appears to be 10px, they may eventually just end up writing:

this.font = 12;

and wait until testers get back to them telling that now, the font is 12px in situations where it should be 14px.

Unit tests speed up long-term development time: Is it really worth the trade-off? Where there is code there are bugs, tests are not exempt from this. [...]

Tests won't magically make bugs go away. However, practice shows that writing a test, checking that it fails, then implementing the feature and checking that the test passes appeared to be a practice which generally leads to less bugs.

Similarly, why would anyone do code reviews? Reviewers are not exempt from lack of attention, and there are plenty of cases where a bug is missed by several reviewers and maintainers. This being said, you get more bugs without code reviews than with them.

Is it worth it? For your personal small app, not really. For business-critical code, yes, indeed.

Unit tests ensure good architecture: No they don't. [...]

They do, somehow. By forcing to test methods in isolation, you force programmers to rethink coupling. Unit testing usually leads to short methods, classes which do one and one only thing (Single responsibility principle), dependency injection, etc.

A 4000 LOC method which relies on a few hundred other methods and requires access to the database is impossible to unit test (while it is perfectly normal to add acceptance tests to such method).

In Going TDD in the middle of the project, I describe specifically this sort of projects. Bad architecture led to the case where it was practically impossible to add unit tests later. If unit tests were considered from the beginning, it would reduce the disaster. The code would still be bad (since written by the same programmers who were fine writing a 400 LOC spaghetti method), but not that bad.

Integration tests ensure the overall performance is accurate and optimal [...]

Don't know. Never heard of that. Performance should be checked by tests corresponding to the performance non-functional requirements.

Functional tests ensure that output is as expected [...]

Don't know.

TDD ensures that when changes are implemented, nothing else breaks in the process: Acceptance tests will ensure this too since everything's based on business requirements/features.  [...]

No, this is the role of regression testing. TDD's purpose is mainly to avoid writing tests which are not testing anything. This is why in TDD, the test should fail before you implement a feature: otherwise, either the test is wrong, or you actually don't need the feature.


答: I would definitely use such a database during the planning stages of a project (before development, before even design) to record data whose structure, relationships, and characteristics are not yet known and subject to analysis. I would try to make everything fit a relational model after that.</p>

Title: When to use a nosql database such as mongodb over mysql?

Body:
I'm new to the concept of nosql databases and have never used it. Based on what I've read and the little that I've understood I still don't see how they can be particularly useful if you can't make references between data, if there's no concept of foreign key.

How would I forexample query something simple as 'find all the comments posted by this user', 'find all photos that belong to an album entity' etc.

Do nosql systems move away from the static relational data-model but still let you keep track of such references, is there something analogous to foreign keys that you can utilize in queries?