问:
How does Chrome V8 work? And why was JavaScript not JIT-Compiled in the first place?
I have been researching Interpreters/Compilers, then I stumbled across JIT-Compilation - specifically Google Chrome's V8 Javascript Engine.

My questions are -

How can it be faster than standard Interpretation?

Why wasn't JIT-Compilation used in the first place?

My Current Understanding

Every Javascript Program starts out as source code, then, regardless of the method of execution, is ultimately is translated to machine code.

Both JIT-Compilation and Interpretation must follow this path , so how can JIT-Compilation be faster (also because JIT is time-constrained, unlike AOT-Compilation) ?

It seems that JIT-Compilation is a relatively old innovation, based off of Wikipedia's JIT-Compilation Article.

"The earliest published JIT compiler is generally attributed to work on LISP by McCarthy in 1960."

"Smalltalk (c. 1983) pioneered new aspects of JIT compilations. For example, translation to machine code was done on demand, and the result was cached for later use. When memory became scarce, the system would delete some of this code and regenerate it when it was needed again."

So why was Javascript  Interpreted to begin with?

I'm very confused, and I've done a lot of research on this, but I haven't found satisfactory answers.

So clear, concise answers would be appreciated. And if additional explanation about Interpreters, JIT-Compilers, etc. needs to be brought in, that's appreciated as well.

答:
The short answer is that JIT has longer initialization times, but is a lot faster in the long run, and JavaScript wasn't originally intended for the long run.

In the 90s, typical JavaScript on a web site would amount to one or two functions in the header, and a handful of code embedded directly in onclick properties and the like.  It would typically get run right when the user was expecting a huge page load delay anyway.  Think extremely basic form validation or tiny math utilities like mortgage interest calculators.

Interpreting as needed was a lot simpler and provided perfectly adequate performance for the use cases of the day.  If you wanted something with long-run performance, you used flash or a java applet.

Google maps in 2004 was one of the first killer apps for heavy JavaScript use.  It was eye-opening to the possibilities of JavaScript, but also highlighted its performance problems.  Google spent some time trying to encourage browsers to improve their JavaScript performance, then eventually decided competition would be the best motivator, and would also give them the best seat at the browser-standards table.  Chrome and V8 were released in 2008 as a result.  Now, 11 years after Google Maps came on the scene, we have new developers who don't remember JavaScript ever being considered inadequate for that sort of task.

Say you have a function animateDraggedMap.  It might take 500 ms to interpret it, and 700 ms to JIT compile it.  However, after JIT compilation, it might take only 100 ms to actually run.  If it's the 90s and you're only calling a function once then reloading the page, JIT is not worth it at all.  If it's today and you're calling animateDraggedMap hundreds or thousands of times, that extra 200 ms at initialization is nothing, and it can be done behind the scenes before the user even tries to drag the map.


问:
How to share data between web applications?
I have two web applications, say Application_1 and Application_2.

Application_2 has a database table named table_2, which changes infrequently, and needs to be accessed by Application_1.

Does it make sense to create a table_2 table in Application_1 and update it with an ETL task?

A straightforward solution would be expose the data through a REST API in Application_2, but this will break the decoupling between both applications and introduce a new point of failure in Application_1.

答:
Since you tagged the question with SOA, I suspect that you're thinking the right answer might be using a service interface.  Such a service interface should not expose the data, but the functionality you want to provide as a contract to be exposed by one application and consumed by the other application.

As the question is being asked in the abstract, this contract could range anywhere from providing answer to a very specific lookup to an event stream notifying the consumer of changes.

Either application (i.e. on either or both sides of the service interface) can make use of caching (copy of table) if they need to, but caching is an optimization that should not be prematurely applied.

Either way, these applications are coupled.  The ETL job you suggest will also couple the applications and probably result in a more poorly understood contract between the them than a well-designed service interface.

ContentLicense: CC BY-SA 3.0


答:
One way of doing this would be to creation an Application_3_API_service which would expose an API to both Application_1 and Application_2.

All services that currently do read/write operations in Application_1 and Application_2 would now hit various endpoints exposed on Application_3_API_service.

The only application with a database connection would be Application_3_API_service.

```<code>+---------------+     +---------------+
| Application_1 |     | Application_2 |
+---------+-----+     +--------+------+
          |                    |
+---------v--------------------v------+
|      Application_3_API_service      |
+-------------------------------------+
</code>```

Title: How to share data between web applications?

Body:
I have two web applications, say Application_1 and Application_2.

Application_2 has a database table named table_2, which changes infrequently, and needs to be accessed by Application_1.

Does it make sense to create a table_2 table in Application_1 and update it with an ETL task?

A straightforward solution would be expose the data through a REST API in Application_2, but this will break the decoupling between both applications and introduce a new point of failure in Application_1.

Body:
One way of doing this would be to creation an Application_3_API_service which would expose an API to both Application_1 and Application_2.

All services that currently do read/write operations in Application_1 and Application_2 would now hit various endpoints exposed on Application_3_API_service.

The only application with a database connection would be Application_3_API_service.

+---------------+     +---------------+
| Application_1 |     | Application_2 |
+---------+-----+     +--------+------+
          |                    |
+---------v--------------------v------+
|      Application_3_API_service      |
+-------------------------------------+


问:
How to represent alternative and sequential tasks?
I am experimenting with hierarchical task planning (in python) and I would like to have functions which return lists of tasks. I need to differentiate between alternative paths and sequential tasks. My current approach is to return a list of lists of tasks, e.g.:

```<code>def travel():
    return [ [call_yellow_cab, ride_yellow_cab, pay_driver],
             [call_limousine,  ride_limousine,  pay_driver] ]
</code>```

The sequential tasks would be call.., ride.., pay_driver. The first and second lists would represent alternative task sequences (cab or limousine).

As 'Explicit is better than implicit' according to 'The Zen of Python' I am curious if there is a more explicit way to differentiate between the alternative tasklists and the sequential tasks within.
Or is my approach not that bad as 'Simple is better than complex.' ?

答:
I find that naming intermediate results often provides semantic clarity to the humans reading it later, even if it doesn't change the end result.  Like focusing a lens, sometimes the proper point is easiest to see by taking it to extremes then backing off.  The extreme version of explicitness is:

def travel():
    yellow_cab_sequence = [call_yellow_cab, ride_yellow_cab, pay_driver]
    limousine_sequence  = [call_limousine,  ride_limousine,  pay_driver]
    alternatives = [yellow_cab_sequence, limousine_sequence]
    return alternatives
