问:
Application Architecture
first of all I am new here and I hope that this is the right place for my question. I have a question about the recommended architecture of a project.

IDEA: Automate some calculations concerning to aerodynamics. I have some input data and I need to process this data in several sub-calculations. You can see such a calculation somehow like a black box:

INPUT => CALCULATION  => RESULTS

Some of these calculations are already available as open source programs and some of them I need to program on my own. This shouldn't be a problem at all. But I want to connect these calculations in a flexible way. For example:

INPUT => CALCULATION 1 => CALCULATION 2 => CALCULATION 3 => RESULTS

Number and order of calculations should be changeable. Should I see each calculation as standalone program and connect them in a kind of framework where I can specify order and arguments of program calls? Or are there other techniques to solve problems like this?

Thanks a lot for each advice and every recommendation.

Sebastian

答:
What you're considering is one of the tenets of the Unix philosophy:  you build lots of small tools and string them together into pipelines to make bigger ones.

One real-world example of this that parallels your problem is a set of programs called NetPBM.  NetPBM consists of more than 200 filters that can be pipelined to read an image in any of a long list of formats, manipulate it an any of a long list of ways -- often more than once -- and write the results in any supported format.  The key to making these tools work is the use of a fixed set of standard formats for the data that each filter can read and/or write or can be derived using a conversion filter.

In your case, as long as the output format of any calculation can be read by any other, you could mix and match them in any order you like.  For example, if everything was a 10x10 matrix, any of the following would work just fine (the "|" symbol means "pipe," or "direct the output of the program on the left side to the input of the program on the right side"):

```<code>Get Input | Calculation 1 | Calculation 2 | Calculation 3 | Write Output
Get Input | Calculation 3 | Calculation 2 | Calculation 1 | Write Output
Get Input | Calculation 1 | Write Output
Get Input | Calculation 1 | Calculation 3 | Write Output
</code>```

As mentioned in your comment, you might have to write filters to do conversions, and that's fine, because they fit in with the idea of having a toolbox full of small, useful tools:

```<code>Get Input | Calculation 1 | Convert 1 out to 2 in | Calculation 2 | Write Output
</code>```

That said, I would urge you to explore a numerical analysis tool like MATLAB or Octave.  Both are designed specifically for this sort of thing.  Once you're over the learning curve, you'll spend a lot more time doing math and a lot less time programming.

Title: Application Architecture

Body:
What you're considering is one of the tenets of the Unix philosophy:  you build lots of small tools and string them together into pipelines to make bigger ones.

One real-world example of this that parallels your problem is a set of programs called NetPBM.  NetPBM consists of more than 200 filters that can be pipelined to read an image in any of a long list of formats, manipulate it an any of a long list of ways -- often more than once -- and write the results in any supported format.  The key to making these tools work is the use of a fixed set of standard formats for the data that each filter can read and/or write or can be derived using a conversion filter.

In your case, as long as the output format of any calculation can be read by any other, you could mix and match them in any order you like.  For example, if everything was a 10x10 matrix, any of the following would work just fine (the "|" symbol means "pipe," or "direct the output of the program on the left side to the input of the program on the right side"):

Get Input | Calculation 1 | Calculation 2 | Calculation 3 | Write Output
Get Input | Calculation 3 | Calculation 2 | Calculation 1 | Write Output
Get Input | Calculation 1 | Write Output
Get Input | Calculation 1 | Calculation 3 | Write Output

As mentioned in your comment, you might have to write filters to do conversions, and that's fine, because they fit in with the idea of having a toolbox full of small, useful tools:

Get Input | Calculation 1 | Convert 1 out to 2 in | Calculation 2 | Write Output

That said, I would urge you to explore a numerical analysis tool like MATLAB or Octave.  Both are designed specifically for this sort of thing.  Once you're over the learning curve, you'll spend a lot more time doing math and a lot less time programming.


问:
Test case design - do for all positive tests exist also negative ones?
There is ambiguity in all papers I have read so I would like to ask about the following requirement:

Requirement: Being a Game master, I can access the GM menu by typing "menuInvoke".

Trying to do that as a regular player - is that a negative test or still positive in terms of verifying the requirement? Because some authors say negative testing means dealing with inputs unknown to specification, which would not be this case as the spec does say you need to be a Game master, implying it is not allowed for the other ones. However if you think like that, it is always implicit: range 1-1000 implies that nothing else can be entered, yet we test it as a negative test.

An example of ambiguity:
Login system. Some say that providing incorrect password to receive Login error is negative test but I agree with the others - it is plain positive test as the requirement definitely specifies that only a user with valid password can login.

答:
Look at your SUT as a function mapping values from a set D to values from a set V. As these values may be tupels as well, this view is valid for any function.

If you enter values from D into your function and test the result, it is a positive test. It may succeed (by getting the appropriate value from V) or fail (in any other case).

If you enter value, which is not from D, into your function and test the result, it is a negative test. It may succeed (by getting an error message) or fail (in any other case).

With these definitions (see Shivprasad Koirala. Sham Sheikh: Software Testing Interview Questions), a case can be constructed, where every possible input is valid. Think of a boolean function determining whether the input is an integer or not. Thus, the answer to the question "Do for all positive tests exist also negative ones?" clearly is: No.

For your example requirement, the function is probably

```<code>f: UserType X Command -> Action
</code>```

In this case, both ('GameMaster', 'menuInvoke') and ('RegularPlayer', 'menuInvoke') are valid inputs, so the both test cases are positive tests.

On the other hand, it could be defined as

```<code>f: 'GameMaster' X Command -> Action
</code>```

In this case, the tupel ('RegularPlayer', 'menuInvoke') is not a valid input, and testing this case would be a negative test.

Since your requirement does not contain the information needed to determine the kind of function, there is no general answer to the question regarding this requirement. This ambiguosity may be the reason, why examples in the literature either are so simple or contradicting.

ContentLicense: CC BY-SA 3.0

Body:
Look at your SUT as a function mapping values from a set D to values from a set V. As these values may be tupels as well, this view is valid for any function.

If you enter values from D into your function and test the result, it is a positive test. It may succeed (by getting the appropriate value from V) or fail (in any other case).

If you enter value, which is not from D, into your function and test the result, it is a negative test. It may succeed (by getting an error message) or fail (in any other case).

With these definitions (see Shivprasad Koirala. Sham Sheikh: Software Testing Interview Questions), a case can be constructed, where every possible input is valid. Think of a boolean function determining whether the input is an integer or not. Thus, the answer to the question "Do for all positive tests exist also negative ones?" clearly is: No.

For your example requirement, the function is probably

f: UserType X Command -> Action

In this case, both ('GameMaster', 'menuInvoke') and ('RegularPlayer', 'menuInvoke') are valid inputs, so the both test cases are positive tests.

On the other hand, it could be defined as

f: 'GameMaster' X Command -> Action

In this case, the tupel ('RegularPlayer', 'menuInvoke') is not a valid input, and testing this case would be a negative test.

Since your requirement does not contain the information needed to determine the kind of function, there is no general answer to the question regarding this requirement. This ambiguosity may be the reason, why examples in the literature either are so simple or contradicting.


问:
What is a Service Locator?
I've heard the term pop all around. I've read various articles regarding the subject and heard two main definitions to the term "Service Location":

A glorified Registry - Bad practice, global variables, general evil.

A type of Dependency Injection Container - Can help with managing dependencies, making modular and extensible applications, generally helpful.

But I can't differentiate between the two. What does a Service Location really means? Can you give a simple example of a Service Locator? Is it good or evil?

答:
Those two things are essentially the same. A service locator is just any centralized system which lets you find a service to process some request. Using the service locator design pattern, you can use this to get an service implementation(which is really an interface at the code level) from the service locator.

More generally, this system is often used in distributed computing to find a node in the network which can service some other node's request.

For example, some client might want to perform some calculations on some data. Lets say there are multiple ways to do this calculation, each implemented as a service, but the client doesn't care which is actually used. The client could just ask for any service from the service locator, without having to worry which specific type is returned.

In both cases, the benefits and drawbacks are largely the same. The service locator lets you modularize your program better and lets you worry less about specific service implementations. On the other hand, you get this centralized point of failure that may be a weak link in your system. Like everything else, it's a tradeoff so there is no simple "good vs bad" answer.

Title: What is a Service Locator?


问:
throwing runtime exception in Java application
I am working as a contractor designing enterprise Java application for my client in the role of  a technical lead. The application will be used by end users and there will be a support team who will support the application when we leave.

The other technical leads with whom I am working are under the impression that exception handling will make the code dirty. The system should throw checked exceptions only from the Service tier and the rest of the code should throw runtime exceptions from all other tiers so that there is no need to handle the unchecked exceptions.

What is a need to ever throw a unchecked exception in a business application?

From my experience in the past about runtime exceptions:

1) Unchecked exceptions make the code unpredictable because they do not show up even in the Javadoc.

2) Throwing Unchecked exceptions in a business application is non-sense because when you throw it and it goes straight on Users face, how do you explain it to the user? I have seen enough of web application which show 500 -Internal Error. Contact Administrator which means nothing for a end user or to the support team managing the application.

3) Throwing runtime exceptions forces the users of the class throwing the exception to walk through the source code to debug and see why the exception is thrown. This can only be avoided if the Javadoc of the runtime exception happens to be excellently documented which I find is never a case.

答:
I think you should ONLY throw checked exception when the application can recover. So, users of your library must catch those exceptions and do what it needs to recover. Anything else should be unchecked.