```

This makes it abundantly explicit you are returning alternative sequences, although I would probably back off from this point a little and merge the last two lines.  It also makes it easy to see opportunities to create function calls to reduce duplication or better separate abstraction levels, perhaps yellow_cab_sequence() or even ground_transportation_sequence("yellow cab").

You could also add clarity by choosing a name for the function such as travel_alternatives.

On the other hand, if your code truly stays as simple as your example, it's clear enough as-is.  Just keep the technique in mind as the complexity grows of explicitly naming intermediate results or splitting them into functions.

Body:
I find that naming intermediate results often provides semantic clarity to the humans reading it later, even if it doesn't change the end result.  Like focusing a lens, sometimes the proper point is easiest to see by taking it to extremes then backing off.  The extreme version of explicitness is:

def travel():
    yellow_cab_sequence = [call_yellow_cab, ride_yellow_cab, pay_driver]
    limousine_sequence  = [call_limousine,  ride_limousine,  pay_driver]
    alternatives = [yellow_cab_sequence, limousine_sequence]
    return alternatives

This makes it abundantly explicit you are returning alternative sequences, although I would probably back off from this point a little and merge the last two lines.  It also makes it easy to see opportunities to create function calls to reduce duplication or better separate abstraction levels, perhaps yellow_cab_sequence() or even ground_transportation_sequence("yellow cab").

You could also add clarity by choosing a name for the function such as travel_alternatives.

On the other hand, if your code truly stays as simple as your example, it's clear enough as-is.  Just keep the technique in mind as the complexity grows of explicitly naming intermediate results or splitting them into functions.


问:
When should I instantiate a variable rather than grabbing it through a method?
This may be tedious, but I would love to know which is a more efficient way of programming. The result may only be slightly better or slightly worse, but I am still interested in which is 'better'.

Say I want to create an array of String objects based on the amount of columns I received from an SQL query and then go ahead and fill this String[] object with values through the use of a for loop. i.e.

```<code>if(rs.next()) {
    String[] topLine = new String[metadata.getColumnCount()];

    for (int i = 0; i < metadata.getColumnCount(); i++) {
        topLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1);
    }
    writeNext(topLine);
}
</code>```

See the use of metadata.getColumnCount() to fetch the amount of columns, only twice. Would it be more appropriate (and faster) to bring this value into it's own variable such that:

int columnCount = metadata.getColumnCount();

and make use of it only twice? Or should I leave the method to call twice?
What n times do I have to call metadata.getColumnCount() before it becomes more efficient to use a local variable. Is there even any change?

Edit: By the way, this isn't my code, I picked it up as an example.

答:
It depends on the intent of your code and avoiding repeating yourself.

If the intent is to rely on the return value of a method to be the same in both instances, assign a single variable. This way, another developer does not have to determine whether or not both uses of the method will always return the same value.

In this example, every developer should know your intent is to apply the same value twice:

```<code>thisCount = metadata.getColumnCount()
DoSomething(thisCount)
DoSomethingElse(thisCount)
</code>```

Now, if there is a new parameter to apply to that method, you only need to change in one place:

```<code>thisCount = metadata.getColumnCount(skipPrimaryKey = true)
</code>```

Body:
It depends on the intent of your code and avoiding repeating yourself.

If the intent is to rely on the return value of a method to be the same in both instances, assign a single variable. This way, another developer does not have to determine whether or not both uses of the method will always return the same value.

In this example, every developer should know your intent is to apply the same value twice:

thisCount = metadata.getColumnCount()
DoSomething(thisCount)
DoSomethingElse(thisCount)

Now, if there is a new parameter to apply to that method, you only need to change in one place:

thisCount = metadata.getColumnCount(skipPrimaryKey = true)


问:
How to contact an open-source organisation (e.g. Apache) about a new project?
I've developed some software within my company and we have agreed that the future of the work is to open source it into the public domain.

Is there an official contact procedure to contact the Apache Software Foundation, apache.org, to propose a new project?

Looking at apache.org I've not been able to find a contact email or enquiry form, so I've resorted to searching lists of people involved in Apache projects and by chance some of them have blogs which may have a contact facility. Seems a bit haphazard way to make an important proposal about a new project, to me.

I'm considering Apache as an Open Source Software (OSS) organisation first because

the project is based on existing Apache libraries and is therefore a practical business problem demonstration applying those libraries, existing on the same open source platform is mutually beneficial - for example library updates may be easier, the project may be easier to find as a related project

Apache Software License appears to be the most suitable license to use, given that the libraries that the project uses use the same and that ASL seems to be more flexible and pragmatic than GPL and possibly attracts more developers including those with commercial motivation

Java-based: the project is Java based and Apache is a large, possibly even the largest, independent non-profit open source supporter of Java.

I would consider other platforms too and if so would want to know how to contact them.

Background Reading

I've been researching how to Open Source, some notable references so far: (but so far not seen how to contact an OSS organisation once you are nearly ready to publish)

http://oreilly.com/catalog/9780596517960/toc.html?CMP=ILC-search_spot1&ATT=intel-property-book  - book describes all the major OSS licenses and industry stories

http://producingoss.com/ - general advice

https://stackoverflow.com/questions/3813613/looking-for-case-studies-of-managing-open-sourcing-code-from-a-company  - my post about how others did it

https://stackoverflow.com/questions/1914104/how-to-license-code-source-but-keep-control-of-it/1914145#1914145  - I got the accepted answer here

答:
You don't need the ASF unless your software competes against expensive, profitable, and  proprietary software. Then the ASF will help you ensure that you and your organization will be able to fight copyright and patent lawsuits resulting from open-sourcing your software.

First you have to figure out intellectual property ownership. For copyright ownership, you & your company can choose between either you, your company, you and your company, or the public domain that owns the copyright. You need to figure out patents. You need to know if your software has any novel ideas that you have patented. You also need to know if your software implements ideas from other patents. You also need to know if there are any novel but unpatented ideas in your software.

Secondly, you have to figure out a license. With public domain, no license is needed, except in jurisdictions which don't recognize public domain. Don't put it in the public domain if there are existing patents that you are unwilling to license for free, or if others have patents against your software.  If your software implements specific patents that you either don't want to release or you don't own, then release your code  under BSD, MIT, or GPLv2. If your software has specific patents which you also own and are willing to license for free to people who take, use, or distribute your software, then use Apache 2.0 or GPLv3. If you want to make your software free for businesses to embed without them giving up their linked proprietary code, then use Apache 2.0, BSD or MIT. If you want the software and its derivatives to always be free to be studied and improved by everybody, use GPLv2 or GPLv3. There are other licenses too, but this covers the common cases.

Thirdly, you have to release your code. I recommend releasing it on github.com. You could also use sourceforge.net, freshmeat.net, and other such places.

Fourthly, you have to build a developer and user community around the code. It needs to get to the point where there are people who are willing to take your code and run with it and without you. The first step is to build a community is to get many people to contribute to the code base, and make sure that each of their names is on the list of copyright owners. That way it will become impossible for a single entity to "take the code proprietary". (It has happened). The second step to building a community is that your code then needs a wiki for users. It may also need a professional support organization so that people can pay for professional support and integration of your application into their systems.

ContentLicense: CC BY-SA 2.5


问:
Who de-duplicates bug tickets?
One of my team mates and I just grabbed separate bug tickets, assigned them separately to ourselves, but the tickets were duplicates!

What is the best way to resolve duplicate tickets? Is this generally done by QA resources? I've worked at a couple places where non-tech people say it interrupts there "flow", but it is something a non-technical person could do in a situation where access to developers is limited (i.e. basically always).

答:
Submit the code changes under one ticket, then resolve the other ticket with a note that says "this is a duplicate, code is under bug# xxx". </p>

<p>This happens all the time. </p>

Title: Who de-duplicates bug tickets?

Body:
Submit the code changes under one ticket, then resolve the other ticket with a note that says "this is a duplicate, code is under bug# xxx".

This happens all the time.


问:
How "close" should a IO class/logic be to a form or thread that controls the IO device?
I am having a difficult time determining where my IO logic should reside within my application. In this application there are multiple IO devices both USB and serial. I currently have the idea to separate the communication with the devices from their control forms and control threads; ie click a button on a form and the device does something or some series of actions leads to a non-UI thread commanding the device.

I have started to work with the serial devices. So I have first wrote a class RS232Comm that wraps the System.IO.Ports.SerialPort class into something nice and thread safe (lock on the Read and Write routines) so that multiple threads can access the device simultaneously.

From here I plan to subclass from the RS232Comm for each serial device, all the subclasses will be singleton objects forcing all communication to go through the singleton.

My current issue is where should the logic about how the device acts and its state lie? Basically, if I want to query a device for its current state, should the state be held in some object and be passed around to each controlling class (possibly an event NewStateObject)? When a controlling class wants to send a command to the device, should it check the input before calling on the singleton, or should the singleton check the input before a write to the serial port?

I feel like it makes more sense for the singleton to check the input and output for errors along with holding the devices state object. This way code is not duplicated in the control classes. But I feel like this will really bloat the singleton classes to hundreds of lines.

Outside of the scope of my project, if I were to only have a 1 to 1 correspondence or IO class to control form/logic, would it make more sense to merge them into one class that "does it all" for that device?

答:
You probably want more intermediate layers.  One to lock or queue at a transactional level, so a device can be dedicated to one caller for multiple sequential requests and responses that must not be interrupted.  And one for the device from an application level.  For example, if you're talking to an LED matrix, this layer's API would be in terms of setting or querying the state of individual pixels.  Depending on your application, you may want additional layers above that to aggregate the common behavior of different devices.

Resist the urge to make your classes too large, especially on hardware-specific code.  You want hardware-specific code to be as small and isolated as possible.


答:
Really, everyone should make a reasonable effort to avoid duplicates, but developers are usually in the best position to do so.  Bugs can be found by many people, but usually are filtered to one developer or a small team responsible for that area of code.  Also, you often need the code to determine if two different symptoms have the same root cause.  All bug trackers can handle duplicates pretty easily.  You shouldn't worry about them popping up occasionally.

On the other hand, if they happen all the time, you're just duplicating testers' effort, and might want to reevaluate how you allocate your testing resources.

Title: Who de-duplicates bug tickets?

Body:
One of my team mates and I just grabbed separate bug tickets, assigned them separately to ourselves, but the tickets were duplicates!

What is the best way to resolve duplicate tickets? Is this generally done by QA resources? I've worked at a couple places where non-tech people say it interrupts there "flow", but it is something a non-technical person could do in a situation where access to developers is limited (i.e. basically always).


答:
See the positive side as well: If the same bug was found twice independently, then it should be easier to reproduce. Both by developers and by customers :-( so it might be higher priority to fix.

You'll often have one person who should prioritise bugs and also removes duplicates, either your manager or a single person with that task. Should be more efficient that way, instead of you picking a bug, and then going through the whole bug list to check for similar ones.

Worst case if you don't avoid duplicates is when you fix the bug, and then the next guy wastes a lot of time to reproduce a bug that is irreproducible because it's gone.

Title: Who de-duplicates bug tickets?


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
When I'm going to performance, the first and last choice is C.

And that’s where you should back up. Now, I cannot, at all, speak for server development. Perhaps there is indeed no compelling reason to prefer C++ over the alternatives.

But generally speaking, the reason to use C++ rather than other languages is indeed performance. The reason for that is that C++ offers a means of abstraction that has, unlike all other languages that I know, no performance overhead at runtime.

This allows writing very efficient code that still has a very high abstraction level.

Consider the usual abstractions: virtual functions, function pointers, and the PIMPL idiom. All of these rely on indirection that is at runtime resolved by pointer arithmetic. In other words, it incurs a performance cost (however small that may be).

C++, on the other hand, offers an indirection mechanism that incurs no (performance) cost: templates. (This advantage is paid for with a (sometimes hugely) increased compile time.)

Consider the example of a generic sort function.

In C, the function qsort takes a function pointer that implements the logic by which elements are ordered relative to one another. Java’s Arrays.sort function comes in several variants; one of them sorts arbitrary objects and requires a Comparator object be passed to it that works much like the function pointer in C’s qsort. But there are several more overloads for the “native” Java types. And each of them has an own copy of the sort method – a horrible code duplication.

Java illustrates a general dichotomy here: either you have code duplication or you incur a runtime overhead.

In C++, the sort function works much like qsort in C, with one small but fundamental difference: the comparator that is passed into the function is a template parameter. That means that its call can be inlined. No indirection is necessary to compare two objects. In a tight loop (as is the case here) this can actually make a substantial difference.

Not surprisingly, the C++ sort function outperforms C’s sort even if the underlying algorithm is the same. This is especially noticeable when the actual comparison logic is cheap.

Now, I am not saying that C++ is a priori more efficient than C (or other languages), nor that it a priori offers a higher abstraction. What it does offer is an abstraction that is very high and incredibly cheap at the same time so that you often don’t need to choose between efficient and reusable code.


问:
What exactly is copyrighted, the text of the code itself, or the design?
I am both the sole developer for a relatively small company and someone who enjoys programming as a hobby. Recently, for one of my personal projects, I started making a framework for a RESTful API and NoSQL integration that I enjoyed programming at home. Near the same time, my work assigned me to begin a project for integrating the disjointed pieces of our backend into something more easily extensible -- using a RESTful API. As I have begun to code both of these projects, I have found that they are, understandably, shaping up in a similar way (similar class hierarchy, interfaces, etc.) However, I have been programming both of them separately, without copying code from one project to another, and only doing work on work time and personal projects in my personal time.

Now, since I have no agreement stating otherwise with my work, I know (or assume) that all code I write there is copyrighted under my workplace, and not under me. And, as I said, I have not taken any code from work and used it in other projects. Also, while some aspects of both projects are similar, others are quite different (the work one does not use NoSQL because too many processes depend on SQL, for example). The similarities seem unavoidable to me, since I am writing both and I have a specific idea of how HTTP requests should be handled, data should be returned, etc.

However, I still worry about the legal implications of all this. While the code itself has not been copied between projects, the solutions have similar points, and I was wondering if only the text of code is copyrightable, or the overall solution. Could these two projects that handle the same problem in similar ways be considered derivative of one another? I.e., could my home project be considered an infringement of work?

If that answer would be yes, the similar solution would be grounds for infringement, it would cause me additional worry, as I believe if I made a RESTful API 10 years from now, it would still look similar, as it is the way I would handle this kind of problem.

Also, I know this is not a site of legal experts and any advice I get is subjective, so I suppose I'm also looking for insight into what is the Right Thing™.

答:
Both code and system design are subject to their own claims of copyright.  And if you're intimately familiar with someone else's work, even a clean-room defense might not hold up in court.

The simple fact is that there is no good easy answer to "how close can my hobby be to my work before I cross the line."  Even if we switch the topic to something slightly easier (for judges to understand), like songwriting, the grey area is still big enough to lose a house in.

Thankfully, you're not working with a team or for a company whose main business is selling your code.  What you have is a potential disagreement about what code is "theirs" and what code is "yours", and that's best solved by taking to your employer and getting some sort of agreement in writing.


答:
The best way is to make the REST api but copy data over in a scheduled job. Sharing databases should always be avoided between solutions. Remember we don't share toothbrushes and connectionstrings.

By exposing the inner workings of the db you lock the cadance of both apps to each other and neither of them can have their inner workings changed to a more appropriate technology in the future. The rest api sidesteps this problem.


答: This should be done during the planning process. When the bugs are initially triaged and prioritized, the person doing that ranking should make sure that there aren't duplicates in the main backlog.</p>

Title: Who de-duplicates bug tickets?


问:
why regex, when using global search and {0,} quantifier, match the end of the string?
I have asked a question here about js, regex, quantifiers and global search. I've understood finally how this works, but, let's take a concrete example and then I`ll write my question.