As a example,

If your app loads data either from an file or a database. Then,..

```<code>try {
  File data = new File(...);
  // parse file here
} catch (Exception ex) {
  throw new MissingDataFileException("data file not found");
}
</code>```

the caller could always catch the checked MissingDataFileException and then try to load the data from the database.

```<code>try {
  Connection con = DriverManager.getConnection( host, username, password );
  // query data here
} catch (Exception ex) {
  throw new RuntimeException("better call Saul!");
}
</code>```

Body:
I think you should ONLY throw checked exception when the application can recover. So, users of your library must catch those exceptions and do what it needs to recover. Anything else should be unchecked.

As a example,

If your app loads data either from an file or a database. Then,..

try {
  File data = new File(...);
  // parse file here
} catch (Exception ex) {
  throw new MissingDataFileException("data file not found");
}

the caller could always catch the checked MissingDataFileException and then try to load the data from the database.

try {
  Connection con = DriverManager.getConnection( host, username, password );
  // query data here
} catch (Exception ex) {
  throw new RuntimeException("better call Saul!");
}


问:
Is the following diagrams correct for RAD and Agile methodologies?
I do not know if this would be the right stack exchange site to ask this question but I have been researching on RAD (Rapid Application Development) and Agile methodologies and was trying to find their diagrams but if I google images this, it comes up with many different diagrams. So based on the images I drew my own diagrams on this.

The RAD diagram is similar to the one shown in wikipedia here but only difference is I change the bottom circle from cutover to implementation. For Agile method, as it is same as waterfall method but only difference is you can jump back to previous steps, I basically drew up a waterfall diagram but changed the arrows to indicate that you can go back.

My question is the below diagrams suitable for the intended methodologies?

RAD:

Agile:

UPDATE:

Waterfall Method:

答:
Your RAD diagram is accurate, but not the Agile one. Agile basically repeats the steps in your diagram several times over the course of a project. Each iteration is a sprint.
This is more accurate:

source


答:
There are a few rules for exception handling that you should bear in mind. But first, you need to remember that exceptions are part of the interface exposed by the code; document them. This is especially important when the interface is a public one, of course, but it's a very good idea in private interfaces as well.

Exceptions should only be handled at the point where the code can do something sensible with them. The worst handling option is to do nothing at all about them, which should only be done when that is exactly the correct option. (When I have such a situation in my code, I include a comment to that effect so I know not to worry about the empty body.)

The second worst option is to throw an unrelated exception without the original attached as a cause. The issue here is that the information within the original exception that would allow diagnosis of the problem is lost; you're creating something that nobody can do anything with (other than complain that “it doesn't work”, and we all know how we hate those bug reports).

Much better is logging the exception. That lets someone find out what the problem is and fix it, but you should only log the exception at the point where it would otherwise be lost or reported over an external connection. That's not because logging more often is a major problem as such, but rather because excessive logging means you just get the log consuming more space without containing more information. Once you've logged the exception, you can report a précis to the user/client with a good conscience (as long as you also include the time of generation — or other correlation identifier — in that report so that the short version can be matched up with the detail if necessary).

The best option is, of course, to completely handle the exception, dealing with the error situation in its entirety. If you can do this, by all means do it! It might even mean that you can avoid having to log the exception.

One way to handle an exception is to throw another exception that provides a higher-level description of the problem (e.g., “failed to initialize” instead of “index out of bounds”). This is a good pattern so long as you don't lose the information about the cause of the exception; use the detailed exception to initialize the cause of the higher-level exception or log the detail (as discussed above). Logging is most appropriate when you're about to cross an inter-process boundary, such as an IPC call, because there's no guarantee that the low-level exception class will be present at all on the other end of the connection. Keeping as an attached cause is most appropriate when crossing an internal boundary.

Another pattern you see is catch-and-release:

```<code>try {
    // ...
} catch (FooException e) {
    throw e;
}
</code>```

This is an anti-pattern unless you've got type constraints from other catch clauses that mean you can't just let the exception go past on its own. Then it's just an ugly feature of Java.

There's no real difference between checked exceptions and unchecked ones other than the fact that you must declare checked exceptions that cross method boundaries. It's still a good idea to document unchecked exceptions (with the @throws javadoc comment) if you know they're being thrown deliberately by your code. Don't deliberately throw java.lang.Error or its subclasses (unless you're writing a JVM implementation).

Opinion: An unexpected error case always represents a bug in your code. Checked exceptions are a way of managing this threat, and where developers are deliberately using unchecked exceptions as a way to avoid the trouble of handling error cases, you're building up a lot of technical debt that you'll have to clean up some time if you want robust code. Sloppy error handling is unprofessional (and looking at the error handling is a good way to determine how good a programmer really is).

Title: throwing runtime exception in Java application

Body:
I am working as a contractor designing enterprise Java application for my client in the role of  a technical lead. The application will be used by end users and there will be a support team who will support the application when we leave.

The other technical leads with whom I am working are under the impression that exception handling will make the code dirty. The system should throw checked exceptions only from the Service tier and the rest of the code should throw runtime exceptions from all other tiers so that there is no need to handle the unchecked exceptions.

What is a need to ever throw a unchecked exception in a business application?

From my experience in the past about runtime exceptions:

1) Unchecked exceptions make the code unpredictable because they do not show up even in the Javadoc.

2) Throwing Unchecked exceptions in a business application is non-sense because when you throw it and it goes straight on Users face, how do you explain it to the user? I have seen enough of web application which show 500 -Internal Error. Contact Administrator which means nothing for a end user or to the support team managing the application.

3) Throwing runtime exceptions forces the users of the class throwing the exception to walk through the source code to debug and see why the exception is thrown. This can only be avoided if the Javadoc of the runtime exception happens to be excellently documented which I find is never a case.

Body:
There are a few rules for exception handling that you should bear in mind. But first, you need to remember that exceptions are part of the interface exposed by the code; document them. This is especially important when the interface is a public one, of course, but it's a very good idea in private interfaces as well.

Exceptions should only be handled at the point where the code can do something sensible with them. The worst handling option is to do nothing at all about them, which should only be done when that is exactly the correct option. (When I have such a situation in my code, I include a comment to that effect so I know not to worry about the empty body.)

The second worst option is to throw an unrelated exception without the original attached as a cause. The issue here is that the information within the original exception that would allow diagnosis of the problem is lost; you're creating something that nobody can do anything with (other than complain that “it doesn't work”, and we all know how we hate those bug reports).

Much better is logging the exception. That lets someone find out what the problem is and fix it, but you should only log the exception at the point where it would otherwise be lost or reported over an external connection. That's not because logging more often is a major problem as such, but rather because excessive logging means you just get the log consuming more space without containing more information. Once you've logged the exception, you can report a précis to the user/client with a good conscience (as long as you also include the time of generation — or other correlation identifier — in that report so that the short version can be matched up with the detail if necessary).

The best option is, of course, to completely handle the exception, dealing with the error situation in its entirety. If you can do this, by all means do it! It might even mean that you can avoid having to log the exception.

One way to handle an exception is to throw another exception that provides a higher-level description of the problem (e.g., “failed to initialize” instead of “index out of bounds”). This is a good pattern so long as you don't lose the information about the cause of the exception; use the detailed exception to initialize the cause of the higher-level exception or log the detail (as discussed above). Logging is most appropriate when you're about to cross an inter-process boundary, such as an IPC call, because there's no guarantee that the low-level exception class will be present at all on the other end of the connection. Keeping as an attached cause is most appropriate when crossing an internal boundary.

Another pattern you see is catch-and-release:

try {
    // ...
} catch (FooException e) {
    throw e;
}

This is an anti-pattern unless you've got type constraints from other catch clauses that mean you can't just let the exception go past on its own. Then it's just an ugly feature of Java.