Based on the same example

```<code>var str = 'ddd';
var r = /d*/g;
console.log(str.match(r))
</code>```

it outputs this array: ["ddd", ""]

I understand that the first item in the array is because it matches the letter d and the last item (that empty string) is because it matches the end of the string, which is nothing, so * makes sense because it matches 0 or more occurrences...

So, my questions are:

Why this is happening?

Why it just have to query the end of the string to finally obtain a
true matching?

In my opinion, the end of the string(ddd) should not be queried; because it's not like my string is containing an empty space at the end 'ddd '. If my string was empty, it was logical to match, but not in this case. My logic here is this:

for every character in the string, do this search/regex (d*) ...so why does it just continue with the end of the string? It should stop on the last charachter of my string, which in this case is d...

答:
match is just a wrapper for exec, per ES5 15.5.4.10, step 8(f)(i):

Let result be the result of calling the [[Call]] internal method of exec with rx as the this value and argument list containing S.

For a global regex, match continuously calls exec until exec retruns a null value.

When we look at exec, we see that each call to exec with a global regex increases the regex object's lastIndex after the match is made:

Let e be r's endIndex value.

If global is true,

Call the [[Put]] internal method of R with arguments "lastIndex", e, and true.

However (here's the real mechanical answer), lastMatch is only reset by exec when it is strictly greater than the length of the string:

Let i be the value of ToInteger(lastIndex).

...

If i < 0 or i > length, then

Call the [[Put]] internal method of R with arguments "lastIndex", 0, and true.

Return null.

(Note i > length, not i >= length.)

Therefore, there will be a final attempt to match the substring whose left bound is lastIndex and whose right bound is the end of the string. Since the final match is done when those positions are identical, a last match attempt is always done on the empty string.

As it happens, d* matches the empty string (since * matches zero and up), so that match is included in the match results.

I cannot offer a surefire explanation why the matching does not stop when lastIndex equal string length. My guess is that this final empty-string check is necessary to match zero-length terminal regexes like /$/ which would never match if considered against a non-zero-length substring.


问:
Difference between '\n' and '\r\n'
Yes yes, I am aware that '\n' writes a newline in UNIX while for Windows there is the two character sequence: '\r\n'. All this is very nice in theory, but my question is why? Why the carriage return character is extra in Windows? If UNIX can do it in \n why does it take Windows two characters to do this?

I am reading David Beazley's Python book and he says:

For example, on Windows, writing the
  character '\n' actually outputs the
  two- character sequence '\r\n' (and
  when reading the file back, '\r\n' is
  translated back into a single '\n'
  character).

Why the extra effort?

I will be honest. I have known the difference for a long time but have never bothered to ask WHY. I hope that is answered today.

Thanks for your time.

答:
What is it with people asking "why can Unix do \n and not Windows"? It's such a strange question.

The OS has almost nothing to do with it. It's more a matter of how apps, libraries, protocols and file formats deal with things. Other than where the OS reads/writes text-based configuration or command line commands, it makes no sense to fault the OS.

Most Windows apps can read both \n and \r\n just fine. They also output \r\n so that everyone's happy. A program doesn't simply "do" either \n or \r\n --  it accepts one, the other, or both, and outputs one, the other, or both.

As a programmer this should really almost never bother you. Practically every language/platform has facilities to write the correct end-line and read most robustly. The only time I've had to deal with the problem was when I wrote an HTTP server -- and it was because a certain browser (hint: the next most popular browser after IE) was doing \n instead of the correct \r\n.

A much more pertinent question is, why do so many modern Unix apps output only \n fully knowing that there are some protocols and programs that don't like it?

Title: Difference between '\n' and '\r\n'


问:
Is it appropriate to pass in a derivative to calculate the error of a Neural Net?
I'm reading a guide for back-propagation of a neural net, and it gives the error function as:

Next work out the error for neuron B. The error is What you want – What you actually get, in other words: ErrorB = OutputB (1-OutputB)(TargetB – OutputB)

But then, underneath that it says:

The “Output(1-Output)” term is necessary in the equation because of the Sigmoid Function – if we were only using a threshold neuron it would just be (Target – Output).

I am in fact using the sigmoid function for my net, but I'd like to write things to be as general as possible. I thought of trying something like this:

```<code>public List<Double> calcError(List<Double> expectedOutput, UnaryOperator<Double> derivative) {
    List<Double> actualOutput = outputLayer.getActivations();

    List<Double> errors = new ArrayList<Double>();

    for (int i = 0; i < actualOutput.size(); i++) {
        errors.add(
            derivative.apply(actualOutput.get(i)) * (expectedOutput.get(i) - actualOutput.get(i))
        );
    }

    return errors;
}
</code>```

Where I allow the caller to pass in the derivative (I think that's what it's called), so the error can be calculated for any activation function.

The problem is, I haven't learned calculus yet, and don't even know if this makes sense. Can I have the derivative passed in like this and still have it give accurate results? Or will the error calculation change depending on activation function/derivative used?

I wasn't sure if this should be put in the Math SE; as it contains code.

答:
Yes you can pass in the derivative, however, it must be the derivative of your activation function. N.b. the network will fail if the derivative isn't actually the derivative of the activation function.

The options you have are:

statically define your activation function and its derivative

statically define a list of activation functions that can be selected, (and the derivative selected automatically)

parametrize the activation function and its derivative as a pair

parametrize the activation function, and then use some method to calculate the derivative automatically (n.b. some neural network libraries use this approach.)

Since rolling your own neural network code really only makes sense as learning exercise, any of the methods are appropriate. A practical library would want to prevent users from easily misconfiguration the network.

N.b. I assume a 'threshold' neuron, mentioned in your quote, refers to a neuron with a rectified linear activation function. The derivative in this case is 1, unless the output is 0, then it is 0. So leaving out the derivative is the same as using it, in that particular case.


问:
Optimizing instant notifications

Scenario

To deliver instant notifications to the client, I'm sending an AJAX request to a PHP page that checks if there are new notifications: if there are, it outputs them, otherwise it sleeps for 10 seconds before trying again, so it has a basic structure similar to the following one.

```<code><?php
$max_attempts = 10000;
for($i=0;$i<=$max_attempts;$i++){
    check_new_notifications(); //checking notifications in an sql database
    if(new_notification){
      echo $notification;
      break;
    }
    else{
      sleep(10);
    }
}
?>
</code>```

What is missing

While this is great for the client, as it doesn't have to send a request every 10 seconds, but just one, I can't find a better way for the server than to check every 10 seconds if there are new notifications.

My question

What solution could I adopt in order to avoid the server to constantly check for new notifications?

答:
You can:

Use polling

However, think about sending a request every 10 seconds.

By using your suggested approach, you are keeping a long connection to the server, which is in turn keeping a busy process/thread.
If this is used only by you, it's fine.
If it's meant to be used by many users, it's a huge waste of resources, since the server will be busy doing nothing 99% of the time.

Use Websockets

This is the thing you need.

Websockets provide a direct and continous TCP communication between the browser and your server. Check out Ratchet, that's a great PHP library for websockets on the server side.

Use an external service

There are services like Pusher which also utilize websockets.
However, you don't need a socket server yourself, but send them an event from your backend. Then their service pushes new data to your browser.

Title: Optimizing instant notifications


问:
Can I avoid more faults if I use different paradigms for the implementation and the specification/tests?
Since it is convenient for the developer, the same paradigm are often used for implementations and specifications, e.g.

for testing (e.g. Java for the implementation and unit tests, Scala for the implementation and property testing)

for model-based testing (e.g. C# for the implementation and specifications using Spec Explorer, or Java for the implementation and specifications using Conformiq)

for verification (e.g. C for some embedded software and specifications in the C-like language Promela for model checking, or Dafny, which integrates implementation and specification).

There even seems to be a trend in this direction.

I always thought using different paradigms would help think on different abstraction levels and more generally in different structures, and that faults could be detected much better that way, when checking the implementation against the tests/specification (similar to using design diversity for fault tolerant systems).

So is it true that different paradigms for the implementation and specification can avoid more faults? Do you have a citable reference?

答:
It's my opinion as a QA person that one doesn't really need different testing paradigims.  Many will disagree with this statement but there's only one method necessary which is simply testing all known edge cases of whatever it is.  The theory is simply Min, Min-1, Min+1, Max, Max-1 and Max+1, Null and or Empty String.  If every one of those edges are tested you have bullet proof code.

People will say nonsense and use fancy terms like end-to-end, black box, white box, grey box, unit test, user acceptance test, unit testing, integration, component and system testing, they'll talk about randomness, statistical approaches.  etc.  All of the above boils down to Edge cases as the method to use.  Edge case tests can be run manually, automated etc.

Finally studies show >70% of all bugs are introduced prior to the developer delivering code to QA.  What does this mean?  It means the best effort for automation is Unit Test!  Now consider this, 90% of all developers say "Unit Testing is not built-in to my schedule"...   Result is that non-bullet-proof code is continually being delivered to QA, but QA can only catch maybe 20-50% of all bugs as they can't see the code usually...

Writing test cases in the language the developers use is good because now the developers can contribute and maintain the Unit Test library.  QA folks should embed with developers and write tests as the code is being created.  Test Stubs can be written just from a specification and make the test almost ready for when code is there.

It is true that developers simply don't have the proper time to develop good Unit Tests given today's fast schedules.


问:
Is it necessary to discuss database changes
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.

答: Don't you have team meetings?  Daily scrums or weekly status get-togethers or anything?  This is the kind of thing I'd expect to be raised in these meetings.  It doesn't sound like the changes are so significant that they require fair warning, but they're presumably important enough to warrant changes to the API, so people should definitely be informed.  Does your team use a wiki?  If so, then maybe create a page that lists database changes and the date they were made.  Alternately, if you're using a bug reporting system, you could create a "change" or "improvement"-class issue and describe the change there.</p>


问:
Are string characters assigned a numerical value in context of how they are assigned in a programming language?
For context I am fairly new to programming after returning back to it after programming a number of years ago... I was reading Bjarne's intro programming with C++ and was wondering if alphabetical string characters are assigned numerical values for the purpose of comparison. For instance in this example from the book Bjarne shows that the strings are compared through analyzing the first letter of the input for the strings. From what I gather the language has been coded to essentially give the string characters a value of what I am assuming is 1-26 corresponding to the standard US alphabet to compare the letters.

For instance:

```<code>int main()
{
    cout << "Please enter two names\n ";
    string first;
    string second;
    cin >> first >> second;
    if (first<second)
        cout << first <<"is alphabetically before"<< second <<'\n ' ;
    return 0;
}
</code>```

答:
```<code>if (first<second)
</code>```

In this case, there is something different involved here, the operator< from std::basic_string.

and was wondering if alphabetical string characters are assigned numerical values for the purpose of comparison.

No, not really. You don't assign a number to a character just for comparison. A computer does not know anything about characters, a computer just knows numbers. What number represents what letter is defined in a charset, ASCII for example is a widely known one. However, a table alone doesn't help the computer either, since it still does not know what a character is and what it should do with it, therefore, at the end, it is the font which makes the number 65 look like a 'A'. A font is just a file with a list of numbers and images (bitmap, vector, ...) and the computer just draws the image which belongs to the number 65, so as I already said, the computer knows nothing about characters, it just draws images.

Body:
if (first<second)

In this case, there is something different involved here, the operator< from std::basic_string.

and was wondering if alphabetical string characters are assigned numerical values for the purpose of comparison.

No, not really. You don't assign a number to a character just for comparison. A computer does not know anything about characters, a computer just knows numbers. What number represents what letter is defined in a charset, ASCII for example is a widely known one. However, a table alone doesn't help the computer either, since it still does not know what a character is and what it should do with it, therefore, at the end, it is the font which makes the number 65 look like a 'A'. A font is just a file with a list of numbers and images (bitmap, vector, ...) and the computer just draws the image which belongs to the number 65, so as I already said, the computer knows nothing about characters, it just draws images.


问:
Should I create thumbnail for uploaded images?
I am working on a Website and trying to decide if I should create separate thumbnail image for each image user uploads. Or just set a smaller width/height when displaying thumbnails.

I am planning to set a limit of image size to 2MB.

Any suggestion?

答: You should create a thumbnail of the image uploaded by the user. It lessen the size of the page and makes it load faster.</p>


问:
Why does C# have both out and ref?
C# has the out and ref keywords. Why are these two required?
Disclaimer: I don't have deep knowledge of C#.

答:
You asked.

C# have out and ref, why these two are required. I don't have depth knowledge of C#. Why out and ref parameters are required?

And the answer is that they aren't REQUIRED, java for instance doesn't have either and VB only has ref (and only requires it in the method declaration).

You can easily write an entire program without using either.

They exist because they are occasionally useful.  Which is why there are two of them and not just one -- because it is useful to make the distinction between 'here is something, modify it if you want' and 'give this thing a new value'.

Other languages have different priorities and so may or may not include these or equivalent.  They may even disagree on whether either is useful, and so may actively decide NOT to implement one or the other.

Title: Why does C# have both out and ref?


问:
Understanding factories
I know there are hundreds of questions about this on here. I've probably read fifty different questions, blog posts and textbooks. The problem is I've gotten about 75 different answers. I have seen all of the following described as some type of factory, and I can't follow the muddled terminology, and get confused on the pros and cons.

```<code>public class PizzaFactory {
  public static Pizza(String city) {
    switch(city) {
      case "Chicago": return new DeepDishPizza();
      case "New York": return new ThinCrustPizza();
    }
  }
}
</code>```

vs

```<code>  public abstract class PizzaFactory {
    public Pizza getPizza();
  }

  public class ChicagoPizzaShop extends PizzaFactory {
    public Pizza getPizza() {
      return new DeepDishPizza();
    }
  }

  public class NewYorkPizzaShop extends PizzaFactory {
    public Pizza getPizza() {
      return new ThinCrustPizza();
    }
  }

public class SomeOtherClass {
  public Pizza getPizza(String city) {
    PizzaFactory pizzaShop;
    switch(city) {
      case "Chicago": pizzaShop = new ChicagoPizzaShop();
        break;
      case "New York" : pizzaShop = new NewYorkPizzaShop();
        break;
    return pizzaShop.getPizza();
    }
  }
}
</code>```

vs

```<code>public class PizzaFactoryFactory {
  public abstract class PizzaFactory {
    public Pizza getPizza();
  }

  public class ChicagoPizzaShop extends PizzaFactory {
    public Pizza getPizza() {
      return new DeepDishPizza();
    }
  }

  public class NewYorkPizzaShop extends PizzaFactory {
    public Pizza getPizza() {
      return new ThinCrustPizza();
    }
  }

  public Pizza getPizza(String city) {
    switch (city) {
      case "Chicago": return new ChicagoPizzaShop().getPizza();
      case "New York": return new NewYorkPizzaShop().getPizza();
    }
  }
}
</code>```

vs

```<code>public abstract class PizzaFactory {
    public Pizza getPizza();
  }

  public class ChicagoPizzaShop extends PizzaFactory {
    public Pizza getPizza() {
      return new DeepDishPizza();
    }
  }

  public class NewYorkPizzaShop extends PizzaFactory {
    public Pizza getPizza() {
      return new ThinCrustPizza();
    }
  }
}

public abstract Customer {
  public Pizza orderPizza();
}

public ChicagoCustomer extends Customer {
  public Pizza orderPizza() {
    return new ChicagoPizzaShop.getPizza();
  }
}

public NewYorkCustomer extends Customer {
  public Pizza orderPizza() {
    return new NewYorkPizzaShop.getPizza();
  }
}
// How does one choose which Customer to use? *Another* factory?
</code>```

There are probably others I'm not thinking of right now. Which, if any, of these is an Abstract Factory pattern? The Factory Method pattern? Some other thing? More concretely, I have eight different subclasses of an abstract class, and I need to return one of those based on a user selection which I can represent either as a string, an int, or an enum. How to best go about it?

答:
Abstract factory only makes sense, when code that creates the factory is in completely different part of your application than the code that actually uses your factory. None of your examples actually represent this. Quite often, the factory is downstream the dependency between modules. So the code that consumes the created abstraction cannot possibly have dependency on the concrete implementations.

Following illustration shows where abstract factory makes sense.

This design has few good properties. When modules for concrete implementations(the ChicagoStores and NewYorkStores modules) change, it doesn't require recompilation of either other modules or the one that actually uses the implementations (People). Second, it allows you to add new concrete implementation (maybe WashingtonStores), after which you only need to change the "application" module, which binds everything together. The "composer" object is one that binds everything together. This would often be some kind of Inversion of Control framework. Also note, that the one that uses the factory to create instance needs multiple of those instances. If it only wanted single instance, then the composer can just pass in those instances. There would be no need to complicate the design with abstract factories.

But you might be saying : "Isn't this too complex?" Yes, that is correct. But if you have requirements that would force this kind of dependency structure, this kind of design is unavoidable. You need to weight the advantages you gain by separating the dependencies against complicated design.

One note for the end : If you are just learning design patterns, my personal opinion would be to simply ignore the (abstract) factory pattern. It's use is highly situational and it is more often abused then used properly. As many seem to agree with me and some more.

Also note, that what I described above is a design pattern called "Abstract Factory". There is also a pattern called "Factory" which IMO is just a method that creates objects. Your confusion probably stems from the fact that those two are often mixed together.

Title: Understanding factories


问:
What licence should I choose for my project?
I originally thought of creative commons when while reading a book about wordpress (professional wordpress), I learned that I should also specify that the product is provided

... WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE

and they recommend GNU GPL.  How do I write a license or select 1?

btw, what does MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE mean actually? Isn't without warranty enough?

答:
Personally your best bet to get a true answer to this question would be to talk with a Legal Professional as they are going to know the specifics.

However, what I remember when i was talking with my lawyer about setting up our code license agreements is that the clause you are talking about basically protects you from cases where you say "this code does X, Y, Z", that is an implied warranty on "fitness for a particular purpose", that clause prevents you have having any issues if it doesn't do X, Y, and Z.


答:
C++ is about as fast as C (some things are faster, some slower), and it offers better abstractions and organization.  Classes work similarly to primitive types, allowing large amounts of code to be used without being held in mind.  Operator overloading and templates make it possible to write code that functions better if data representations change.  Exceptions can allow easier error-handling.  The compiler can be used to check more stuff at compile-time.

The price you pay for this is a fairly nasty learning curve, and it's easier to make subtle mistakes in it than most other languages I'm familiar with.

So, I can't tell whether it would be worthwhile for you to learn it for what you're doing now.  You can certainly get by with combinations of Python or Perl and C, but C++ offers both abstraction and performance in one hard-to-get-used-to package.

Title: Is there any reason to use C++ instead of C, Perl, Python, etc.?

Body:
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?


答:
I think what you want is some level of formalism, see Formal Methods. This is the only guaranteed way to get less fault by using different paradigms because just using something different also has the potential to give different faults (even fixes produce bugs).

Doing implementation in level closer to math will give the ability to have some level of mathematical proof, which means you will have no fault and potentially eliminate need for testing.

This link From HOL to Haskell and Software Foundations should illustrate ideas of using developing specification in theorem prover then translate it into programming language. One article talks about using Isabelle/HOL and haskell, the other is about using Coq, which then you can translate into scala using some tool.

Because it takes more time to do it formally, only small amount of code are developed this way.

Title: Can I avoid more faults if I use different paradigms for the implementation and the specification/tests?

Body:
Since it is convenient for the developer, the same paradigm are often used for implementations and specifications, e.g.

for testing (e.g. Java for the implementation and unit tests, Scala for the implementation and property testing)

for model-based testing (e.g. C# for the implementation and specifications using Spec Explorer, or Java for the implementation and specifications using Conformiq)

for verification (e.g. C for some embedded software and specifications in the C-like language Promela for model checking, or Dafny, which integrates implementation and specification).

There even seems to be a trend in this direction.

I always thought using different paradigms would help think on different abstraction levels and more generally in different structures, and that faults could be detected much better that way, when checking the implementation against the tests/specification (similar to using design diversity for fault tolerant systems).

So is it true that different paradigms for the implementation and specification can avoid more faults? Do you have a citable reference?


问:
Shuffle/Randomize a collection without knowing the number of items?
Let's say I have a sequence of items of unknown length, n. I want to randomize the order of this sequence without having to go through the entire sequence. Are there any algorithms that can do this?

Example:

I have 10 items in my sequence: A B C D E F G H I J (though I don't know that I have 10). At the end of my randomization it would have ended up as E G F B A I C D J H.

If I only wanted to know the first 3 random elements, I would get E G F, and since G is the furthest element in the original sequence, I would never have to read the sequence past G.

My algorithm would, somehow, look at A and realize that it randomly belongs past the first 3 requested elements, it would then look at B and realize the same, ..., it would look at E and realize that it needs to randomly be the first element so it adds it to a return buffer as element 1, then F randomly should be the third element, so it adds it to a return buffer as element 3, then it hits G and adds that to the return buffer as element 2 and it completes. It never even looks at where H, I, or J should go.

答:
Here is one such scheme. It is only a brief idea, I did not check it carefully for potential fallacies.

Before starting, we perform the following configuration:

For every natural number N (1, 2, 3, ...), choose a bit shuffling function for N bits.

Procedure for converting query integer I to response integer J

Given a query integer I, convert it into binary representation.

If the query integer I is zero or one, there is nothing to do; return it as J.

This is a limitation of this scheme.

Find its highest-bit-set (the most significant bit that is a "one"). Choose N so that there are N binary digits below the highest-bit-set.

Look up the bit shuffling function for N as configured above.

Apply this bit shuffling function to the lowest N bits of the number. Remember that the highest-bit-set is not being shuffled; it must keep its value of "one".

The new number (where the highest-bit-set is kept but the lower bits had been shuffled) is returned as response integer J.

Analysis.

Let's say the query integer I can be represented in 6 binary digits. (example: "100101"). The maximum possible response integer J given I is also 6 binary digits (example: "111111"). Therefore, the upper bound for J is pow(2, ceil(log2(I + 1))) - 1.

Refinement prompted by @amon's comment.

The N-bit bitwise-permutation function can be replaced by a general 2**N integer permutation function (one-to-one integer mapping). This way, when the N-bits are all zero, it will not be stuck with an all-zero output due to the bitwise permutation.

There are lots of shortcomings in this scheme. The purpose of this answer is to encourage more discussions and possibly more practical answers.


问:
Immutable class with behavior
I've just finished Effective Java and I loved it. I'm trying to refactor one of my programs to take advantage of what I've learned, and I have a lot of questions regarding immutability.

My program is largely built around a model class representing a reminder, which is stored in a content provider. This article suggests that, since it represents data held in the content provider, I could create an immutable class that simply calls through to the content provider. But for all I know this author is completely wrong and this is a terrible idea. It sounds to me like it would be very non-performant to be calling the content provider all the time, which then queries a sqlite database, and I'm disinclined to follow this pattern.

My other question regards several small classes I have where none of their members change after they are created, but they make asynchronous calls to system services, and return the response along an interface. Can a class like that ever be immutable? The class itself is stateless and never changes once created, but it calls other classes that are closely tied to device status.

答:
Please don't follow the advice in that article.

The author is correct to advocate immutable objects. But to get the advantages of immutable objects, the object should be transitively immutable. That is, it should only keep references to other transitively immutable objects. It shouldn't be referencing data providers, and it certainly shouldn't be keeping its state on some other object in some misbegotten attempt to pretend to be immutable when it is not.

Immutable objects are nice primarily because they are easy to reason about. I know that once created they don't change. If its the same object as I had before, I know that nothing is different. I know that I can pass it other functions and not worry about them changing it.

The proposed solution in that article makes the supposedly immutable object act like a mutable object. Sure, it might not actually modify its own fields, but it still acting like a mutable object. I don't really care how it is implemented internally, its a mutable for all intents and purposes.

So, yes, from my perspective that site is full of terrible ideas. It wouldn't be performant, and it wouldn't have almost any of the advantages of immutable objects. All you would be doing is sacrificing simplicity and efficiency for misbegotten understanding of immutability.

My other question regards several small classes I have where none of
  their members change after they are created, but they make
  asynchronous calls to system services, and return the response along
  an interface. Can a class like that ever be immutable? The class
  itself is stateless and never changes once created, but it calls other
  classes that are closely tied to device status.

I would not call such a class immutable. Yes, its immutable in some sense because it doesn't change. But that is an implementation detail. It doesn't act like an immutable object. When I'm using that object elsewhere, I care about the interface, not the implementation.

Title: Immutable class with behavior


问:
Best pattern for manager class that handles syncing objects between client and server
I am writing a client which has support of 'offline mode'.  When offline records can be stored locally.

When we go online we want to be able to synchronize these records with the remote API.

I want to be able to keep track of some state like the progress of the sync, whether we're syncing or not and other things like that.

I'm considering creating a singleton manager class that can store this state but I feel like there is a better way to do this.  I want to stay away from singletons as much as possible due to their global nature.

答:
Singletons exist in programming. A lot. People don't think about this often, yet they are there. While there is some merit to avoiding "global" values, it is detrimental to avoid global designs when they are warranted.

With a singleton design, you can make sure that multiple writes to the same record won't clobber data, that reads and writes to the queue don't leave it in an unpredictable state because of non-atomic updates, and so you can answer questions like "how many records are left?" in an easy and predictable manner.

True, there are other solutions to all these problems. For example, you could create pools that hold records to sync, and put atomic locks on those methods, and so on. You'll still need a place to keep track of these pools to answer questions like above, so there's little benefit in that case.

If you had a ton of traffic on the client, it might make sense to go with a parallel/concurrent design. I doubt that's the case, but there's compelling reasons you'd want to spilt the load, perhaps so you could sync with more threads or service many records at once.

Internally, the singleton might utilize threads or other techniques, but outside calls into the manager shouldn't be as concerned with implementation details, so a singleton will also decouple your others classes a bit from the sync process.


问:
Availability on updating, migration, etc
When you want to update, migrate or deploy-new-version of a large and/or critical system, absolutely, you can't shutdown the system and do your job, then start it!!! I want to know what's the requirements of designing a system that can be available during update,...? what's the compatibility issues? How clients should be aware of changes?

For example: In updating a new refactored version of a large system that provides services to embedded softwares, the updating all of clients take some months, then how the development team should deal with this sitution?

答:
It hugely depends on the type of system, but here are some things to consider.

Hot patching allows your system to continue running while you deploy new features and upgrades.  For this to work, you generally need to be working in a functional programming language, since such languages do not hold mutable state variables.  Erlang is such a language; hot code deployment is fully supported in Erlang.  Lisp has had this feature for ages.  Java also supports hot code replacement, but not C#.

Some web application servers like Microsoft Internet Information Server (IIS) and Apache Tomcat have a hot deploy option.  In some cases, code is dynamically compiled at execution time. In the case of DLL's, IIS does a shadow copy of the deployed DLL, waits for an opportune time, recycles the app domain, and swaps in the new DLL.  The user merely sees a short delay in his web browser while the app domain restarts.

Mechanisms like the Managed Extensibility Framework and Activator.CreateInstance() (techniques specific to the .NET ecosystem) allow you to change out modules and plugins at runtime.

Further Reading

Dynamic Software Updating


问:
Do Ruby (and other dynamic language) programmers use IoC / Dependency Injection?
I'm primarily an ASP.NET developer and the single thing i've been introduced to in recent years that has had the most dramatic impact on the quality of the code I write has learning how to use IoC containers to manage dependencies between different layers of the application efficiently.

I've recently made it my hobby to learn Ruby (and Rails) for personal projects, and I love the language so far. However, one of the things i've noticed from the various tutorials and references i've been using, has been that there has been no mention yet of using IoC. This is in stark contrast to .NET where it is (and where it isn't, should be) drummed into developers at an early stage.

I appreciate that one reason why dependency injection may not be necessary in Ruby, is that everything in a class is public and virtual so open to modification so it's not really needed in order to write good unit tests. But there are of course many other benefits to using IoC containers such as the decoupling options this brings, managing object creation and lifetime etc.

Is dependency injection used in Ruby? If not, why is this not an issue?

答:
Inversion of Control is still a concept that applies well. You don't need to be doing dependency injection to apply IoC, although in .NET they do tend to go together often.

The big drive behind dependency injection in .NET is avoiding depending on concrete implementations. In Ruby, as you mentioned, things are much more open and you can replace implementation of a class at run time, so there's much less need to create "interfaces" and explicitly inject dependencies.

It can be argued that interfaces and IoC/DI aren't strictly necessary in .NET either (even when it comes to testing -- there are mocking frameworks that will allow you to eliminate the need to interface everything under the sun), but it's more pronounced in Ruby.


问:
Is it safe to only use intval to sanitize user input for a database select?
Is it safe to only use intval to sanitize the user input for a database select, as in the following example?</p>

```<code>$id = intval($_GET['id']);

$query = "SELECT * FROM table WHERE id='$id'";
</code>```

答: First, check if $id is a valid numeric value ( using is_numeric ) then finally cast the $id to type ( int ).</p>


问:
Pattern for "Assembling" result from multiple datasources
I'm creating a server in Java (although this question is language agnostic) that will do the following:

Pull a set of "leads" from a database every 10 minutes

For all leads with a certain marker, use a different database to get additional information

For every lead that actually has relevant data in database #2, combine the data from two datasources and pass it to a few Machine Learning (ML) algorithms

Store the results of the ML algorithms in Database #1

I'm confused as to the best way to organize it. After looking at this relevant question, I think the Repository pattern may be part of the solution but I don't think it satisfies all requirements. Particularly, I think each "lead" should be processed in its own thread, but I'd like to use a pattern that would enable me to make use of cached thread pools.

Although there may be specific Java classes or libraries that may be of use, I marked the question language agnostic as I feel the question will best be answered by suggesting pattern(s). I'll retag accordingly if the community disagrees.

答:
Repository can be useful to deal with data access to the different databases.

As for the rest, depending on what you pass to the ML algorithms you might want to use a Facade that hides away the details of accessing the different database and determining if the information there is relevant. You would pass a lead to a facade class, that class would determine what markers there are and pass the lead off to different classes depending on the markers. These classes in turn add data from the other databases.

In the end, your 'base' flow would be: get a lead, 'enhance' the lead with relevant data, pass off lead to ML and store result.


问:
Do microservices scale down?
I've been reading up on microservices architecture, which gained a lot of recognition in recent years. As a big fan of UNIX philosophy, I find it very clean and sensible. However, exisiting publications as well as libraries/frameworks seem to treat microservices as solution to "big data", "web scale" and similar buzzword problems. When talking about scaling an app, the context is always scaling it up to work on multiple servers in distributed, networked environment.

Does it make sense to use microservices on a much lesser scale? I.e. I want to write a hobbyist application deployed on single VPS instance and used in total by few hundred people at most. Architectural benefits of microservices are obviously retained, but what about performance when compared to traditional, threading servers and frameworks?

答: Microservices incur a penalty in both performance and complexity that is usually traded off in order to be able to scale out more easily (adding more instances of various microservices independently). If you're building a small system, avoid the runtime and cognitive overhead by just building out your app as a "monolith". (a terrible word that people now unfortunately attach a negative connotation to)</p>

Title: Do microservices scale down?


问:
Is it common to use arrays everywhere with PHP?
I'm a fresh grad, and I just started workingin real world projects. I'm basically using PHP most of the time. I just figured out that most of the solutions I came out with for most of the problems, is involving using an array in somehow. What Am I doing wrong here? How could I unlearn this and always think of something else? Or is it the fault of the language?</p>

答:
Depending on the problem, if it includes data or collections it is usual that you may come up with a solution using arrays.
But if you're thinking that it's the programming language's fault, then think again; problem is the way of how you think solutions.</p>


答:
Using microservices in your context may still be useful in your context if the system is large enough so that it makes sense to:

Make the parts of the system be maintained by different developers or even teams,

Or write the different parts using different languages; for instance, you can have a service written in Python and hosted on a Linux VM interacting with a service written in ASP.NET MVC and hosted on Microsoft Azure servers.

Or be able to maintain or even completely replace a part of the system without affecting at all the other parts.

If the system is not large enough, using microservices may not be that useful. Probably, you would be better with a single service, while putting proper abstractions and interfaces to make it easier to maintsin the application later.

Title: Do microservices scale down?

Body:
I've been reading up on microservices architecture, which gained a lot of recognition in recent years. As a big fan of UNIX philosophy, I find it very clean and sensible. However, exisiting publications as well as libraries/frameworks seem to treat microservices as solution to "big data", "web scale" and similar buzzword problems. When talking about scaling an app, the context is always scaling it up to work on multiple servers in distributed, networked environment.

Does it make sense to use microservices on a much lesser scale? I.e. I want to write a hobbyist application deployed on single VPS instance and used in total by few hundred people at most. Architectural benefits of microservices are obviously retained, but what about performance when compared to traditional, threading servers and frameworks?


问:
Using PHP without mixing presentation logic
I'm conceptually designing a website / application and trying to come up with the correct separation of concerns.

The basic technologies I'm settling on are: MySQL, PHP (Laravel), HTML/JS (jQuery).
It's been a few years since I've written PHP, and since then I've gotten very used to MVC and MVVM approaches.

I would like to stay away from using PHP as a templating engine. My reason for this is that I want to keep presentation solely to JS and HTML code, with none of it mixed in with server-side code.
To achieve this, my thinking is to stick with using PHP to create services, then call those services from JS / AJAX on the pages.

As far as I can tell, this approach would allow me to keep PHP to handling data and the client will handle all of the logic and presentation.

My main concern is that I am having a difficult time finding any resources outlining similar approaches used in the real world.
Almost every single instance I can find of PHP being used has it implemented as a templating engine, dropping HTML and data onto pages when they're being sent from the server.

Are there any obvious flaws in my approach that I've missed?

I'm entirely open to changing my thinking on this one - no code has been written yet so the architecture is mine to play with :)

Thanks!

答: Your approach is far different from that of most PHP applications does, obviously a template engine binds some logic in views, most programmers prefer writing this logic in PHP itself. Limiting PHP to create services/ API s to only manipulate Data is a good idea, indeed. You may consider http://backbonejs.org/. I believe you could use it to write all presentation logic, that further connects with the services you are gonna develop in PHP. You would enjoy going this way. It helps you clearly identifying Business logic with Presentation logic and makes the software more readable and maintainable for future up-gradations.</p>


问:
Controller technique with request data in session
I am trying to find out the best possible way to save the POST data in session and making it available in different page requests.

For example at website's homepage I have a Search form with different fields. On Submitting the form a product's page is displayed containing a list of all product matching the search criteria.

On selecting a product product's detail page is loaded. and on Detail page we have a back link to the Product's list page. on clicking the link, I am interested that the controller should load only the product depending on the search parameters. This means that maybe the search criteria will be saved in Session and on coming back to List or Search page these parameters will be loaded again from Session.

Is there any Best Practices or Design pattern available to to and load the Search Form fields?

答:
Lets assume index.php as your home page.

I can assume that your controller might work using a action parameter appended to the URL or based on request parameter set.

index.php?search would takes the controller to execute search logic and there you get all post data of search criteria. and loads products based on a query mapped with data keywords entered by user.

There you show each product mapping the criteria.

and for details, you might be using, index.php?productDetail=product_id (or) some thing.

Here you can simple modification by adding all the search fields data to

index.php?productDetails=product_id&search1=val1&search2=val2&...

Then append all these get parameters to the Back Link of Product details page, this way you can get all search data to the product list page back.

Importantly make small changes in your controller to search based on Get parameters as well, i.e., like if you are using $_POST to read search form data change it to $_GET, so that the same search result page will be loaded even if the user clicked back from the product detail page.


问:
PHP MVC concept large controller
I have custom MVC framework in PHP and my controller file has about 5000 lines.

The question is, is it a big concept flaw?

It is structured code with kiss method and quite maintainable.

Are there any rules that specify how large the controller should be?

And offcourse could it have some bad influence on web performance?

答:
While there are no hard rules about the size of a controller, 5000 lines is clearly beyond any reasonable size for a hand-coded class. Chances are this class is violating the Single Responsibility Principle (SRP) and therefore is flawed. You most likely have several methods in there that can logically be grouped together. See if you can't extract methods off into separate controllers: you are very likely to end up with a larger number of controllers with fewer lines of code per controller and well-defined responsibilities. Or package up code into separate classes that your controller can call into.

I can't see where performance would be a problem, and I doubt performance of your code would be anything but the last reason you would want to split up a 5000 line class...

Title: PHP MVC concept large controller


答:
I'd say a solid no. Microservices more or less inherently need a 24/7 devops support team; an alternative name for the approach is monitoring-driven-development. That's the thing that takes a novel error case and intelligently limits the scope of the failure to something that 99.99% of customers will never be aware of.

A hobbyist project won't have that, and also won't have the millions of customers that mean 1% of them will do more and better testing in an hour than a building-full of QA teams could do in a week. And they certainly won't have a vast system that would be less bad as several huge ones, many large ones, and a few dozen small ones.

Without any of those, microservices are just a way to take a small system and turn it into several slightly larger, slower and buggier systems.

No-one implementing unix cat ever said:

ok, I need to read input and then write output. So I need two main processes, and then another that connects the two together...

Title: Do microservices scale down?


问:
How to promote code review as an employee?
I have just graduated not long ago and started to work in a startup company for almost a year. I have introduced git to my current company and they are now happy to use it for version control. I feel that my boss and the company is open to new stuff.

Recently I have heard about the idea of code review and want to give it a try in our company. However, unlike git, I have never done code review. Also, it adds extra work load and I am not sure if everybody is open to accept comment / complain during code review. Is there any suggestion on promoting code review?

答:
First you must be sure that everybody is ready to accept his code to be reviewed (actually this can be the hardest step) and can leave his ego aside.

Then you can promote the virtues of code reviews to your colleagues (over the lunch, etc.) to make them understand what are the benefits of code reviews. I suggest you reading this article.

When you feel they are mind-ready for code reviews, you can install a tool and start reviewing your colleagues code (alone, but better with them) and assign them issues. They will receive mails and will eventually complete the issue and getting familiar with the system and start reviewing !


问:
Using sourcetree/bitbucket how can I manage multiple projects using a common codebase?
I have made a few libraries that different projects use.

When I make changes to projects, I sometimes make changes to the codebase, and I want to be able to manage this all through sourcetree.

So, for example, I have a project with global.js and project1.js.
I also have another project with global.js and project2.js.

I never want to merge project2.js with project1 and vice-versa, however, any changes I make to global.js in either project, I want to be able to merge.

As this is work for separate companies, it is important that the code is never brought across to the wrong project.

This is obviously quite a simple example, however, in reality there are many files to deal with.

For these particular projects, the changes to each individual project is stored in subfolders to keep the project specific code separate to the global code.

eg:
codebase/includes/global.js etc..

codebase/modules/project1
or
codebase/modules/project2

What is the recommended way of managing this using sourcetree/bitbucket?

答:
Use a separate repository for your common codebase

The easiest way would be to manage the common code apart, in a separate repository.

Then you can use git submodules or git subtree to import your common code into the other repository.

Use packages instead of GIT merging to import the common codebase

Better still, Esben Skov Pedersen's answer gives a preview about package management. I personnally know well Maven in the Java world. In JavaScript, I think the two most widespread are Bower and NPM.

Choose the right granularity

The granularity is to be defined according to your needs. For instance, if your projects 1 and 2 have a large common codebase and project 3 shares only a subset of this common codebase, you could cut it out this way:

common codebase imports minimal subset

project 1 imports common codebase

project 2 imports common codebase

project 3 imports minimal subset

Adapt to your own needs.


问:
Coding guidelines for seamless merging
I am looking for coding guidelines developers should follow while writing C#/ASPX/SQL code, so that merging into other branches is smooth if not seamless.</p>

答:
Always put the code for if, while, etc in “{}” with the brackets on
  their own line.

A bad merge is then much more likely to lead to code that will not compile.

Do not have lot of boiler place comments, for example.

```<code>//-----
// Arther AXB
// Date method was added::
//-----
</code>```

Often the merge will decide the 2 methods are the same due to the comments and merge the updates date, when you had added new method.

Always put a "," on the last item in an emun

Then when two people add a value the merge often works.

Title: Coding guidelines for seamless merging

Body:
Always put the code for if, while, etc in “{}” with the brackets on
  their own line.

A bad merge is then much more likely to lead to code that will not compile.

Do not have lot of boiler place comments, for example.

//-----
// Arther AXB
// Date method was added::
//-----

Often the merge will decide the 2 methods are the same due to the comments and merge the updates date, when you had added new method.

Always put a "," on the last item in an emun

Then when two people add a value the merge often works.


答:
Dependency Injection is less important in dynamic languages because they are dynamic- you can change your code whenever you want so you don't have to plan ahead for potentially changing dependencies. There are easier ways to achieve IoC in a language like Ruby.

Fabio Kung on this topic which refers to Jamis Buck on the same thing - those give a bit of depth.

Title: Do Ruby (and other dynamic language) programmers use IoC / Dependency Injection?

Body:
I'm primarily an ASP.NET developer and the single thing i've been introduced to in recent years that has had the most dramatic impact on the quality of the code I write has learning how to use IoC containers to manage dependencies between different layers of the application efficiently.

I've recently made it my hobby to learn Ruby (and Rails) for personal projects, and I love the language so far. However, one of the things i've noticed from the various tutorials and references i've been using, has been that there has been no mention yet of using IoC. This is in stark contrast to .NET where it is (and where it isn't, should be) drummed into developers at an early stage.

I appreciate that one reason why dependency injection may not be necessary in Ruby, is that everything in a class is public and virtual so open to modification so it's not really needed in order to write good unit tests. But there are of course many other benefits to using IoC containers such as the decoupling options this brings, managing object creation and lifetime etc.

Is dependency injection used in Ruby? If not, why is this not an issue?


问:
Database design: manage permissions on multiple applications resources
Overview

A central web application to supports other web applications(A) for user and its role/permission management. Applications (A) call the central application via API to get the user roles/permissions.

1) Application(A) can have resources.

2) Resources can have permissions.