There's no real difference between checked exceptions and unchecked ones other than the fact that you must declare checked exceptions that cross method boundaries. It's still a good idea to document unchecked exceptions (with the @throws javadoc comment) if you know they're being thrown deliberately by your code. Don't deliberately throw java.lang.Error or its subclasses (unless you're writing a JVM implementation).

Opinion: An unexpected error case always represents a bug in your code. Checked exceptions are a way of managing this threat, and where developers are deliberately using unchecked exceptions as a way to avoid the trouble of handling error cases, you're building up a lot of technical debt that you'll have to clean up some time if you want robust code. Sloppy error handling is unprofessional (and looking at the error handling is a good way to determine how good a programmer really is).


答:
Your diagram for RAD is mostly correct. However, "cutover" is the term. The term "implementation" is often overloaded. In RAD, "construction" is what most people consider "implementation" - coding, unit testing, and system testing. The last stage in RAD, often called cutover and what you're calling "implementation" encapsulates all of the deployment activities - integration with other systems, deployment, training, and support.

What you're calling "agile" is incorrect. This is a model that is presented by Winston Royce in his paper Managing the Development of Large Software Systems, but isn't really agile. The agile methods are all iterative/incremental methods, and there are several ways to model these processes. The spiral model is iterative and incremental, but typically with longer increments than say Scrum or Extreme Programming, all of which have visual representations on Wikipedia.

Something to consider is that you probably can't come up with a reasonable depiction of "agile". Agile is a set of principles - adapting to changes, iterative/incremental development, time-boxed cycles (often relatively short), collaboration within the cross-functional team and between the team and the customer. Many specific process methodologies adhere to these principles to varying degrees - Scrum, the Agile Unified Process, Extreme Programming, Crystal Clear - and you would probably better model a specific agile process with its own set of activities and relationships.

Title: Is the following diagrams correct for RAD and Agile methodologies?

Body:
I do not know if this would be the right stack exchange site to ask this question but I have been researching on RAD (Rapid Application Development) and Agile methodologies and was trying to find their diagrams but if I google images this, it comes up with many different diagrams. So based on the images I drew my own diagrams on this.

The RAD diagram is similar to the one shown in wikipedia here but only difference is I change the bottom circle from cutover to implementation. For Agile method, as it is same as waterfall method but only difference is you can jump back to previous steps, I basically drew up a waterfall diagram but changed the arrows to indicate that you can go back.

My question is the below diagrams suitable for the intended methodologies?

RAD:

Agile:

UPDATE:

Waterfall Method:


答:
There are two key problems with a service locator/registry:

Finding the registry. Often the only way is to have your code be explicitly told the location of the registry, though in some cases (DI containers, discovery protocols such as Jini) the discovery of the registry isn't so hard, or is even provided as a given.

Ensuring that the information in the registry is correct/relevant. This is actually the hardest part of all. Even without the problem of malicious attacks, ensuring that any enduring collection of services is actually curated correctly is a horribly labor-intensive problem. (You can usually automatically detect when the information isn't right — with enough effort — but can't actually determine how to fix the situation without manual intervention.)

OTOH, it's entirely practical to replicate a distributed registry as long as the rate of change of the mappings it contains is not too fast. What do you think DNS is, if not a replicated registry? (Well, with extra stuff too.) This does suggest that using DNS to handle the hard parts of registry management might be a smart move, rather than replicating all that stuff again at a higher level of network stack…

Title: What is a Service Locator?

Body:
I've heard the term pop all around. I've read various articles regarding the subject and heard two main definitions to the term "Service Location":

A glorified Registry - Bad practice, global variables, general evil.

A type of Dependency Injection Container - Can help with managing dependencies, making modular and extensible applications, generally helpful.

But I can't differentiate between the two. What does a Service Location really means? Can you give a simple example of a Service Locator? Is it good or evil?


答:
Making a single product will require many, many sprints. Each sprint will require more or less of every component in your waterfall diagram (labelled "Agile" in your question).

There are many different approaches to Agile.  See this diagram

from the Wikipedia entry on agile software development for several different takes. Image taken from "Agile Software Development Methods: Review and Analysis" by Abrahamsson, P., Salo, O., Ronkainen, J., & Warsta, J..


问:
How to prove a Dynamic programming strategy will work for an algorithm?
How can I prove that a dynamic programming (dp) strategy for a problem will work or not? For greedy algorithms, we can prove by showing the sub problems exhibits matroid property.
Is there any such methods for dp algorithms?  </p>

答:
In general, the Dynamic Programming solution can be proved by showing that your solution exhibits the Optimal Substructure property.

Basically, you formulate the actual problem as composed of smaller subproblems and then combine the solutions to get your final answer. In combining, if the problem size increases, then the solution for smaller subproblem must still be optimal for the combination to actually work.

For example, if in a graph you are trying to find an the shortest path between A and C, and you already know(somehow) that that path passes through an intermediate point B, and you already know the shortest way to get from A to B, then you only need to find a shortest way to get to C from B. You don't have to worry about finding a new way all the way from A to C, that's what the optimal substructure property means. For a dynamic programming correctness proof, proving this property is enough to show that your approach is correct.

They way you prove Greedy algorithm by showing it exhibits matroid structure is correct, but it does not always work. Some greedy algorithms will not show Matroid structure, yet they are correct Greedy algorithms. For example, Huffman encoding scheme is a greedy approach, but it does not exhibit matroid structure.

To prove a greedy algorithm, in general, you need to show that your solution exhibits -1) optimal substructure property as in DP and 2) The choice made by a greedy approach is not sub-optimal (basically show that it is optimal or one of the optimal choices that can be made at that point in time)


问:
What is ASM.js and what does it mean for everyone?
I'm starting to hear rumblings about this project called ASM.js. Currently their web site is terrible and confusing. Here's what I know from my research on the web.

It is a subset of JavaScript that can be highly optimized. I'm guessing because it avoids the more dynamic parts of the language.

Performance of code compiled to ASM.js runs at about half the speed of C (not light).

The intention is for compilers to make their target language ASM.js.

Firefox is going to be shipping with ASM.js optimization baked in.

The Mozilla and Unreal teams ported the Unreal Engine to the web with it and its running in a build of Firefox at near-native speeds.

There doesn't seem to be any concrete information on the web about what this really is or the usefulness or ultimate purpose. Is it that I can compile my otherwise server-side code bases and have it run in the browser at close-to-native speeds? What are the ramifications for developers?

答:
Imagine ASM.js as a big binary ArrayBuffer called a heap and a set of JavaScript modules, which begin with a prologue directive: "use asm"; and perform fast low-level operations on raw binary data, similar to assembly languages. Those modules could be written by hand or better compiled from LLVM code by scripts like Emscripten. Their performance could be boosted thanks to the Mozilla OdinMonkey engine, but they are backward-compatible with most of the modern ECMAScript interpreters.

ASM.js is not limited to games, you can even run whole Qt apps in your browser, like these!


问:
What is the netiquette for forking other people's open source projects?
I started to get more and more engaged in open source development and I was wondering if there are any guidelines on how to properly document and maintain a fork?

For example, let's say you fork a project to add some specific thing to it. Maybe you do not want to send pull requests back to the original project or maybe your addition is something that won't be merged back. Now you have your version of a project which is not really yours and you probably don't want to neither maintain it nor you really understand it.

But if the original project keeps growing, it would be nice to incorporate patches and new features. So, what do you do? Rebase all the time or merge changes continuously? How do you setup your branches: do you keep master branch which is always unmodified fork of the original with separate branch for your changes?

What about documentation? You most likely want to keep the original readme, since it describes the project rather well. But you also need to specify what your fork does differently or additionally. Maybe you need to remove references to automated build servers from the readme since they relate to the original project.

It is easy to fork and change the code, but that isn't good enough. I want to hear your opinions, experiences and recommendations in regards to the proper and healthy open source development.

答:
Maybe you do not want to send pull requests back to the original project or maybe your addition is something that won't be merged back

Then that's it.

Why would you be concerned about incorporating your changes into the original project if you aren't concerned about merging or pulling?  Save that for the serious folks.  This is especially true if you have no intention of redistributing your fork, or only intend to distribute it within your organization.

In short, be a serious contributor, or don't.

If you are serious about being a contributor, the best way to approach that is to contact the project owner.  Generally, they will allow you to make pull requests when you have demonstrated that you're trustworthy by contributing useful changes.  The project owner can tell you what they expect in terms of proper documentation, release schedules and the like.


问:
Byte code weaving vs Lisp macros
I have been reading about the libraries people have written for languages like Java and C# that make use of byte code weaving to do things like intercept function calls, insert logging code, etc. I have also been reading up on Lisp/Clojure macros in an attempt to better understand how to utilize them. The more I read about macros, the more it seems like they provide the same kind of functionality as byte code weaving libraries. By functionality, I mean the ability to manipulate code at compile time.

Examples of libraries I have been looking at would be AspectJ, PostSharp, and Cecil.

Is there anything that can be done with one and not the other? Do they actually solve the same problems or am I comparing apples and oranges?

答:
Byte code weaving and macros are two different things.

Byte code weaving is a way to intercept function calls, so that you can inject some sort of functionality (generally a cross-cutting concern such as logging) into a function call, either before or after the function is executed.  Byte code weaving is done at the byte code level, which means that it occurs after compilation.  The function itself is not affected.  This is one of the techniques that Aspect Oriented Programming uses.

Macros are a way to extend the syntax of a language.  In its simplest form, a macro is simply a way to record keystrokes, and then play them back using a hot key.  Language macros work in a similar fashion; a keyword or other syntax construct substitutes for some sort of macro expansion.  This is oversimplified, of course; a better example of a macro specific to Lisp can be found here.

Title: Byte code weaving vs Lisp macros


问:
Is what someone publishes on the Internet fair game when considering them for employment as a programmer?
(Originally posted on Stack Overflow but closed there and more relevant for here)

So we first interviewed a guy for a technical role and he was pretty good. Before the second interview we googled him and found his MySpace page which could, to put it mildly, be regarded as inappropriate.  Just to be clear there was no doubt that it was his page (name, photos, matching biographical information and so on).

The content was entirely personal and in no way related to his professional abilities or attitude.

Is it fair to consider this when thinking about whether to offer them a job?

In most situations my response would be what goes on in someone's private life is their own doing. However for anyone technical who professes (implicitly or explicitly) to understand the Internet and the possibilities it offers, is posting things in a way which can so obviously be discovered a significant error of judgement?

EDIT: Clarification - essentially it was a fairly graphic commentary on porn (but of, shall we say, a non-academic nature).  I'm actually more interested in the general concept than the specific incident as it's something we're likely to see more in the future as people put more and more of themselves on-line.

My concerns are not primarily about him and how he feels about such things (he's white, straight, male and about the last possible victim of discrimination on the planet in that sense), more how it reflects on the company that a very simple search (basically his name) returns these things and that clients may also do it.  We work in a relatively conservative industry.

答:
Is it fair to consider this when
  thinking about whether to offer them a
  job?

Yes, though I would argue that seeking clarification may be a good idea.  Could what was posted be old enough that this would now be retracted?  How well would someone defend what they posted?  Shouldn't the candidate have a chance to defend themselves?

In most situations my response would
  be what goes on in someone's private
  life is their own doing. However for
  anyone technical who professes
  (implicitly or explicitly) to
  understand the Internet and the
  possibilities it offers, is posting
  things in a way which can so obviously
  be discovered a significant error of
  judgement?

Not necessarily.  Could the material be bait as some part of a sting operation?  Is the material dated enough that what you are seeing is years old that may or may not still be relevant,e.g. if someone posted a claim of Google being dead 2 years ago that it would happen within 6 months this would be a big blow to credibility to my mind?  As there are, however remote, rational justifications for doing what was done, I'd give the person a chance to explain themselves.  If they seem shocked that you found this, then there was a significant error of judgment.  Making assumptions can be very dangerous here is a caution I would point out.  Granted that I'm speculating of why it may not be a horrible idea but this is because your post suggests you already have that side of the argument and want some ammo for the other side as most things can be argued from either side, at least in my experience.

ContentLicense: CC BY-SA 2.5


答:
I'm assuming you are referring to a project hosted on a DVCS services (e.g. GitHub) where forking and merging is the normal way of doing things ...

It is easy to fork and change the code, but that isn't good enough.

Good enough for what?

If you are doing this solely for your own benefit, then this is a no brainer.  Do whatever you like.  But do it quietly so that you don't detract from the project that you forked from.

If you are doing this for other people's benefit then, forking and changing when you have no intention of merging is probably a bad thing:

You will inevitably antagonize the people working on the original project.

You are creating a situation where the developer effort is inevitably spread more thinly.  It is inefficient.

You are creating uncertainty and confusion for users.  Which version should they use?  Who should they trust to keep working on their fork?  To do things properly?

Unless you have a really, really good reason to maintain a long-term public fork, you should always aim to merge back.  And in order for your pull requests to be accepted you should follow the project's written guidelines for contributions.  If there are no guidelines, treat the best parts of the existing codebase as an example.  (If there is documentation, add / update it.  If there are unit tests, include unit tests for your changes.)  If nothing else, doing these things will make it more likely that your pull requests that will be accepted.

Another strategy for getting your pull requests accepted is to discuss what you are intending to do with the lead developer, and talk through any issues ... before you start coding.  And listen to what he / she says.  Be polite, be deferential, be patient.  Don't be a prima donna.

I asked about how to maintain healthy project fork which doesn't look dead and has proper documentation that states what its intent is.

Well my first advice would be DON'T ... unless you have good reason.  Long term public forks are unhealthy, for the reasons above.

Apart from that, maintaining a healthy fork is the same as a maintaining a healthy project.  For example, write the documentation, maintain the activity, provide support, recruit other contributors ... have a purpose and plan.

Title: What is the netiquette for forking other people's open source projects?

Body:
I started to get more and more engaged in open source development and I was wondering if there are any guidelines on how to properly document and maintain a fork?

For example, let's say you fork a project to add some specific thing to it. Maybe you do not want to send pull requests back to the original project or maybe your addition is something that won't be merged back. Now you have your version of a project which is not really yours and you probably don't want to neither maintain it nor you really understand it.

But if the original project keeps growing, it would be nice to incorporate patches and new features. So, what do you do? Rebase all the time or merge changes continuously? How do you setup your branches: do you keep master branch which is always unmodified fork of the original with separate branch for your changes?

What about documentation? You most likely want to keep the original readme, since it describes the project rather well. But you also need to specify what your fork does differently or additionally. Maybe you need to remove references to automated build servers from the readme since they relate to the original project.

It is easy to fork and change the code, but that isn't good enough. I want to hear your opinions, experiences and recommendations in regards to the proper and healthy open source development.


问:
Bothering to cater to non-JavaScript clients?
Considering that it's April, 2013; do I still need to worry about non-JavaScript capable/enabled clients?

Note: This question excludes having helper text with: JavaScript is required to view this page, upgrade to a modern browser or modify your settings

BTW: Just to be clear, in order to cater to non-JavaScript capable/enabled clients; I will have to: prerender (cache) a version of my decoupled (JavaScript on the client-side consumes my RESTful API) website.

Because of framework limitations this will result in far less functionality for the non-JavaScript user.

答:
It depends on what types of webpages you are designing. At any rate here are some of the problems:

Some older mobile phones (in use) still do not support Javascript.

If you webpage is displayed in an e-mail (e.g., Mac mail allows you to embed webpages; some e-mailers display web snippets etc.) and if the target e-mail client (e.g., Microsoft Outlook 2007) is used to view the e-mail then the viewer will not be able to see the page properly (as Microsoft Office 2007 will not allow Javascript in many enterprise settings).

Javascript blacklists/blockers disable javascript is many modern browsers.

A university I visited last year (January 2012) has a lab that uses Mac workstations running an archaic version of Mac OS (not even OS X). Their particular scientific software is not yet runnable on OS X. A lot of people have very good reason to not upgrade to the modern world OS/browsers.

In all these cases, you may want to handle this error properly.


答:
Some people prefer disable javascript for various reasons. To some degree, it depends on your audience, but I think it makes sense to ensure that your site is at least minimally usable without javascript. </p>

<p>Don't waste too much time on it though, as they will probably be <1% of users. </p>

Title: Bothering to cater to non-JavaScript clients?

Body:
Considering that it's April, 2013; do I still need to worry about non-JavaScript capable/enabled clients?

Note: This question excludes having helper text with: JavaScript is required to view this page, upgrade to a modern browser or modify your settings

BTW: Just to be clear, in order to cater to non-JavaScript capable/enabled clients; I will have to: prerender (cache) a version of my decoupled (JavaScript on the client-side consumes my RESTful API) website.

Because of framework limitations this will result in far less functionality for the non-JavaScript user.

Body:
Some people prefer disable javascript for various reasons. To some degree, it depends on your audience, but I think it makes sense to ensure that your site is at least minimally usable without javascript.

Don't waste too much time on it though, as they will probably be <1% of users.


问:
Is (1/(1/x)) always a perfect round trip?
Is the following guaranteed to return true for all numerical and non-zero values of x?

```<code>bool IsRoundTrip(double x)
{
    double y = 1 / (1 / x);
    return x == y;
}
</code>```

What conditions would cause a discrepency?

答:
There exists the possibility that they will not be the same due to how the floating point numbers are represented.

Information on their numerical representation can be found at ...
    http://en.wikipedia.org/wiki/Floating-point

Most of the time, floating point numbers are normalized.  Should the number be a denormalized float, your algorithm can be expected to return false.  Whether it will or not, will depend upon whether your compiler chooses to recognize the mathematical equivalency and optimize based on that, OR to implement exactly what you have requested.

There may be other cases where your algorithm could return false, but that is the first that comes to my mind.


答:
Rule of thumb: If the language has a type named "double", this will probably be false for most values of x.

"Double" is usually short-hand to "Double Precision Floating Point Number". By saying "Double precision", it implies "finite precision", i.e. rounding will occur at some point.

Some languages support "Arbitrary Precision Numbers", which allows storing any value that has a finite representation, and can usually do some math with these numbers without loss of precision. This still doesn't cover all options, as some numbers just don't have a finite representation - for example, 1/3 is close to 1.3333, but it can't be written down without some

To handle this, some languages also support "Symbolic numbers", which is basically means they keep the number as "1/3", and can do math with this form.

Using arbitrary precision or symbolic numbers has a high cost in performance, which is why it's not common in "mainstream" languages.
Languages that support these forms also have a tendency to be untyped, and will only have join all number types under the name "Number" (But this is by no means related to supporting high-precision).

I most languages that have a type "double", it's identical (Or at lease very similar) to IEEE 754 Double Precision type.

Note: Your code might not fail for x=3, because although the program can't hold 1/3 precisely, it may also make a similar rounding error when dividing 1 by what it can hold, and come out with 3 again.

Note 2: You will find libraries for arbitrary/symbolic math for most languages that don't have them built in.

Title: Is (1/(1/x)) always a perfect round trip?

Body:
Is the following guaranteed to return true for all numerical and non-zero values of x?

```<code>bool IsRoundTrip(double x)
{
    double y = 1 / (1 / x);
    return x == y;
}
</code>```

What conditions would cause a discrepency?


答:
Besides rounding errors with either the first or the second division, IEEE floating point has + and - infinity and NaN (Not a Number), as well as zero, which doesn't even work with your formula for real numbers (meaning the mathematical abstraction, rather than a computer storage format).

Without getting into the odd special cases (zero, infinity, NaN), it seems likely that the only way you're going to get a true result is if there are two rounding errors that happen to cancel out or if the number is exactly representable in IEEE floating point.  Since there are several different rounding schemes for IEEE floating point, and hardware could store more bits than the representation to try to keep things accurate, predicting when rounding would cancel out seems both difficult and hardware-dependent.

This is not the sort of thing that floating point was invented to deal with.


答:
If you care about accessibility (and why wouldn't you?) having the site work without JavaScript goes a long way towards it working nicely with screen readers for sight impaired users.

Modern screen readers can function with JavaScript enabled, but it takes more work and testing to make sure content is accessible and navigation works. If the main functions of the site work without JavaScript you can be fairly confident that it's ok for screen readers too.


答: I'd assume this will produce true whenever the compiler optimizes the calculation away. Apart from that checking for equality is considered a programming error in case of doubles (unless your compiler/hardware combination warrants the opposite, which I would not dare to believe in). This is not limited to your example, but may also occur in other situations. Like writing a double to the DB and reading it back and comparing it with the original value you may still have in memory.</p>


问:
How to design member access for an Article-type class?
I am doing a final project in a C++ class writing a very simple usenet-like client/server. I figure that since it's usenet-like I'll have a NewsGroup class and an Article class, I'm now working on my Article class. I can't really decide on a good design, though (this class is not about design patterns and I haven't taken any).

This is what I have:

```<code>class Article {
public:
    const std::string author;
    std::string title;
    std::string text;
    const uint32_t id;
    system_clock::time_point timestamp;

    Article(const std::string auth&,
            const std::string tit&,
            const std::string txt&,
            const system_clock::time_point&);

private:
    Article(const Article&);
    void operator=(const Article&);
    static uint32_t id_pool;
};
</code>```

My motivation is this:

author should never change -> const

title could change if edited -> non-const

text could change if edited -> non-const

id should never change -> const

timestamp could change but probably shouldn't, I'm not sure what to do with it yet.

id_pool is just where I get IDs from. One specification is that IDs should never be reused so I just increment id_pool in the Article constructor.

Coming from Java with all the getters and setters that I really don't like, and then some Python with it's "Everything public" and properties, that I do like, I'm getting a bit confused here.

I mean, I could make the members private and have getters and setters (I can't think of any natural "verb-methods" that an Article can "do"), but it feels like I would gain very little.

I would be thankful for some pointers on good design in this case.

答:
Start with the interface you want the class to expose to its users. Do not think immediately about the implementation, e.g., whether to use std::string for the title, etc. I would come up with something like below:

```<code>class Article {
public:
    typedef implementation_defined Id;

    Article(const char* author, const char* title);
    ~Article();

    Id GetId() const;
    const char* GetAuthor() const;
    const char* GetTitle() const;
    const char* GetText() const;
    system_clock::time_point GetTime() const;

    void SetTitle(const char* text);
    void SetText(const char* text);
    void SetTime(system_clock::time_point timestamp);
};
</code>```

The intention is that the caller should use the type Article::Id instead of something like int. I assume the Id is uniquely generated on creation, the text can be empty, and the default timestamp is the current time.

As you are not exposing the implementation to the caller, you are free to change the implementation later. E.g., maybe the interface dictates the UTF-8 encoding, but the real implementation uses UTF-16 (wchar_t) on Windows (just to show, not that it is something you should/want to do). You can also make some checks in the Set... methods.

This might be trivial, but I think the principle is that you need to: 1) think from the user of the class; 2) make it flexible and reduce the dependency.

Body:
Start with the interface you want the class to expose to its users. Do not think immediately about the implementation, e.g., whether to use std::string for the title, etc. I would come up with something like below:

class Article {
public:
    typedef implementation_defined Id;

    Article(const char* author, const char* title);
    ~Article();

    Id GetId() const;
    const char* GetAuthor() const;
    const char* GetTitle() const;
    const char* GetText() const;
    system_clock::time_point GetTime() const;

    void SetTitle(const char* text);
    void SetText(const char* text);
    void SetTime(system_clock::time_point timestamp);
};

The intention is that the caller should use the type Article::Id instead of something like int. I assume the Id is uniquely generated on creation, the text can be empty, and the default timestamp is the current time.

As you are not exposing the implementation to the caller, you are free to change the implementation later. E.g., maybe the interface dictates the UTF-8 encoding, but the real implementation uses UTF-16 (wchar_t) on Windows (just to show, not that it is something you should/want to do). You can also make some checks in the Set... methods.

This might be trivial, but I think the principle is that you need to: 1) think from the user of the class; 2) make it flexible and reduce the dependency.