3) User can have access to resource/permissions.

Admin should able to create resources for an application, Permissions for that resource, assign access of a resource/permission to a user and the response should be something like this.

```<code>User
 - Resource
    - Permissions
 - Resource
    - Permissions
</code>```

Scenario

Admin for an application(A) wants to create resources say R1, R2 but not necessarily any permissions under them because it is sufficient for him if he get the response like this.

```<code> User
     - R1
     - R2
</code>```

Approach 1

Create these tables
1) Application

2) Resource (FK as appID)

3) Permissions(FK as resourceID)

4) User_Permissions(FK as permissionID)

In this case since there are no permissions for a resource so User_Permission table will be empty. But then admin wants to give access to the resources, so either the system creates a default permission OR admin has to create a default permission whenever he created a resource. So we enter the default permissions in the User_Permissions table and we can eventually find out the corresponding resources and return the below response.

User
     - R1
       - Default Permission
     - R2
       - Default Permission

Approach 2

Create these tables
1) Application

2) Resource (FK as appID)

3) Permissions(FK as resourceID)

4) User_Resources(FK as resourceID)

5) User_Permissions(FK as userResourceID)

In this case we have the extra table User_Resources which specifies the resources to which the user has access and then permissions on that resource.

Need you suggestion which approach to prefer.

答:
I think requirement #3: "Users can have access to resources/permissions" is a little vague. Until you're more specific in your requirements, it cannot be answered. Here is how you can look at your two scenarios and make a decision.
In scenario #1 a user can only have access to a resource by having a permission that is linked to a specific resource. That is not the same as having independent access.

If there is some performance reason, you want to separately track the user's resources & permissions, you may find accessing one table performs better than having to constantly join Permissions to the Resource table.

Also, I think you need an additional foreign key in the User_ tables for UserID. They are your typical Many-to-Many link tables.


问:
Entity Framework 6 and Stored Procedures
I'm new to Entity Framework, and currently developing an MVC 5 application with Code-First Entity Framework 6.1.2.

I need to write custom reports. Instead of writing complex linq, I can write a couple quick Stored Proc's and write the results to CSV. Can I call these procs with EF? or would I just be better off using ADO.NET?

I know I can do:

```<code>var data = db.Database.SqlQuery<ReportDetailed>("sp_rpt_report @reportType @endDate, @startDate", parameters).ToList<ReportDetailed>();
</code>```

But I would need to build a rather large model for each report result, and that seems like a lot of work for little reward and wrong.

答:
I think Robert Harvey's comment is very good advice. In the long-run, I think you'll wish you did it in Linq.

Here's why:

Changes in Entity Framework for your data objects will be easier to make changes to the report data sets. The stored procedures will probably just fail. You'll need to maintain them separately. There will be no shared logic that can be reused.

You'll learn Linq much better.

I do think you can take a few steps to accomplish this. It sounds like you're better at this in sql and you may have some pressure to get this done. So go ahead and create a stored procedure that works. You'll understand the requirements better. Then you can get to work on refactoring it in linq. You'll have a result set from the stored procedure that you can use to test/compare your Linq results. You'll feel more comfortable knowing you've been able to accomplish the same thing in the new language.

This way you can get your app into production in parallel with becoming a better Linq programmer. The next programmer that has to maintain this app will appreciate it. And don't forget, that new programmer could be you in a year or so.


问:
Sacrifice server validation in pos of performance with Rich Client validation?
I recently started to work in a java enterprise project (~200 people) that uses a SWT rich client.
In many cases I've found business rules not being validated in server side, because the widgets that trigger such actions are disabled in the SWT client using the business rules.

This is a well known question of validation in server, client or server+client and I'm not pointing to the same issue. Also, I'm in favor of validation in server+client.

The need of validation in the client is obvious because allows a more responsive application for the end user and less requests for the server.

The need of validation in the server is obvious with a web client, where one can play with the html and javascript for avoid the client-side validations and send incorrect data to the server.