问:
Is it a bad habit to (over)use reflection?
Is it a good practice to use reflection if greatly reduces the quantity of boilerplate code?

Basically there is a trade-off between performance and maybe readability on one side and abstraction/automation/reduction of boilerplate code on the other side.

Edit: Here is an example of a recommended use of reflection.

To give an example, suppose there is a an abstract class Base which has 10 fields and has 3 subclasses SubclassA, SubclassB and SubclassC each with 10 different fields; they are all simple beans. The problem is that you get two Base type references and you want to see if their corresponding objects are of same (sub)type and are equal.

As solutions there is the raw solution in which you first check if the types are equal and then check all fields or you can use reflection and dynamically see if they are of the same type and iterate over all methods that start with "get" (convention over configuration), call them on both objects and call equals on the results.

```<code>boolean compare(Base base1, Base, base2) {
    if (base1 instanceof SubclassA && base2 instanceof SubclassA) {
         SubclassA subclassA1 = (SubclassA) base1;
         SubclassA subclassA2 = (SubclassA) base2;
         compare(subclassA1, subclassA2);
    } else if (base1 instanceof SubclassB && base2 instanceof SubclassB) {
         //the same
    }
    //boilerplate
}

boolean compare(SubclassA subA1, SubclassA subA2) {
    if (!subA1.getField1().equals(subA2.getField1)) {
         return false;
    }
    if (!subA1.getField2().equals(subA2.getField2)) {
         return false;
    }
    //boilerplate
}

boolean compare(SubclassB subB1, SubclassB subB2) {
    //boilerplate
}

//boilerplate

//alternative with reflection
boolean compare(Base base1, Base base2) {
        if (!base1.getClass().isAssignableFrom(base2.getClass())) {
            System.out.println("not same");
            System.exit(1);
        }
        Method[] methods = base1.getClass().getMethods();
        boolean isOk = true;
        for (Method method : methods) {
            final String methodName = method.getName();
            if (methodName.startsWith("get")) {
                Object object1 = method.invoke(base1);
                Object object2 = method.invoke(base2);
                if(object1 == null || object2 == null)  {
                    continue;
                }
                if (!object1.equals(object2)) {
                    System.out.println("not equals because " + object1 + " not equal with " + object2);
                    isOk = false;
                }
            }
        }

        if (isOk) {
            System.out.println("is OK");
        }
}
</code>```

答:
Overusing of reflection probably depends on the language used. Here you are using Java. In that case, reflection should be used with care because often it is only a workaround for bad design.

So, you are comparing different classes, this is a perfect problem for method  overriding. Note that instances of two different classes should never be considered equal. You can compare for equality only if you have instances of the same class.
See https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java for an example how to implement equality comparison correctly.


问:
Do you find languages with indentation requirements cumbersome?
Thoughts on these?  Python is one example, and no this is not a stab against Python I like the language.

What languages have a indentation requirement?

答: There is no free lunch; something must be used for a delimiter. Since we use spacing anyway, using EOL,space and tab characters makes sense and reduces clutter. </p>


答: No, it is not always a round trip.  In mathematics (i.e., the kind your write on paper with a pencil), it will be, because mathematics doesn't have a problem with limited precision.  But in any finite-precision system (e.g., any computer), there will be quantities of the form x != 1/(1/x).  It's downright trivial to prove - when x is 3, finite-precision decimal arithmetic cannot make 1/(1/3) come out to 3.  1/3 => 0.33333..., and no matter how many digits you extend it to, you'll still be incorrect.  Finite-precision binary arithmetic has the same problem with other values.


答:
Reflection was created for a specific purpose, to discover the functionality of a class that was unknown at compile time, similar to what the dlopen and dlsym functions do in C.  Any use outside of that should be heavily scrutinized.

Did it ever occur to you that the Java designers themselves encountered this problem?  That's why practically every class has an equals method.  Different classes have different definitions of equality.  In some circumstances a derived object could be equal to a base object.  In some circumstances, equality could be determined based on private fields without getters.  You don't know.

That's why every object who wants custom equality should implement an equals method.  Eventually, you'll want to put the objects into a set, or use them as a hash index, then you'll have to implement equals anyway.  Other languages do it differently, but Java uses equals.  You should stick to the conventions of your language.

Also, "boilerplate" code, if put into the correct class, is pretty hard to screw up.  Reflection adds additional complexity, meaning additional chances for bugs.  In your method, for example, two objects are considered equal if one returns null for a certain field and the other doesn't.  What if one of your getters returns one of your objects, without an appropriate equals?  Your if (!object1.equals(object2)) will fail.  Also making it bug prone is the fact that reflection is rarely used, so programmers aren't as familiar with its gotchas.

Title: Is it a bad habit to (over)use reflection?

Body:
Is it a good practice to use reflection if greatly reduces the quantity of boilerplate code?

Basically there is a trade-off between performance and maybe readability on one side and abstraction/automation/reduction of boilerplate code on the other side.

Edit: Here is an example of a recommended use of reflection.

To give an example, suppose there is a an abstract class Base which has 10 fields and has 3 subclasses SubclassA, SubclassB and SubclassC each with 10 different fields; they are all simple beans. The problem is that you get two Base type references and you want to see if their corresponding objects are of same (sub)type and are equal.

As solutions there is the raw solution in which you first check if the types are equal and then check all fields or you can use reflection and dynamically see if they are of the same type and iterate over all methods that start with "get" (convention over configuration), call them on both objects and call equals on the results.