But, with a SWT client this is not that simple (could be achieved with a package sniffer like Wireshark?) so one could argue that validate in the server would have an innecesary cost in performance. Always in a scenario where there is only one point of access to the application and it's the SWT client.

If the project had begun yesterday I would fight for server+client validation, but in a project with 8 years of history this could be difficult because we would have to convince end-users and analysts for the advantages of the performance penalty.

So, every time I find one of this validation holes I struggle between add the server side validation or let it go, thinking "the client will catch it and this will never happen" and continue with a more priority task.

This project has been productive four years, so it's a viable practice, but from the point of view of design, is correct this approach? Aniway I think this is a consequence and not something deliberately sought.

Could be taken it like a political decision with knowledge of the consequences or the software world will say NO to this practice?

答:
As you pointed out, it's best to do validation both client side and server side.  You want the client side validation so you can quickly give feedback to the user, and you want it server side because often the people who write the server code aren't the same people who write the client code and it's necessary to check assumptions.

However, the code has been running in production for 4 years without obvious problems.  If the missing server validations were added (probably at considerable expense), the code would still run without obvious problems.

Unfortunately, the ROI on fixing this is likely almost zero.

If you add the server validation code in now, you have to consider the cost of ensuring it is doing exactly the same checks as the client side code (including any bugs in the client code).