```<code>boolean compare(Base base1, Base, base2) {
    if (base1 instanceof SubclassA && base2 instanceof SubclassA) {
         SubclassA subclassA1 = (SubclassA) base1;
         SubclassA subclassA2 = (SubclassA) base2;
         compare(subclassA1, subclassA2);
    } else if (base1 instanceof SubclassB && base2 instanceof SubclassB) {
         //the same
    }
    //boilerplate
}

boolean compare(SubclassA subA1, SubclassA subA2) {
    if (!subA1.getField1().equals(subA2.getField1)) {
         return false;
    }
    if (!subA1.getField2().equals(subA2.getField2)) {
         return false;
    }
    //boilerplate
}

boolean compare(SubclassB subB1, SubclassB subB2) {
    //boilerplate
}

//boilerplate

//alternative with reflection
boolean compare(Base base1, Base base2) {
        if (!base1.getClass().isAssignableFrom(base2.getClass())) {
            System.out.println("not same");
            System.exit(1);
        }
        Method[] methods = base1.getClass().getMethods();
        boolean isOk = true;
        for (Method method : methods) {
            final String methodName = method.getName();
            if (methodName.startsWith("get")) {
                Object object1 = method.invoke(base1);
                Object object2 = method.invoke(base2);
                if(object1 == null || object2 == null)  {
                    continue;
                }
                if (!object1.equals(object2)) {
                    System.out.println("not equals because " + object1 + " not equal with " + object2);
                    isOk = false;
                }
            }
        }

        if (isOk) {
            System.out.println("is OK");
        }
}
</code>```


问:
Resources for Test Driven Development in Web Applications?
I would like to try and implement some TDD in our web applications to reduce regressions and improve release quality, but I'm not convinced at how well automated testing can perform with something as fluffy as web applications.

I've read about and tried TDD and unit testing, but the examples are 'solid' and rather simple functionalities like currency converters, and so on.

Are there any resources that can help with unit testing content management and publication systems? How about unit testing a shopping cart/store (physical and online products)? AJAX?

Googling for "Web Test Driven Development" just gets me old articles from several years ago either covering the same examples of calculator-like function or discussions about why TDD is better than anything (without any examples).

答:
I've written a book on TDD for web development with Python + Django.  it covers TDD, both with end-to-end / functional tests (selenium) and lower-level "unit" tests.  I also cover modern dev practices like how to integrate git into your workflow, how to deploy to a server and automate and test that, continuous integration, mocks and test isolation, and lots more:

http://www.obeythetestinggoat.com/

(or http://shop.oreilly.com/product/0636920051091.do)

ContentLicense: CC BY-SA 4.0


答:
To simplify things by defining a concrete implementation, I will assume (as other answers do) that we're talking about IEEE 754 64-bit floating point.

Each floating point number has three parts: a sign, an exponent, and a mantissa. (Technical details about hidden bits are irrelevant to this discussion).

Reciprocation doesn't affect the sign

1 / (2**e * m) = (1 / 2**e) * (1 / m) = 2**-e * (1 / m) , so there are two ways in which the double-reciprocation can fail to provide a fixpoint. The easy one is that the exponent can be an extreme value such that we move from a denormalised number to one which overflows. The second is that the mantissa can be a non-fixpoint of the double-reciprocation.

I wrote a simple program to test random mantissas:

```<code>import java.util.Random;

strictfp class RoundTrip
{
    public static void main(String[] args)
    {
        long one = Double.doubleToLongBits(1.0);
        Random rnd = new Random();
        for (int i = 1; i < 1<<30; i++) {
            long mantissa = rnd.nextLong() & 0xfffffffffffffL;
            double x = Double.longBitsToDouble(one + mantissa);
            double y = 1 / (1 / x);
            if (x != y) {
                System.out.println(Long.toHexString(one + mantissa));
                System.out.println(x);
                System.out.println(y);
                break;
            }
        }
    }
}
</code>```

It quickly gave some output:

```<code>3ffeca41c09ebb2b
1.9243791126461456
1.9243791126461458
</code>```

The program can be expected to find an answer if as few as 1 in 2**30 mantissas fail. With a slight modification, I found that about 17.15% of mantissas fail.

Slightly handwavy analysis:

There are 2**52-1 mantissas covering the open range (1, 2), and they're uniformly spaced.
The same uniformly spaced mantissas cover the open range (0.5, 1), which contains the reciprocals. Note that in this range one unit in the last place (1ulp), i.e. the difference between consecutive values, has an absolute value half that of the ulp in the range (1, 2). But reciprocation isn't a linear operation, so in some parts of the range the density of values required is higher than in others. Therefore we expect that the reciprocation will not be injective.

Suppose values x and x+dx, both in (1, 2), differ by 1ulp. If they map to the same reciprocal mantissa, at most one of them can round-trip. What is the probability of this collision?

x^-1 differentiates to -x^-2, so the difference between 1/x and 1/(x+dx) is approximately -dx/x^2, or -2dx/x^2 ulps, so a difference of one ulp before reciprocation gives a difference of -2/x^2 ulps after reciprocation. Given that the separation between two exactly representable values is 1ulp (by definition), and assuming (for simplification) no particular alignment between mantissas and reciprocal mantissas, we can estimate the probability of a collision as max(0, 1 - 2/x^2), and we can approximate the proportion of collisions as \int_1^2 max(0, 1 - 2/x^2) dx = \int_{\sqrt 2}^2 (1 - 2/x^2) dx = 3 - 2\sqrt 2 is approximately 0.1716. This is in very good agreement with my empirical results for the proportion of mantissas that don't round-trip, so it seems reasonable to hypothesise that a mantissa will round-trip unless its reciprocal collides with that of another mantissa, in which case only one of the two will round-trip.

Body:
To simplify things by defining a concrete implementation, I will assume (as other answers do) that we're talking about IEEE 754 64-bit floating point.

Each floating point number has three parts: a sign, an exponent, and a mantissa. (Technical details about hidden bits are irrelevant to this discussion).

Reciprocation doesn't affect the sign

1 / (2**e * m) = (1 / 2**e) * (1 / m) = 2**-e * (1 / m) , so there are two ways in which the double-reciprocation can fail to provide a fixpoint. The easy one is that the exponent can be an extreme value such that we move from a denormalised number to one which overflows. The second is that the mantissa can be a non-fixpoint of the double-reciprocation.

I wrote a simple program to test random mantissas:

import java.util.Random;

strictfp class RoundTrip
{
    public static void main(String[] args)
    {
        long one = Double.doubleToLongBits(1.0);
        Random rnd = new Random();
        for (int i = 1; i < 1<<30; i++) {
            long mantissa = rnd.nextLong() & 0xfffffffffffffL;
            double x = Double.longBitsToDouble(one + mantissa);
            double y = 1 / (1 / x);
            if (x != y) {
                System.out.println(Long.toHexString(one + mantissa));
                System.out.println(x);
                System.out.println(y);
                break;
            }
        }
    }
}

It quickly gave some output:

3ffeca41c09ebb2b
1.9243791126461456
1.9243791126461458

The program can be expected to find an answer if as few as 1 in 2**30 mantissas fail. With a slight modification, I found that about 17.15% of mantissas fail.

Slightly handwavy analysis:

There are 2**52-1 mantissas covering the open range (1, 2), and they're uniformly spaced.
The same uniformly spaced mantissas cover the open range (0.5, 1), which contains the reciprocals. Note that in this range one unit in the last place (1ulp), i.e. the difference between consecutive values, has an absolute value half that of the ulp in the range (1, 2). But reciprocation isn't a linear operation, so in some parts of the range the density of values required is higher than in others. Therefore we expect that the reciprocation will not be injective.

Suppose values x and x+dx, both in (1, 2), differ by 1ulp. If they map to the same reciprocal mantissa, at most one of them can round-trip. What is the probability of this collision?

x^-1 differentiates to -x^-2, so the difference between 1/x and 1/(x+dx) is approximately -dx/x^2, or -2dx/x^2 ulps, so a difference of one ulp before reciprocation gives a difference of -2/x^2 ulps after reciprocation. Given that the separation between two exactly representable values is 1ulp (by definition), and assuming (for simplification) no particular alignment between mantissas and reciprocal mantissas, we can estimate the probability of a collision as max(0, 1 - 2/x^2), and we can approximate the proportion of collisions as \int_1^2 max(0, 1 - 2/x^2) dx = \int_{\sqrt 2}^2 (1 - 2/x^2) dx = 3 - 2\sqrt 2 is approximately 0.1716. This is in very good agreement with my empirical results for the proportion of mantissas that don't round-trip, so it seems reasonable to hypothesise that a mantissa will round-trip unless its reciprocal collides with that of another mantissa, in which case only one of the two will round-trip.


问:
Ext JS licensing issue
First of all I'm not asking for legal advice but just checking if anyone agrees with my suspicions. That might help in convincing Sencha to change their license.

Their commercial license says:

The Open Source version of the Software (“GPL Version”) is licensed under the terms of the GNU General Public License versions 3.0 (“GPL”) and not under this License Agreement. If You, or another third party, has, at any time, developed all (or any portions of) the Application(s) using the GPL Version, You may not combine such development work with the Software and must license such Application(s) (or any portions derived there from) under the terms of the GNU General Public License version 3, a copy of which is located at http://www.gnu.org/copyleft/gpl.html.

Meanwhile there exist libraries licensed under MIT or BSD, that use ExtJS. GeoExt is one example. It's likely some contributors of those libraries have not bought the commercial license of Ext JS, and are using its GPL-licensed version. Reasonably GPL-licensed Ext JS shouldn't "infect" GeoExt code if it's distributed without the Ext JS library.

Now the problem is, if I use GeoExt then likely "portions" of it have been "developed using" the GPL version. Specifically Sencha clarifies what they mean by "develop using" in their FAQ:

The license prohibits combining code that you develop using a GPL licensed version of the software with code that you develop using a commercial licensed version. In other words, you may not begin development with our GPL version and then "convert" it to our commercial version.

My interpretation is that it's not allowed by the Sencha commercial license to combine Ext JS with GeoExt and who knows what other libraries whose contributors at some point may have "developed using" a GPL version of Ext JS. This may or may not include OpenLayers, jQuery and other libraries developers would likely also need to use in their commercial projects.

If Sencha then so desires, according to their commercial contract they can demand commercial customers who combined Ext JS with other libraries, to release their software under the GPL, since the commercial license doesn't offer any other resolution.

My question is: do you agree that this sounds like developing commercial software using Ext JS may be risky, or is my interpretation incorrect?

答:
As far as I can determine, the commercial license forbids the development of libraries, because libraries permit a third party to do software development using Ext JS.

This means that any libraries that are built upon Ext JS must, by necessity, be using the GPL version of Ext JS.

By extension, if you use any of those libraries in your own application, you are also forbidden from using the commercial version of Ext JS.

I am not familiar enough with how the GPL interacts with JS to be able to tell in how far the use of the GPL version of Ext JS "infects" the rest of the code.

Title: Ext JS licensing issue


问:
Is slower performance of programming languages, really, a bad thing?
Here's how  I see it.

There's machine code and it's all that computers needs in order to run something. Computers don't care about programming languages. It doesn't matter to them whether the machine code comes from Perl, Python or PHP. Programming languages don't serve computers. They serve programmers.

Some programming languages run slower than others but that's not necessarily because there is something wrong with them. In many cases, it's because they do more things that programmers would otherwise have to do (i.e. memory management) and by doing these things, they are better in what they are supposed to do - serve programmers.

So, is slower performance, of programming languages, really, a bad thing?

答: I'll point out that most the performance problems exist because the programmer did a bad job not because the language was too slow. Really, there are many more pertinent things to worry about in performance than the language you choose. That would be approximately number 1,203,407th on my list.</p>


问:
Functional document from code
I am a Sr java Developer and have recently joined a new team. Here I have been asked to create a functional document looking at the code of a legacy application. This application was written about 8-10 years back, which is currently running in live environment but due to lack of documentation it is difficult to be setup and run on local development box. I consulted some of the old team members who support it, but none was able to run it on their dev boxes.

Now I have to create a functional document out of it (with running it only looking at the code) which will act as a base to re-write this application with new technology and some enhancements. Kindly suggest what would be the best way to move forward?

I tried to find out from testers and found that there is no tester currently allocated to this application as it's an old running app on live. There are not much enhancements or bugs coming up. Ans as this re-write project is already queued up, the management is looking into aligning any coming bugs to this new app.

答:
Joel Spolsky had a lot to say about rewriting code (i.e., "don't").

In your shoes I'd try to tie down the business users and see if I could get a current set of requirements out of them.  It's possible the old code contains logic to handle situations and conditions that are no longer relevant.  You may have an opportunity to greatly reduce the footprint.

You can use this new list as a guide when you examine the code, to determine which bits are important and which bits can receive less attention.

Be sure to remind management that they'll need to assign testers to this project.

(A mechanical bug-for-bug port is possible of course, but personally I'd avoid it)

Good luck!

Title: Functional document from code


问:
Form validation and file structure
I have a form (lets say a registration form) and onsubmit, it calls a function to validate as follows:

```<code>$.ajax({
        url : "/ajax/validate.php",
        type : "POST",
        data : $(".form").serialize(),
        success : function(data) {
            data = $.parseJSON(data);
            $.each(data, function(i, item) {
                $('#' + i).addClass('errors');
            });
        }
    });
</code>```

The validate.php looks something like this:

```<code>if ($_POST['email'] == '' || filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) {
    $errors['email'] = 'Not a valid email';
}
if ($errors) {
    echo json_encode($errors);
} else {
    // insert to db
}
</code>```

Now all of this code is specifically for the registration form. I'll have many forms on my site. My question is, do I make a new file (like validate.php) for each individual form? Such as /ajax/save_profile_data.php etc? Do I keep each form validation separate or is there a clever way to approach this? I don't know if having a validate file for each form on my site is the correct way to do it.

答:
If you have multiple forms submitting to the same page (file), you can use hidden fields in your form to determine which action should take place -  to identify the forms by sending along a hidden data field.

For example:

```<code><form id='reg'>
  <input type='hidden' name='act' value='registration'>
  <!-- More HTML -->
</form>

<form id='news'>
  <input type='hidden' name='act' value='newsletter'>
  <!-- More HTML -->
</form>
</code>```

Also, add client side validation to reduce server processing. For this purpose, you can use free jQuery Validation plugin

Download and copy to your website's directory jquery.validate.js, additional-methods.js and jQuery library itself. In pages where you wish to use validation, reference all these files.

Here is how to use it

HTML

```<code><form action="#" method="post" name="registration">
<input type="text" name="name" required minlength="2" maxlength="30"
            pattern="^[a-zA-Z\s]+$" placeholder="Name"
            title="Name is required, and must contain between 2 and 30 alpha characters" />
</form>
<form action="#" method="post" name="newsletter">
<input type="text" name="name" required minlength="2" maxlength="30"
            pattern="^[a-zA-Z\s]+$" placeholder="Name"
            title="Name is required, and must contain between 2 and 30 alpha characters" />
</form>
</code>```

JS

```<code>$(function() {
      $("form").each(function() {
            $(this).validate({
                  submitHandler: function (form) {
                        return false; //prevent actual submit (requirements?)
                  }
            });
      });
});
</code>```

Title: Form validation and file structure

Body:
If you have multiple forms submitting to the same page (file), you can use hidden fields in your form to determine which action should take place -  to identify the forms by sending along a hidden data field.

For example:

<form id='reg'>
  <input type='hidden' name='act' value='registration'>
  <!-- More HTML -->
</form>

<form id='news'>
  <input type='hidden' name='act' value='newsletter'>
  <!-- More HTML -->
</form>

Also, add client side validation to reduce server processing. For this purpose, you can use free jQuery Validation plugin

Download and copy to your website's directory jquery.validate.js, additional-methods.js and jQuery library itself. In pages where you wish to use validation, reference all these files.

Here is how to use it

HTML

<form action="#" method="post" name="registration">
<input type="text" name="name" required minlength="2" maxlength="30"
            pattern="^[a-zA-Z\s]+$" placeholder="Name"
            title="Name is required, and must contain between 2 and 30 alpha characters" />
</form>
<form action="#" method="post" name="newsletter">
<input type="text" name="name" required minlength="2" maxlength="30"
            pattern="^[a-zA-Z\s]+$" placeholder="Name"
            title="Name is required, and must contain between 2 and 30 alpha characters" />
</form>

JS

$(function() {
      $("form").each(function() {
            $(this).validate({
                  submitHandler: function (form) {
                        return false; //prevent actual submit (requirements?)
                  }
            });
      });
});


问:
Time required to start coding at a new company
I am a software engineer for 4 years, and I just changed my company for the first time.

Company works with pair programming, and it's been 3 days, I couldn't even write a single line of code.
It's so frustrating for me because I was very productive at my previous company.

The codebase is large, they are using 5-6 languages/tools that I am not familiar with, like rspec, haml, jasmine and others. But still, I feel awful.

This weekend I created UML to get better understanding of the application, but still I am guessing I'll not be able to write decent amount of code this week.

Is this normal?

What is your experience when you change your job, and dive into a large codebase written with languages/libraries you are not familiar with.

Of course I am not asking for exact time required, but past experiences or things to make the process would be great.

Btw, I've already read below questions&answers,
How do you dive into large code bases?

https://stackoverflow.com/questions/215076/whats-the-best-way-to-become-familiar-with-a-large-codebase

https://stackoverflow.com/questions/214605/the-best-way-to-familiarize-yourself-with-an-inherited-codebase

UPDATE

All great suggestions! I just came from work, I've worked a lot!

About pair programming:

Generally they write code, and I am trying to not miss even a second!
If I try to write the code, I know it's gonna take forever, because I don't even know which files should I edit, but beside that, as I said, they are using 6-7 languages/frameworks that I'm not familiar with, and learning all these syntaxes at one is not easy.

How well the company prepared for engineers:

I can't say they are well organized, they kind of expecting me to start writing code immediately.

Taking notes, being proactive:

I'm always taking notes when they write a new command/or anything about data models.
My peers are very smart and kind people, and I'm trying to ask lots of questions, even lots of stupid questions sometimes.

Is this common?:

@Telastyn, thanks for your answers, it made me feel a little better. It seems like my problem is not that uncommon, but I was really productive before this job, and now I really feel useless and not smart.

I hope I can start solving bugs/implementing issues very soon.

About frameworks/languages they use:

I was really honest about that, I didn't say I know something that I don't know actually.
But I wasn't expecting that much different things, and since I started working at the day I accepted the offer, I didn't have time to prepare myself.

@Southpaw Hare, thanks alot for sharing your experience. You are absolutely right. There is no guarantee that I'm going to learn all of these stuff, but I'm trying.
At the end, it's is hard to learn all of the syntax at once, and I think that is the main problem too. Because I can navigate in ruby code well since I know that language, and I navigate in js codes thanks to browser inspectors, but the problem is writing the actual codes with the frameworks/languages I don't know.

答:
This depends on things like the complexity of the system and how well the organization is prepared to onboard new programmers. It can take anywhere from 30 minutes to multiple weeks. It's not necessarily anything you're doing wrong and you shouldn't feel bad about it.

What you should do, however, is be proactive about fixing it for yourself and others. Tell your manager about your frustrations and work together to overcome them and to improve the process for other new hires.

Write notes about the things that you are struggling with, brainstorm ways to fix them or get around them, and document your process. Keep other people who can help you up-to-date with your progress and reach out for help. There's nothing shameful in asking for help.


答:
Is this normal?

For most codebases it is. Hell, at my company you are meeting with HR for 2 days before you're allowed to touch a computer. That's an outlier, but consider how long it takes to get the development environment setup, get vaguely familiar with the domain, code structure, team norms...

As a team lead, I expect you to do effectively nothing for 1 (two week) sprint, and work at ~50% for the next 1-2 sprints.

Title: Time required to start coding at a new company

Body:
I am a software engineer for 4 years, and I just changed my company for the first time.

Company works with pair programming, and it's been 3 days, I couldn't even write a single line of code.
It's so frustrating for me because I was very productive at my previous company.

The codebase is large, they are using 5-6 languages/tools that I am not familiar with, like rspec, haml, jasmine and others. But still, I feel awful.

This weekend I created UML to get better understanding of the application, but still I am guessing I'll not be able to write decent amount of code this week.

Is this normal?

What is your experience when you change your job, and dive into a large codebase written with languages/libraries you are not familiar with.

Of course I am not asking for exact time required, but past experiences or things to make the process would be great.

Btw, I've already read below questions&answers,
How do you dive into large code bases?

https://stackoverflow.com/questions/215076/whats-the-best-way-to-become-familiar-with-a-large-codebase

https://stackoverflow.com/questions/214605/the-best-way-to-familiarize-yourself-with-an-inherited-codebase

UPDATE

All great suggestions! I just came from work, I've worked a lot!

About pair programming:

Generally they write code, and I am trying to not miss even a second!
If I try to write the code, I know it's gonna take forever, because I don't even know which files should I edit, but beside that, as I said, they are using 6-7 languages/frameworks that I'm not familiar with, and learning all these syntaxes at one is not easy.

How well the company prepared for engineers:

I can't say they are well organized, they kind of expecting me to start writing code immediately.

Taking notes, being proactive:

I'm always taking notes when they write a new command/or anything about data models.
My peers are very smart and kind people, and I'm trying to ask lots of questions, even lots of stupid questions sometimes.

Is this common?:

@Telastyn, thanks for your answers, it made me feel a little better. It seems like my problem is not that uncommon, but I was really productive before this job, and now I really feel useless and not smart.

I hope I can start solving bugs/implementing issues very soon.

About frameworks/languages they use:

I was really honest about that, I didn't say I know something that I don't know actually.
But I wasn't expecting that much different things, and since I started working at the day I accepted the offer, I didn't have time to prepare myself.

@Southpaw Hare, thanks alot for sharing your experience. You are absolutely right. There is no guarantee that I'm going to learn all of these stuff, but I'm trying.
At the end, it's is hard to learn all of the syntax at once, and I think that is the main problem too. Because I can navigate in ruby code well since I know that language, and I navigate in js codes thanks to browser inspectors, but the problem is writing the actual codes with the frameworks/languages I don't know.


答:
I dislike a lot this kind of language requirement.

I think python is a great language but this is keeping me away of it !

For those complaining about not or bad formatted code, I will say: use a code formatter !

I think that this restriction is more invasive than a rule about having parenthesis, using '.' or '->' for member access or using a ';' or a '.' to end a line.

Title: Do you find languages with indentation requirements cumbersome?

Body:
Thoughts on these?  Python is one example, and no this is not a stab against Python I like the language.

What languages have a indentation requirement?


答:
swing to the other extreme..   I worked at a company that had only 2-3 languages but it took the better part of a year before programmers were let loose on the code base, probably 1 or 2 months before they committed their first line of code.

Don't beat yourself up over it, if you were honest in the interview about your lack of knowledge on these platforms they knew what they were getting themselves into.  It takes time and time cannot be expanded, cut short or compressed, just make sure you make the most of it.


答:
Some amount of time is absolutely normal in order to get used to something so completely unfamiliar - I would not blame yourself or feel bad.  However, it's important to be willing to accept the possibility that this job may not be within your skillset.  This isn't necessarily the case, it's just worth leaving the possibility open in your mind.

The problem may not be in the codebase size, but in the fact that you do not know the languages involved.  In my own personal experience, I had a job at one company where I didn't know any of the languages being used in a rather extensive codebase.  Unfortunately, I wasn't ever able to learn this sufficiently after 5 months or so, and went to another company instead.  There, I was proficient at the primary language, and despite the codebase size being comparable, I've done quite well.

When it comes to learning new languages, people usually think it's easier than it actually is, and hold themselves to high standards of learning them quickly.  It's likely that it will take you longer than you think it will, so just keep that in mind regardless of what you decide.


问:
How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?

答:
One of the benefits of git is that it's peer-to-peer, so you don't actually need a master VCS, though many companies (including my own) do use github as a master repository.

You can assign access to individuals (either read only or read/write) and define individuals as administrators too, so you have a fair degree of access control.

Github does "hiccup" occasionally (angry unicorns) but is generally pretty stable, and we've never had any problems with data loss; but you do also have backup options


问:
Changing the license in a fork from GPL to GPL compatible?
I have forked a project that was released under the GPL and made substantial modifications, however there are still some parts and general ideas that are the same as upstream.

Due to user interest I am wondering how, if at all, I can relicense the project. Another developer and I have attempted to reach the upstream dev multiple times but he has never responded. Since there hasn't been updates in several years I'm considering the upstream project abandoned and looking at other options.

GNU lists Apache and Modified BSD as GPL compatible, which are 2 licenses that come up often and are less "viral" than the GPL. Since they are compatible can I Just relicense my project with either of those licenses?

If I am unable to do that, are there any options I have to change the license? It's important because there are several users who have software that is incompatible with the GPL, and therefore makes it impossible for them to adopt the project. I'm trying to avoid simply rewriting everything, which is hard since there's only a handful of good (or correct) ways to accomplish the project goals and I'd end up splitting hairs on what constitutes "derivative" code.

答:
Bad news, dude.

It isn't your code.  Only the owner of the code in question can relicense that code, and you are not the owner of the code in question.

You accepted the code under the terms of the GPL.  You modified it, and forked it, under the terms of the GPL.  You are now stuck with the terms of the GPL, and one of those terms is that you can't relicense it under some other license more to your liking.


答:
We have a closed-source project hosted in such a way.

It's pretty widely accepted that stealing source code won't get anyone too far (good article here). bitbucket and github make their living from closed-source, so they have a natural imperative to keep things as secure as they can (and minimize bad press).

One note is that every once in a while, the service goes down for a while - probably (IMO) caused by open-source traffic.

But overall, we've weighed the pros and cons, and are happy.

p.s.  If I'm not mistaken, github offers a "private cloud" instance for enterprise customers.

Title: How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?

Body:
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?


答:
So, is slower performance, of programming languages, really, a bad thing?

Everything else being equal, going faster is a good thing. After all, nobody really wants to wait longer for some results, and once that result is done it can free up resources for other things.

But not everything else is equal. For starters, it's also important to produce the right result, or at least right-enough. (If completely wrong results are allowed, you can produce those very quickly indeed and they will be of exactly zero value to anyone.) If a change to a somewhat slower language makes it more likely that the right result will be produced, that's typically a great trade-off. Higher-level languages have an advantage over lower-level ones here, as their richer set of models usually makes it easier to express a complex problem without overwhelmingly much explicit detail.

It's also usually important to manage the cost of producing the software in the first place, of adding new features as desired, and of keeping it working as the underlying systems change. Higher-level languages usually allow for faster programming turnaround, and there's a lot of value in keeping the costs of programming within budget. Indeed, keeping costs there down allows more different things to be achieved overall, which is generally a good thing.

The final key point to note is that it is not necessary to use just one language, and that many software systems have a majority of their components being not performance critical. Using a low-level language to produce high-performance components for the critical bits is sensible, while leaving the less critical parts to a high-level language (so as to minimize the cost of producing them) is eminently sensible. What's more, the features that make a good low-level language (the ability to control precisely what the machine does) are not the features that make a good high-level language (the ability to infer the details from much smaller descriptions): they are diametrically opposed, so being able to couple them together and use them for their strengths and avoid their weaknesses, that's a great thing indeed.

Which components should get the high-performance treatment? The optimization? Measure them. Profile them. Find the truth rather than guessing. Focus your effort where it does most good.

Title: Is slower performance of programming languages, really, a bad thing?

Body:
Here's how  I see it.

There's machine code and it's all that computers needs in order to run something. Computers don't care about programming languages. It doesn't matter to them whether the machine code comes from Perl, Python or PHP. Programming languages don't serve computers. They serve programmers.

Some programming languages run slower than others but that's not necessarily because there is something wrong with them. In many cases, it's because they do more things that programmers would otherwise have to do (i.e. memory management) and by doing these things, they are better in what they are supposed to do - serve programmers.

So, is slower performance, of programming languages, really, a bad thing?