The big value in server side checks in this scenario (rich client) is during development -- not after the system is in production, stable, and relatively bugless.


问:
Upgrading from XP Pro to Win 7, anything I should worry about?
I do mainly .NET work so I assume that the framework is all fine and that.  But have there been reports of various tools like .NET Reflector and the like not working properly with Win 7?  This is a company-wide thing so there isn't much I can do about it, but once everything is reinstalled I'm hoping to not find anything shocking.

Cheers.

答:
Three different places, three flavors of Windows 7. All web development.

Computer one was a Core i5 with 4 gigs ram, windows 7 professional. All work development was actually done in a virtual machine running VS2005 which was transfered over to the machine and added under XP mode. With the full screen display and ability to drag and drop across desktops it was actually very difficult to tell when you went from one OS to the other. No issues here.

Computer two was a 64bit version dual core machine with 7 professional. Ran on the bare metal with VS2008. Only issue I had in the beginning was running asp.net web applications off of IIS7 when the application was not in the WWWroot folder. This really just needs a little configuration on permissions. Everything else worked like a charm.

Last computer, 64bit AMD chip with 3gigs ram, 7 Enterprise. Again VS2008 and again just the issue with IIS7.

The second two computers all had a version of source control (SVN or SourceSafe), SQL Express and other utilities. (Downloaded most item with the Microsoft Web Platform Installer).

64bit/multi-core cpu's and lots of ram make a huge difference in feel. I down grade the UAC security of 7 so that it doesn't bug me about everything and the user has to be the admin of the machine (really no different from other OS's).

Good luck and hope this helps you some.


答:
I'd say no, its not.  The reason is that anyone can sniff the network traffic to see what your calls are, and if you're not validating, you're opening up security risks as well as data corruption risks.

The performance rationalization doesn't hold water; are there performance issues on the client running the rules?  If not, then there should not be running the same rules on the server either.  Have you even tried to implement validation on the server to see what the performance penalty would be?  From your question is sounds like the answer there would be no, and that the performance concerns are an after the fact reason not to do it.

It does not matter if this is an internal only application either; you're relying on your company's firewall to keep intruders out, but the problem is that firewall might fail to do so.  Your apps need to be secure as well; this is known as depth of defense.  You cannot rely on any one system for your security.

If you want to justify it, simply sniff one of the calls from the client to the server in something like Wireshark or Fiddler, alter it, say, make the price zero, or change some data to otherwise be invalid such that it cause the company losses, and then fire off that request (against a test environment, of course).  If that doesn't convince them, I don't know what will.

Title: Sacrifice server validation in pos of performance with Rich Client validation?

Body:
I recently started to work in a java enterprise project (~200 people) that uses a SWT rich client.
In many cases I've found business rules not being validated in server side, because the widgets that trigger such actions are disabled in the SWT client using the business rules.

This is a well known question of validation in server, client or server+client and I'm not pointing to the same issue. Also, I'm in favor of validation in server+client.

The need of validation in the client is obvious because allows a more responsive application for the end user and less requests for the server.

The need of validation in the server is obvious with a web client, where one can play with the html and javascript for avoid the client-side validations and send incorrect data to the server.

But, with a SWT client this is not that simple (could be achieved with a package sniffer like Wireshark?) so one could argue that validate in the server would have an innecesary cost in performance. Always in a scenario where there is only one point of access to the application and it's the SWT client.

If the project had begun yesterday I would fight for server+client validation, but in a project with 8 years of history this could be difficult because we would have to convince end-users and analysts for the advantages of the performance penalty.

So, every time I find one of this validation holes I struggle between add the server side validation or let it go, thinking "the client will catch it and this will never happen" and continue with a more priority task.

This project has been productive four years, so it's a viable practice, but from the point of view of design, is correct this approach? Aniway I think this is a consequence and not something deliberately sought.

Could be taken it like a political decision with knowledge of the consequences or the software world will say NO to this practice?