问:
Algorithm to generate parallel path inside polygon
A path is defined as a list of 2D points (x,y) (and may be open or closed).

Given a path p, what is an algorithm which generates a path p' which is "inside" p and at constant offset to p i.e. each line segment of p' is parallel to the corresponding line segment of p.

答:
Well, this turns out to be non-trivial extension of Veldaeven's solution.

For each sequence of 3 points, calculate the 2 vectors between them, as suggested by Veldaeven.

Find the angle between the two vectors by adding the angles from the x axis - (nb do not use dot product which always returns an angle less than pi and hence is too symmetrical for our problem).

Halve this angle. This is the perpendicular bisector along which the resulting vector will lie.

Now to calculate which quadrant to draw the point in (the "which side" problem). Find the difference between the 2 vectors. If the gradient of this (i.e. the "double derivative") is positive then the path is going back on itself through a maximum: add pi/2. If the gradient is negative, the path is going through a minimum: subtract pi / 2

```<code>innerWallClockwise :: Float -> V2 Float -> [Point V2 Float] -> [V2 Float]

innerWallClockwise w acc (p : p' : p'' : ps) =

 let v = p' .-. p
  v' = p'' .-. p'
  d2v = v' .-. v
  phi = atan2 (v ^. _y) (v ^. _x)
  rho = atan2 (v' ^. _y) (v' ^. _x)
  theta = phi + rho
  d2vtheta = atan2 (d2v ^. _y) (d2v ^. _x)

  theta' = theta / 2 + if d2vtheta > 0 then pi / 2 else (-1) * pi / 2
  v''' = w *^ angle theta'
  v'''' = acc .+^ v'''
in
  if ps == [] then [v''''] else v'''' : (innerWallClockwise w (acc .+^ v') (p' : p'' : (head ps) : (tail ps)))
</code>```

Let's give it a simple rectangular path

```<code>let path=[P (V2 0 0), P(V2 0 5), P(V2 5 5), P (V2 5 (-5)), P (V2 0 (-5))]
</code>```

Try out our function:

```<code>innerWallClockwise 1 (V2 0 5) path

=> [V2 0.70710677 4.2928934,V2 4.2928934 4.2928934,V2 4.2928934 (-4.2928934)]
</code>```

Yes, the points are all inside the input path at a distance of sqrt(2) from the vertex.

NB all methods using e.g. the cross product of the two vectors are too symmetrical.

Hopefully this will help someone in the future.

Body:
Well, this turns out to be non-trivial extension of Veldaeven's solution.

For each sequence of 3 points, calculate the 2 vectors between them, as suggested by Veldaeven.

Find the angle between the two vectors by adding the angles from the x axis - (nb do not use dot product which always returns an angle less than pi and hence is too symmetrical for our problem).

Halve this angle. This is the perpendicular bisector along which the resulting vector will lie.

Now to calculate which quadrant to draw the point in (the "which side" problem). Find the difference between the 2 vectors. If the gradient of this (i.e. the "double derivative") is positive then the path is going back on itself through a maximum: add pi/2. If the gradient is negative, the path is going through a minimum: subtract pi / 2

innerWallClockwise :: Float -> V2 Float -> [Point V2 Float] -> [V2 Float]

innerWallClockwise w acc (p : p' : p'' : ps) =

 let v = p' .-. p
  v' = p'' .-. p'
  d2v = v' .-. v
  phi = atan2 (v ^. _y) (v ^. _x)
  rho = atan2 (v' ^. _y) (v' ^. _x)
  theta = phi + rho
  d2vtheta = atan2 (d2v ^. _y) (d2v ^. _x)

  theta' = theta / 2 + if d2vtheta > 0 then pi / 2 else (-1) * pi / 2
  v''' = w *^ angle theta'
  v'''' = acc .+^ v'''
in
  if ps == [] then [v''''] else v'''' : (innerWallClockwise w (acc .+^ v') (p' : p'' : (head ps) : (tail ps)))

Let's give it a simple rectangular path

let path=[P (V2 0 0), P(V2 0 5), P(V2 5 5), P (V2 5 (-5)), P (V2 0 (-5))]

Try out our function:

innerWallClockwise 1 (V2 0 5) path

=> [V2 0.70710677 4.2928934,V2 4.2928934 4.2928934,V2 4.2928934 (-4.2928934)]

Yes, the points are all inside the input path at a distance of sqrt(2) from the vertex.

NB all methods using e.g. the cross product of the two vectors are too symmetrical.

Hopefully this will help someone in the future.


问:
Changing coordinate systems in python
I am working on a visual python program that is meant to model the orbit of an electron around the core of a Hydrogen atom.  In order to avoid the singularity at r = 0 in the equation for coulomb force, I am modelling this scenario in semi-parabolic coordinates.  My question then is how can I change from cartesian coordinates to semi-parabolic coordinates within python?</p>

答:
I'd start with a pair of functions that converts from one coordinate system to another:

```<code>rho, tau = fromCartesian(x, y)
x, y = fromParabolic(rho, tau)
</code>```

I hope you have the formulas and won't have trouble implementing the functions.

Then you convert the coordinates where it's convenient. I suppose that you should read input values, convert to parabolic, do your calculations, convert back to Cartesian and output.

ContentLicense: CC BY-SA 3.0

Title: Changing coordinate systems in python

Body:
I'd start with a pair of functions that converts from one coordinate system to another:

rho, tau = fromCartesian(x, y)
x, y = fromParabolic(rho, tau)

I hope you have the formulas and won't have trouble implementing the functions.

Then you convert the coordinates where it's convenient. I suppose that you should read input values, convert to parabolic, do your calculations, convert back to Cartesian and output.


问:
Domain object model: query by id vs object
Let assume I have two simple model classes: Product and Brand

It is obvious I have a query method in Product  class like this

```<code>Product product = Product.findById(123);
</code>```

What if, I want to query products by brand?

```<code>ArrayList<Product> products = Product.findByBrand(234);
// or
ArrayList<Product> products = Product.findByBrand(new Brand("ABC", 234));
</code>```

Assume 234 is the brand ID in the database.

I assume the 2nd way of writing make the method more easy to test as I can mock the Brand class in my unit test, right?

答:
It's more than just whether you can mock a Brand object or not.

First, I'll assume your Product is really a Data Access Object, and not a simple Java Bean/DTO/POJO.

The real question to ask is, how long will this assertion hold?

Assume 234 is the brand id of the brand in database.

Will simple int values become long in the future, necessitating all methods interacting with a 'brand ID' to be changed from accepting an int to long? Will it become an alphanumeric, which might be possible to remain as an int (plausibly - if we're talking hexadecimals smaller than Integer.MAX_VALUE, and there is now a conversion method/utility somewhere to turn "AA" into 170) or will the whole type-changing parade enter the String phase?

The one slim benefit I can see for accepting an int is that you don't have to pay particular attention to a null input. Well, there's still the extremely odd chance of a null explicitly casted as an Integer and then getting auto-boxed, but you probably have other concerns then.


问:
Is APL a Turing-complete language?
On the Wikipedia page for APL, I haven't been able to find any mention of the language being Turing-complete, although it does (to my incomplete understanding of TC) appear to be capable of performing any possible calculation.

Can anyone elucidate?

答:
(elaborating on my comment)

In general, most programming languages and many domain specific languages are Turing-complete. In practice, you need to design a language very carefully to have it be non Turing-complete (hence, nearly all programming languages are Turing-complete). When someone tells you: this language Foo is not Turing-complete you need to be very suspicious and require a proof of that fact. For most programming languages, ask yourself about the Halting problem (if it applies, that language is Turing complete)

Look also for accidental Turing-completeness, it is amusingly instructive.

APL is Turing-complete because it has conditionals, branching, and recursive functions. It is also Turing complete because you could code in APL a Random-Access-Machine interpreter.

Notice that Turing-completeness is a theoretical abstraction. In practice, all our digital computers (and even the entire Internet) are finite state machines; they have a finite amount of memory, e.g. 1014 bits for most laptops in 2015, so a finite, but enormous, state space. Even the entire quantum universe could be viewed as a gigantic finite state machine (pan-computationism, Planck units, ...).

But viewing most computers (or programming languages) as finite state machines is inadequate for most purposes. The Turing machine model (or its equivalents) is often more adequate. Learn also the Rice's theorem. Read also J.Pitrat's blog which has some interesting views.

Notice also that time complexity & combinatorial explosion & computational complexity matters usually much more than Turing-completeness. A program giving a result in billion years is useless.

Title: Is APL a Turing-complete language?


问:
Is hiding complexity from API clients by merging resources a correct practice?
So let's say we have three simple resources: Groups, Users, and GroupUsers.

```<code>Groups - Represent interest groups which can be subscribed by users.
{
    name: 'Colorado Mountain Biking Group'
    ownerId: 1 (Some user)
}

GroupUsers - Represents the junction table in the many to many Groups - Users relationship. Group membership status and some other attributes are stored here.
{
    userId: 2,
    courseId: 1,
    color: '#FFFFFF',
    nickname: 'MBG Colorado',
    status: 'accepted'
}
</code>```

Since our API client will always handle the group from the perspective of the authenticated user, GET /api/groups/1 AUTH(userId=2) should return:

```<code>  Group (Includes GroupUser for authenticated user)
  {
      id: 1
      name: 'Colorado Mountain Biking Group'
      ownerId: 1,
      groupUser: {
          userId: 2,
          courseId: 1,
          color: '#FFFFFF',
          nickname: 'MBG Colorado',
          status: 'accepted'
      }
  }
</code>```

Someone suggested to me that our API Clients should not know or care about the junction table, all they should care about is the group, so I should instead respond with a merged resource like so:

```<code>  group (In reality group merged with groupUsers for the authenticated user.)
 {
      id: 1
      name: 'Colorado Mountain Biking Group'
      ownerId: 1,
      userId: 2,
      color: '#FFFFFF',
      nickname: 'MBG Colorado',
      status: 'accepted'
 }
</code>```

The problem I see with this (besides merging issues like repeated Id's and createdAt/updatedAt timestamps)is that the API clients will then use this same resource to further interact with our API endpoints.

If an API client wishes to update the groupUser resource he would:

```<code>PUT /api/groups/1
{
      id: 1
      name: 'Colorado Mountain Biking Group'
      ownerId: 1,
      userId: 2,
      color: '#000000',
      nickname: 'Some other value',
      status: 'accepted'
 }
</code>```

So now we would also need to scan request bodies and differentiate between group and groupUser attributes. Is the hassle worth it? Even when API consumers are other in-house developers?

答:
You are facing a trade-off between two design principles:

first, simplicity/consistency: your original approach has the advantage that the names and structure correspond better to your server-side structures, what saves you some mapping effort. For example, imagine you introduce a color attribute into the Group resource later. So your first approach now will create a naming conflict, which has to be solved in the mapping.

second, API design should primarily done from the viewpoint of the client, whatever serves him best. Following this principle, the second approach is better (as long as it works and the additional effort is not unreasonable).

So you have to make a decision on what is more important to you and your coworkers, in your environment. The first approach may produce a little bit more effort for someone else, the second a little bit more effort for you.


问:
Break big method into 2 methods, first containing a "for" loop and second a "break"
A method grew too big for its own good, and I need to break it up into two separate methods.

```<code>def big_method(dct):

    # Initial code
    # ...
    for i in dct:
        # More code
        # ...
        for j in dct[i]:
            # Inner code
            # ...
            # ...
            # and a break
            if j == 'something':
                break
            # Inner code ended here.
</code>```

The problem is that my first method will contain a loop, and the second method needs to contain a break:

```<code>def first_small(dct, second_method):
    # Initial code
    # ...
    for i in dct:
        # More code
        # ...
        for j in dct[i]:
            second_method()

def second_small(j):

    # Plenty of code
    # ...
    # ...
    # and a break
    if j == 'something':
        break
    # Inner code ended here.
</code>```

second_small() would raise a SyntaxError: 'break' outside loop.

To fix it, I can replace break in second_small() with a custom exception and make first_small() handle that exception, and break its loop when it finds it:

```<code>def first_small(dct, second_method):
    # Initial code
    # ...
    for i in dct:
        # More code
        # ...
        for j in dct[i]:
            try:
                second_method(j=j)
            except MyException:
                break

def second_small(j):

    # Inner code
    # ...
    # ...
    # and a break
    if j == 'something':
        raise MyException
    # Inner code ended here.
</code>```

However, I am not so sure this is the cleanest way to achieve that.

Question:

How should I split a method into two others, where first method will contain a loop and second has to break that loop?

答:
Forget the outer loop around for a moment, and think about the meaning of your method second_small, the abstraction it represents (I assume in your real code, you picked a more meaningful name). Then what you do in that method should depend on what

```<code> if j == 'something':
     ...
</code>```

means, in contrast to that abstraction. For example, if j == 'something' is a real error case, throw an exception. If it means "I successfully found the result of a search", use a boolean return value and return True. If it means "could not find it", return False. If it means "validation succeeded", return True.

A boolean return value might be also the better alternative if the condition means "might be an error, not sure, only the caller can decide". A boolean is probably the wrong alternative if you have to provide some kind of error message.

It should be clear in case of using a boolean, your code will finally look like this:

```<code> for j in dct[i]:
      if second_method(j):
            break

def second_method(j):
    # ...
    if j == 'something':
        return True
    # ...
</code>```

Body:
Forget the outer loop around for a moment, and think about the meaning of your method second_small, the abstraction it represents (I assume in your real code, you picked a more meaningful name). Then what you do in that method should depend on what

 if j == 'something':
     ...

means, in contrast to that abstraction. For example, if j == 'something' is a real error case, throw an exception. If it means "I successfully found the result of a search", use a boolean return value and return True. If it means "could not find it", return False. If it means "validation succeeded", return True.

A boolean return value might be also the better alternative if the condition means "might be an error, not sure, only the caller can decide". A boolean is probably the wrong alternative if you have to provide some kind of error message.

It should be clear in case of using a boolean, your code will finally look like this:

 for j in dct[i]:
      if second_method(j):
            break

def second_method(j):
    # ...
    if j == 'something':
        return True
    # ...


问:
const reference and const pointer. How do they work?
I read a post about how const storage works.

How does const storage work? (Item 2, Scott Myers Effective C++)

This says that each segment has separate section of write protected memory and const data goes there.

But what happens in case of references?
I want to understand three scenarios.

Global const reference.

const reference in method.

const reference in a class.

And for that matter pointers, I mean even though pointer can be stored in some write protected section, then how different versions of consts maintained.

such as

```<code>char x = 'z';
//following can not change the data of x, but ptr itself can change.
const char* ptr = &x;
char y = '9';
ptr = &y;
</code>```

above is allowed but following is not

```<code>char* const ptr1 = &x;
ptr1 = &y;
</code>```

How this is handled?

答:
Strictly speaking, const x merely asks the compiler to check at compile time that you aren't changing x after its initial definition. This does not imply any change to the runtime behavior of the program, or any requirement to store x's value differently. A smart compiler will try to take advantage of that for some optimizations, but in the general case the machine code it generates for a const value, pointer or reference may be exactly the same as for a non-const value, pointer or reference. The only distinction between const char* and char* const is that the compiler performs a different check.

In fact, the main optimization here is not putting "const variables" in the static read-only program memory, but putting literal values there. In the sample you gave, the 'z' and the '9' characters are likely to exist somewhere in the compiled binary, regardless of what variables you did or did not use the const keyword on. If you use longer strings, you should be able to find them in the binary quite easily with a hex editor.

When you assign that literal to const x, the compiler will probably try to perform the additional optimization of not representing x as a separate location in memory, and instead interpreting all reads of x as reads of that literal value in the program code. But it would probably try to do that even if x happened to be non-const, since it can still see that you never assign anything to it (if it didn't, it wouldn't be able to enforce x's const-ness when you do declare it const). And it's probably also storing some intermediate values in CPU registers to avoid reading from any memory at all, so the actual machine code will vary pretty wildly.

It's worth noting that a lot of C++ features work the same way. A class method being private is also "just" a compile-time check.


问:
In javascript, should object properties be declared on top of the function?
I learned that it's good practice to declare variables before they are used. For example:

```<code>function myFunction() {
  var i;
  var j;
}
</code>```

Does the same thing go for object properties, and is there a usual way/best practice for doing it? Because sometimes we don't know values of all properties when we declare the object. But if we don't declare them upfront (and set to null for example), it seems we can easily lose track of what's contained in the object:

```<code>function myFunction2() {
  var car = {};

  // some conditional code here fetching car data
  car.make = APIResponse.car.make;
  car.color = APIResponse.car.color;
  // even more code, before we can know another car property
  car.isLemon = isLemonAPIResponse;
}
</code>```

Should it be instead something like:

```<code>function myFunction2() {
  var car = {
      make: APIResponse.car.make, // we can get this value right away so why not assign it
      color: APIResponse.car.color, // same here
      isLemon: null // this will be true or false once we find out, null means it's not set
  };
}
</code>```

Or should it be some other way?

答:
There is no "correct" way of doing this as either will work just fine.  It depends entirely upon what makes your code the easiest to write, understand and maintain.

If  I already know the values of object properties at the time of declaration of the object, I find it generally makes the code a bit more self describing if I just put the known properties inside the initial object declaration.

If, on the other hand, a property name might need to be computed or there's significant code involved in figuring out what a property value might be, then I find the code is cleaner if I assign the property later in the function.


答:
There are two aspects to the const in C++:

logical constness: When you create a variable and point a const pointer or reference to it, the compiler simply checks that you don't modify the variable via the const pointer or reference, directly or indirectly. This constness can be cast away with a const_cast<>. As such, the following code is perfectly legal:

```<code>char myString[] = "Hallo Welt!";    //copy the string into an array on the stack
const char* constPtr = myString;
const_cast<char*>(constPtr)[i] = 'e';    //perfectly legal
</code>```

physical constness: When you create a variable in static storage that is const, you allow the compiler to put in into non-writable memory. It may do so, or it may not. As far as the standard is concerned, you are simply invoking undefined behavior if you cast away constness to modify such an object. This includes all string literals, so the following code may or may not work:

```<code> const char* myString = "Hallo World!";
 const_cast<char*>(myString)[1] = 'e';     //Undefined behavior, modifying a const static object!
</code>```

Title: const reference and const pointer. How do they work?

Body:
I read a post about how const storage works.

How does const storage work? (Item 2, Scott Myers Effective C++)

This says that each segment has separate section of write protected memory and const data goes there.

But what happens in case of references?
I want to understand three scenarios.

Global const reference.

const reference in method.

const reference in a class.

And for that matter pointers, I mean even though pointer can be stored in some write protected section, then how different versions of consts maintained.

such as

```<code>char x = 'z';
//following can not change the data of x, but ptr itself can change.
const char* ptr = &x;
char y = '9';
ptr = &y;
</code>```

above is allowed but following is not

```<code>char* const ptr1 = &x;
ptr1 = &y;
</code>```

How this is handled?

Body:
There are two aspects to the const in C++:

logical constness: When you create a variable and point a const pointer or reference to it, the compiler simply checks that you don't modify the variable via the const pointer or reference, directly or indirectly. This constness can be cast away with a const_cast<>. As such, the following code is perfectly legal:

char myString[] = "Hallo Welt!";    //copy the string into an array on the stack
const char* constPtr = myString;
const_cast<char*>(constPtr)[i] = 'e';    //perfectly legal

physical constness: When you create a variable in static storage that is const, you allow the compiler to put in into non-writable memory. It may do so, or it may not. As far as the standard is concerned, you are simply invoking undefined behavior if you cast away constness to modify such an object. This includes all string literals, so the following code may or may not work:

 const char* myString = "Hallo World!";
 const_cast<char*>(myString)[1] = 'e';     //Undefined behavior, modifying a const static object!


答:
Neither is inherently better than the other. Use whichever one is more readable.

In your example, where you can get all the values immediately and construct the object in a single object literal expression, I see absolutely no reason not to do just that. If getting each property was a non-trivial exercise, or there are many properties the final object may or may not have, or there are objects within objects, then I'd be more inclined to start with var x = {}; and fill it in one property at a time.

It's important to point out that the reason people recommend declaring variables at the top of the function in Javascript is because of variable hoisting. In a nutshell, that means any variable declaration inside a function is effectively "hoisted" to the top of the function without you knowing about it. Personally, I still prefer to declare my variables in the scope where I actually use them, much like in C++, but at work we have linters like JSHint that will shout at me if I accidentally write code that refers to that variable outside the block scope I declared it in, or if I redeclare it in another block scope (a typical example would be writing two for loops that both start with var i = 0;), so in practice I never get bitten by this issue.

Because object members are not variables you declare, but rather properties of a variable, hoisting does not affect them in either of your examples, so it has no bearing on how you should construct your object. Only if you were constructing your object like var x = {}; var a = 2; x.prop = a; would "hoisting of members" become an issue.

Title: In javascript, should object properties be declared on top of the function?

Body:
I learned that it's good practice to declare variables before they are used. For example:

```<code>function myFunction() {
  var i;
  var j;
}
</code>```

Does the same thing go for object properties, and is there a usual way/best practice for doing it? Because sometimes we don't know values of all properties when we declare the object. But if we don't declare them upfront (and set to null for example), it seems we can easily lose track of what's contained in the object:

```<code>function myFunction2() {
  var car = {};

  // some conditional code here fetching car data
  car.make = APIResponse.car.make;
  car.color = APIResponse.car.color;
  // even more code, before we can know another car property
  car.isLemon = isLemonAPIResponse;
}
</code>```

Should it be instead something like:

```<code>function myFunction2() {
  var car = {
      make: APIResponse.car.make, // we can get this value right away so why not assign it
      color: APIResponse.car.color, // same here
      isLemon: null // this will be true or false once we find out, null means it's not set
  };
}
</code>```

Or should it be some other way?


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
Far from being evil, the ternary operator is a godsend.

It is most useful when you want to make a decision in a nested expression.  The classic example is a function call:

```<code>printf("I see %d evil construct%s in this program\n", n, n == 1 ? "" : "s");
</code>```

In your particular example, the ternary is nearly gratuitous, since it is the top-level expression under a return.  You can lift the conditional out to the statement level without duplicating anything other than the return keyword.

N.B. Nothing will ever make that particular algorithm for median easy to read.

Title: Ternary operator considered harmful?

Body:
Far from being evil, the ternary operator is a godsend.

It is most useful when you want to make a decision in a nested expression.  The classic example is a function call:

printf("I see %d evil construct%s in this program\n", n, n == 1 ? "" : "s");

In your particular example, the ternary is nearly gratuitous, since it is the top-level expression under a return.  You can lift the conditional out to the statement level without duplicating anything other than the return keyword.

N.B. Nothing will ever make that particular algorithm for median easy to read.

ContentLicense: CC BY-SA 2.5


问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答:
It depends on the language implementation of exceptions. Exceptions allow you to take some action to prevent damage to data or to cleanly release resources in the event your system enters an unanticipated state or condition. This is different from error handling which are condition you can anticipate. My philosophy is that you should have as little exception handling as possible. It's noise. Can your method do anything reasonable by handling the exception? Can it recover? Can it repair or prevent further damage? If you are just going to catch the exception and then return from the method or fail in some other harmless way then there was really no point in catching the exception. You would have only added noise and complexity to your method, and you may be hiding the source of a fault in your design. In this case I would let the fault bubble up and be caught by an outer loop. If you can do something such as repair an object or mark it as corrupt or release some critical resource such as a lock file or by cleanly closing a socket then this is a good use of exceptions. If you actually expect the NULL to show up frequently as a valid edge case then you should handle this in the normal logic flow with if-the-else or switch-case statements or whatever, not with an exception handling. For example, a field disabled in a form may be set to NULL, which is different than an empty string representing a field left blank. This is an area where you must use good judgment and common sense. I have never heard of good solid rules of thumb for how to deal with this problem in every situation.

Java fails in its exception handling implementation with "checked exceptions" where every possible exception that might be raised by objects used in a method must be caught or declared in the "throws" clause of the method. The is the opposite of C++ and Python where you may choose to handle exceptions as you see fit. In Java if you modify the body of a method to include a call that may raise an exception you are faced with the choice of adding explicit handling for an exception that you may not care about thus adding noise and complexity to your code, or you must add that exception to the "throws" clause of the method you are modifying which not only adds noise and clutter but changes the signature of your method. You must then go an modify code wherever your method is used to either handle the new exception your method now may raise or add the exception to the "throws" clause of those methods thus triggering a domino effect of code changes. The "Catch or Specify Requirement" is must be one of the most annoying aspects of Java. The exception exception for RuntimeExceptions and the official Java rationalization for this design mistake is lame.

That last paragraph had little to do with answering your question. I just hate Java.

--
Noah


问:
Is is possible to write a "Brainfuck with variables" compiler?
I'm on a quest to write a LISP-ish language that compiles to Brainfuck. Well, it's a stack of intermediate compilers actually. Currently I'm trying to write the one that transforms this code:

a++b+a

into:

++>+<

It's standard Brainfuck, but with variables added.

The compiler is responsible for two things:

Assigning a and b some address in the memory, say, 0 and 1

Translating each occurrence of a and b into a number of <'s or >'s so the memory pointer ends up at the right location

Now, here's the thing: in order for the compiler to know how many <'s to put, it needs to know where the memory pointer currently points to. At first it points to 0, but as the code gets executed, the pointer moves around and to get to a you need to move relatively from where you're at.

So the only way to know the value of the memory pointer would be to execute the code and replace variable names as you go. "Oh, mempoint is now 4, I see an a and it's location is 1 so i need to move three places left: <<<"

If I close my eyes I can hear a voice saying: "you're trying to solve the Halting Problem"

So my question is: am I really? Is there any way around?

答:
It depends on whether you want to replace < and > with variables or really add variables to the language. In the first case, you probably lose Turing completeness (because you only have finitely many memory cells). It may remain Turing complete if each cell can hold arbitrarily large values, but honestly I'm not sure.

Anyway, if there are no < and > operations, the translation is simple: You know which variable the code last accessed so you just need to compare the addresses of the previous and next variable. Only loops are a bit tricky, because with code like a+[b+] the current cell might be either a or b, both in the loop body and after the end of the loop. One simple workaround is forcing all paths to end on the same cell, i.e., rewriting the code to a+[b+a] or a+b[b+] (which could be simplified to a+b[+]).

If bare > and < remain available in your source language, then things are more tricky. As a comment points out, Brainfuck is Turing complete so you can just build an equivalent program with enough complication, but a simple and efficient translation may not always be possible. Statically determining the current cell at any given point generally requires knowing the trip count of all loops up to that point. Even ignoring the potential reduction from the Halting problem (I'm not convinced that that actually applies here), the trip count and thus the memory location frequently depends on the input, i.e. can not be predicted statically even by an oracle machine.


问:
Do common relational database systems work 'out of the box'?
I'm quite new to software development and whenever I come across small projects which involve storing (relational) data I always ask myself if something like a micro-blog (or any other project with few users that stores few types of data) really need 'big' RDBMS like MySQL/MariaDB, PostgreSQL or even SQL Server, DB2 or Oracle (of course I didn't use the latter 3 but the former 2 seem very wide-spread even with very little applications).

If you look at the feature matrix of any of those software packages, it is usually massive and overwhelms me a little bit.
I basically want to create a database, a bunch of tables, one or two users with specific rights to access them and that's it.

But after looking up documentation, I'll find things like 'Cascading streaming replication', 'Foreign data wrappers' or 'Materialized views with concurrent refresh' and much, much more and that always gets me thinking whether I should really read up on those things, tweak my complete configuration file and especially if those features pose a possible security threat when I don't disable them or don't know how to use them.

Basically, the whole thing just doesn't seem like it was 'made for me' and my small micro-blog, but big corporations with tons of systems and modules which need to interact with each other and exchange data in multiple formats, etc.

Of course, there is sqlite but when I last looked it seemed like it didn't support concurrency and therefore is quite unsuitable for web applications.

答:
The database is a framework. How much you need advanced features depends on your business needs. For what you've described in terms of needs, you need SQL tables, but not the long list of other things you mention.

Start small and simple is the way to go.

Think of it as building scaffold. For a shed a few 4x4's does the trick, though only provides a frame, not a roof, shelves, etc. For a high-rise building the scaffold includes a ton more engineering features to pay attention to - but it's still a framework and not finished habitable space.

SQLite is fine for a small database with one or two users unless they are pounding on it in some heavy way. If you use a provider for this stuff you can just rely on their stuff. For instance, a Ruby on Rails application running on Heroku uses PostgreSQL.


问:
What is the explication for the difference execution time for the same instruction?
As you know when we run instruction in our code

like long a = b;

we will not have the same ticks each to be executed.

first exeution it take 2ticks;

second exeution it take 3ticks;

third exeution it take 2ticks;

It depends for memory state, caches, instruction pipeline, branch prediction.

For the memory state:

We will have different time execution because  the state of memory is not the same for situation 1,2,3,.. OS can do the allocation in 2 tick and next time it will need more time like 3 tick because lot of program change the state of the memory.

The example above was one of examples which they change the execution time, their are other examples that i need to understand,
like how can caches, instruction pipeline, branch prediction effect this variation.

Please can someone explain it to me.

And also I need to know if the time of affected by each operation is the kernel time or user time for the process which execute the instruction.

答:
Modern CPUs don't do one instruction at a time. Instead, they might be decoding one group of instructions while an earlier group are waiting for dependencies and waiting to be sent to execution units, while even earlier instructions are being executed, while even earlier instructions are being retired (committed to state).  It's (literally) a pipeline of stages where many instructions are "in flight" at various stages at the same time.

How long an instruction takes depends on so many different things (what it depends on and when those dependencies are satisfied, what else is happening at each stage in the pipeline as it passes through). This is what causes the variability in how long an instruction takes.

For instructions that read from memory things get more complicated - in addition to everything else, they also depend on how quickly the data can be obtained, which depends on where the data has to come from (a very close store forwarding buffer, a close L1 data cache, a nearby L2 data cache, ..., all the way through a quickpath link to a memory controller that's able to talk to the actual RAM chip) and also depend on things like bandwidth utilisation along the paths the data needs to take (e.g. if the RAM chips are flat out handling something else, then you're going to have to wait your turn).

On top of all of that; there's higher level things to consider. If an instruction reads or writes to memory, then maybe that causes TLB miss and the CPU has to do a page table walk. Maybe the TLB miss becomes a page fault and the OS's kernel has load data from a memory mapped file. Maybe the memory mapped file is on an networked file system. Maybe the network connection has a high number of packet errors. Maybe it takes a full 10 seconds for all of this to happen before the instruction is retried and is able to complete.


问:
Orgmode file format license
Orgmode is an emacs plug-in and is under GPL. I am developing an application that uses plain text files to store notes and I do like the org mode file format. I am not going to copy any of the orgmode code.

Do I have to use GPL for my application if it uses a (subset of) orgmode file format? Currently I'm using MIT license.

答:
As far as I know, the GPL is for licensing code in source and binary formats, not the formats of data files manipulated by said code.

An instructive example is GCC. GCC is licensed under the GPL, but the source code that goes into it and the binaries that come out of it are not affected by that license (its version of the GPL even has a special exception to allow linking against its runtime library). So normally its license only comes into play if you want to change GCC or make a program using the code in GCC.

There is such a thing as a "patent-encumbered" file format. This most famously applies to audio and video file formats like MP3 and MP4 where the inventor(s?) spent a heck of a lot of R&D money figuring out the compression algorithms used by those formats. But in these cases the use of the format doesn't force you to change your license, it forces you to give the patent holders money (if you exceed certain usage thresholds).

All-in-all, I would be very surprised if a file format for a plugin for free software had any "infectious" license/patent/whatever. But there may be political/social/cultural reasons to use GPL (for all we know the author of the plugin may have strong feelings about free-as-in-speech software and copyleft licensing). You're probably fine using MIT, but IANAL, and it can't hurt to ask the orgmode author directly.

Title: Orgmode file format license


答:
This question is too broad; there are too many factors that could contribute to the fluctuations in the time taken to execute some source code.

The poorly-written question also doesn't help - it is unclear whether the asker is more interested in knowing the possible factors that affect nanoscopic performance (on the order of 1 - 10 CPU instructions) or macroscopic performance (on the order of millions to billions of CPU instructions, i.e. on a timescale that is perceivable and relevant to a human).

Therefore, despite me trying to write an answer (to cover some factors that hasn't been mentioned so far), this question still has my downvote.

Because of a knowledge gap, no amount of explanation is going to help. The asker is encouraged to borrow a copy of this book from a local library or close friend:

Computer Architecture, Fifth Edition: A Quantitative Approach (The Morgan Kaufmann Series in Computer Architecture and Design)

The factors listed below are patently non-exhaustive. There are infinitely many factors, including CPU temperature throttling, which could arguably be influenced by cosmic rays raining down on your computer or a butterfly flapping wings on the other side of the Earth.

This dry humor is intended to soften the emotional damage from the harsh words in this answer.

Some factors that contribute to fluctuations in the execution time on the nano-scopic level:

A bubble in the pipeline (en.wikipedia.org)

A bubble can be caused by anything - anything deemed by the designers of the CPU that would prevent the next instruction from being executed immediately. Examples are: all execution units are busy; the input value to the instruction is still being computed (by a previous instruction), the input value is still being loaded from memory and hasn't yet arrived, etc.

Design limitations (imperfections) in superscalar architecture

In an ideal world, a superscalar architecture should be able to schedule up to the theoretically optimum. In practice, sometimes it might generate a bubble despite having the input values and execution unit available. This is due to imperfection of the design.

The CPU running at a different (fluctuating) frequency than the clock

Thanks to the creativity and resourcefulness of CPU vendors, a CPU can run somewhat faster, or somewhat slower than the advertised "normal speed", depending on the workload of the CPU.

But isn't the clock supposed to run at the same frequency as the CPU's execution units?

No. Most new CPUs implement something called Invariant TSC, which means the TSC (the highest-resolution timer you'll find on a computer, specifically on the CPU) will run at a constant (advertised) frequency, unaffected by the frequency fluctuations of the execution.

Cache, as pointed out in the other answers.

I need to do a nano-benchmark, and I want my results to be comparable and repeatable. How to I minimize these nanoscopic fluctuations?

Turn off the frequency scaling features of the CPU when you conduct your benchmarks.

This may require restarting the computer for the changes to take effect.

Cache Warm-up.

Take a look at the disassembly (CPU instructions) that are being generated, to get a sense of how it will play out with the superscalar architecture. Unfortunately, you can only get a fuzzy insight from this, and typically you have no influence over how such low-level machine code is generated or executed.

The CPU vendor may have tools that help gather insights such as cache misses and/or CPU pipeline stalls (bubbles).

Some factors that contribute to fluctuations on the microscopic level:

Just-in-time compilation (as opposed to ahead-of-time compilation) if your test code is written in a managed language (such as C#, .NET, Java, or many other high-level languages).

Some factors that contribute to fluctuations on the milli-scopic level:

Context switching

Open up the task manager (on Windows or Ubuntu), or top (on Linux command-line), and you will see many background processes running in the operating system in addition to your test code.

(You might need to flip a switch to see "all background processes".)

Once a while, your test program will be interrupted (or preempted), which means it will take a pause from execution, and the CPU will be told by the OS to execute something else instead.

If your test code is very CPU intensive, it will occupy a very high percentage of the CPU's time, but still it will not be a full 100 percent. It might be more like 95 - 98 percent.

Title: What is the explication for the difference execution time for the same instruction?

Body:
As you know when we run instruction in our code

like long a = b;

we will not have the same ticks each to be executed.

first exeution it take 2ticks;

second exeution it take 3ticks;

third exeution it take 2ticks;

It depends for memory state, caches, instruction pipeline, branch prediction.

For the memory state:

We will have different time execution because  the state of memory is not the same for situation 1,2,3,.. OS can do the allocation in 2 tick and next time it will need more time like 3 tick because lot of program change the state of the memory.

The example above was one of examples which they change the execution time, their are other examples that i need to understand,
like how can caches, instruction pipeline, branch prediction effect this variation.

Please can someone explain it to me.

And also I need to know if the time of affected by each operation is the kernel time or user time for the process which execute the instruction.


答:
They do work out of the box, for the most part, but you do have to know how to use them.  They don't come pre-populated with your application's data model, because they don't know what that is, so they're a blank slate, in that respect.

SQLite will support small to medium websites with nominal concurrency and relatively low traffic, which describes probably 95 percent of all websites out there.  If you're still uncomfortable using SQLite, Postgresql gives you an industrial-strength database in an executable that's about 50MB in size.  Most of the major database vendors have a "lite" version, but that's really just the full-sized version with some artificial limitations imposed.

You don't need to know everything there is to know about a database in order to make full use of it.  How many of the features in your favorite high-end spreadsheet or word processor do you actually know & use?  Maybe 10 percent of them?

In short, databases are cheap enough that most applications with non-trivial data needs can make very good use of them.

Title: Do common relational database systems work 'out of the box'?

Body:
I'm quite new to software development and whenever I come across small projects which involve storing (relational) data I always ask myself if something like a micro-blog (or any other project with few users that stores few types of data) really need 'big' RDBMS like MySQL/MariaDB, PostgreSQL or even SQL Server, DB2 or Oracle (of course I didn't use the latter 3 but the former 2 seem very wide-spread even with very little applications).

If you look at the feature matrix of any of those software packages, it is usually massive and overwhelms me a little bit.
I basically want to create a database, a bunch of tables, one or two users with specific rights to access them and that's it.

But after looking up documentation, I'll find things like 'Cascading streaming replication', 'Foreign data wrappers' or 'Materialized views with concurrent refresh' and much, much more and that always gets me thinking whether I should really read up on those things, tweak my complete configuration file and especially if those features pose a possible security threat when I don't disable them or don't know how to use them.

Basically, the whole thing just doesn't seem like it was 'made for me' and my small micro-blog, but big corporations with tons of systems and modules which need to interact with each other and exchange data in multiple formats, etc.

Of course, there is sqlite but when I last looked it seemed like it didn't support concurrency and therefore is quite unsuitable for web applications.


答:
Basically, the whole thing just doesn't seem like it was 'made for me' and my small micro-blog

I think, this is the basic statement here.

Although your question is about Do common relational database systems work 'out of the box'?, what you are looking for is more: do I need a full featured DB for microblogging?. And there is a clear answer: No, you don't. Take a look at Static Websites and Static Site Generators. Historically, blogging was made famous with Wordpress, which is written in PHP - a very common programming language for Websites - which in turn is mostly accompanied by MySQL. This is a mere coincidence and there is no causality to say: blogging is only possible with a database.

Of course, it gives you some nice features: Your posts are data and as such queryable in every form. But on the other hand, just for microblogging it is totally overkill.

I am personally very fond of Jekyll. Perhaps, you have a look!

As far as the point of batteries included goes: If you are using a typical hosting package from a hoster of your choice, MySQL or every other DB offered is readily configured.

If you plan to host your blog yourself or run a Cloud box, e.g. one at Digital Ocean, then you have to install and configure the DB yourself; which is typically not what you want, if you only want to microblog; since there are many security implications. You have to know, what you are doing.

tl;dr

Do common relational database systems work 'out of the box'?

Yes, they work out of the box, but have to be configured properly in security terms

Basically, the whole thing just doesn't seem like it was 'made for me' and my small micro-blog

Yes, you are better off with static sites.


问:
Should I be looking for developers with specific skill sets or generalists that need to learn?
Thanks to the great help of this site and SO, I've been able to make a prototype of a software I want to sell but unfortunately although the prototype works I think my code quality is very low. I didn't use much OOP or design patterns so although my code is understandable to me, I think a normal developer would faint if they had to read it.

So I wanted to hire a developer to make it a bit more better quality and improve some of my implementations of API's that I may have not done correctly.   I'm having problems hiring a developer though.

I have met 2 developers and had them read my software specs.The problem is, they lacked my business's domain knowledge(which is completely understandable and no biggie) but they also lacked knowledge of the underlying tech systems I used such as Hadoop, Hbase, Cuda, etc..I spent alot of time explaining map/reduce, bigtables and other technologies I used. I thought it was common knowledge because of my interactions with people on this site but the people I met with mentioned they never had to deal with these things so they didn't know it.

My question is, for software projects that are hiring contractor developers is it a danger if the developer does not have experience with the underlying technologies? or can a general developer who is accomplished in another area realistically pick up new technologies?  I did a very very quick back of envelope calculation and I think the upfront costs would be similar if I hire a student or developer with no experience in my technologies who will work many hours versus hiring a highly experienced developer who charges double but finishes in half the time but what other risks should I be considering or worried about?  Also, should if I do hire a generalist, should I be paying for the time it takes them to learn hadoop or cuda if they are contractors(seems to make business sense but not sure how fair it is to them if they do not use the skill again).

I'm a bit confused so any suggestions would be great.

答:
It is hard to give advice on this. Only some thoughts:

I think the upfront costs would be similar if I hire a student or developer with no experience in my technologies who will work many hours versus hiring a highly experienced developer who charges double but finishes in half the time but what other risks should I be considering or worried about?

Form what you have written in your introduction:

my code quality is very low

I didn't use much OOP

I wanted to hire a developer to make it a bit more better quality and improve some of my implementations

Answering this should be a no-brainer:

If you hire a developer with no experience, it is very unlikely, that you are able to increase code quality. A programmer with no experience is no help.

Although it might be cheaper in the short run, to hire a novice, you are paying later!

what other risks should I be considering or worried about?

Do not make the mistake to calculate only the costs, to get you and your product up and running. More important are the costs of maintenance.

As a direct consequence, of what I said in the previous paragraph, you have to consider, what is called Technical Debt. As you said: the codebase is in no good shape - so to say, there is already technical debt. And with hiring unskilled workers, you are increasing the debt. Perhaps in some years from now, you end up with an unmaintainable codebase and have a) to start over again and b) loose eventually customers, which equals in both cases: loss of money.

Also, should if I do hire a generalist, should I be paying for the time it takes them to learn hadoop or cuda if they are contractors(seems to make business sense but not sure how fair it is to them if they do not use the skill again).

Clearly: Yes! I do not see any reason, not to do this. They need the knowledge, you need them to have it - so: yes.

If they are good developers, they should easily get grips on new - or at least new to them - technology. Chances are high, that if they take their job seriously, they have technologies on their radar, meaning, they do not actually have done anything productive with the technology, but know the how and when- to use it.

I have to admit, having no knowledge of Hadoop for myself, but I know, when it might be a good solution and have a fair understanding on how it works in theory; so I would say, that it should not take long to get me productive.

I have met 2 developers and had them read my software specs.The problem is, they lacked my business's domain knowledge(which is completely understandable and no biggie) but they also lacked knowledge of the underlying tech systems I used such as Hadoop, Hbase, Cuda, etc..I spent alot of time explaining map/reduce, bigtables and other technologies I used.

To explain your business should be the easiest part for you, since you know best. You can not expect everyone to know your business as good as you or even know it at all.

The same goes for technology:

There are a bazillion of frameworks, languages, toolkits out there - it is unlikely to find (m) any developer(s) knowing them all

Of course you could say: $Technology_du_jour is hyped in the media, so I expect every developer having a working knowledge. But that is not the reality.

For me as a developer my job is a tradeoff: I have a working knowledge of some languages and some technolgies. This makes me flexible in many ways. If I have to, I am able to develop an in-depth-understanding of my current tools, but as seasons go by, tools and languages do.

tl;dr;

1) If you can, hire an expert in your domain and in the desired technology

2) If you can't,

2a) Look for a generalist with some project expertise, which may or may not have knowledge of the used technologies in your project

3) If there is really, really nobody else: hire a student.

You have technical debt, do not increase it!


问:
Can relational database tables always be topologically sorted by their FK reference relation?
Suppose I have some conceptual, not physical, E-R diagram describing a relational database. I want to sort all the tables in the database using a topological sort, where the partial ordering between tables is Table 1 has a foreign key onto Table 2.

When clearing out tables after putting test data in them, I would need to delete Table 1 above first, then Table 2, in order to not violate FK references. A topological sort on the FK relation gives me an ordering to clear the tables in.

It is possible to have a table with an FK to itself, providing a simple counter example where there is a cycle, and subsequently no topological sort. However, this self relationship could also be represented using a join table, which lists 2 rows of the table, where one refers to the other, and in this case there would be a topological sort.

By replacing direct FK references between tables with join tables, is it always possible to arrive at a structure that can be topologically sorted?

答:
It seems to be me that you can trivially get rid of the cycles by moving all foreign keys to join tables.

Once you've move all foreign keys to join tables, none of the original tables have dependencies on anything. The join tables have dependencies on the original tables. Nothing has dependencies on the join tables. In consequence, you have a trivial topological sort: first the join, then the original tables.

Under no circumstances should you actually contemplate doing this. You are massively complicating your data model without much benefit.

When clearing out tables after putting test data in them, I would need
  to delete Table 1 above first, then Table 2, in order to not violate
  FK references. A topological sort on the FK relation gives me an
  ordering to clear the tables in.

If you really need to clear out test data like this, you can do the following:

Set all foreign keys to NULL

Delete everything

But you should consider some other alternatives:

Can you do everything inside a transaction that simply lets your rollback when you are done?

Can you create and populate a temporary database that you can simply throw away when the test is done?


问:
How to design for good abstractions using algebraic data type?
Every now and then I have peaked at Haskell Tutorials and found the Algebraic data types quite interesting. I took their purpose to be to represent types that have completely separable states. Sadly, I never got to write more Haskell than tutorial level projects, and so I never had to really design programs using this pattern.

Now I am writing some Rust, and I have algebraic datatypes (enums) in the toolbox. However, I am not very confident in using them.

Let me start with an example where I am confident that such an enum is a proper choice.

```<code>enum Tree {
    Leaf(i: String),
    Branch(Tree, Tree)
}
</code>```

The same example would be applicaple for an XML-like structures, etc.

With other data, I am not so confident about using enum types. Let's take a connection object

```<code>enum Connection {
    UnConnected(...),
    ConnectedConnection(....)
}
</code>```

Here we would have a Connection type with two possible values, one representing the state where a connection is not yet established, the other one could represent the state of a connected connection (and wrapping a connection handle for example).

The other possibility would be to introduce 2 types for a Connection-Template and a connected connection.

Another example that I found in rust code is that in the hyper library. There is the type Response that represents a HTTP response. It is a generic type.
Response<Fresh> represents the state where headers are not yet frozen. Once upon it is mapped to a Response<Streaming>, which can be used to write the body of the response. It seems like what Hyper models here with different types (Response<Fresh> vs Response<Streaming>) could have been modeled with enum types as well.

The approach with different types allows for more safety, Response<Fresh> does not implement streaming (I think) and Response<Streamimg> does.

Do you know of guidelines and best practices that guide through modelling logic in types properly?

答:
Do you know of guidelines and best practices that guide through modelling logic in types properly?

Sure, at least in theory.

Algebraic Data Types are made of two parts, sum types (or variants, or discriminated unions, or...) and product types (or tuples; conceptually records and classes fall here, but some disagree).

Product Types are used when you need and. Do you need a username and a password? Make a product type of a string and another string. Do you need a date and a time? Make a product type that combines the two. Tuples are ordered pairs of things, records and classes are unordered but accessible by name - but the concept is the same as far as design goes.

Sum Types are used when you need or. Do you need a leaf or a full tree? Sum type. Do you need a stream of data or an error? Sum type.

So when you're modeling what sort of data is legal to/from a function or into a variable, keep those concepts in mind. If you just need some value, use a plain old type. If you need one value and another? Product Type. If you can have one value or another (but not both)? Sum Type. Some combination (like the tree above)? Some combination.

Best practices will vary from language to language. Many languages don't make Sum Types readily available (beyond nullable values), or awkward to work with. Many languages prefer you use built-in collections for simple product types (because they're well optimized). But the concepts largely hold once you learn how your language wants you to encode them.


问:
Would implementing a "Throwable Event System" be abusive?
I have been thinking for a couple years now about using Throwable events and implementing a sort of event system that uses throw to dispatch an event, or let a different method handle it with throws.

The only problem is, Throwable is reserved for Errors and Exceptions. A google search shows zero (relevant) results on something like this. I'm assuming this is completely original or in the minority of event systems out there.

I know that the C# event system is similar to my idea (though I've never used it, only seen code fragments).

The question here is would it be abusive to create an event system that uses try-catch statements and throwables, which are really made for error handling? And would there be performance issues compared to a "vanilla" interface-Listener-with-Event-object event system?

Regardless, I will probably make an event system using this idea just to try it out (a little exercise).

I have made two examples. One of which uses "vanilla" event system, the other uses Throwables.

Vanilla:

```<code>public class Entity implements EntityListener {
  @Override
  public void entityEvent(EntityEvent e) {
    //...
  }
}

public interface EntityListener {
  public void entityEvent(EntityEvent e);
}

public static void main(String... args) {
  new Entity().entityEvent(new EntityEvent());
}
</code>```

Throwable:

```<code>public class Class1 {

  public void logicalThrow() throws ThrowableEvent, HelloEvent, LogicEvent {
    if(something)
      throw new ThrowableEvent();
    else if (sayHello)
      throw new HelloEvent();
    else
      throw new LogicEvent();
  }
}

public class Class2 {
  private Class1 class1 = new Class1();

  public static void main(String... args) {
    try {
      class1.logicalThrow();
    } catch(ThrowableEvent e) {
      System.out.println("Event thrown: " + e.getClass().getName());
    } catch(HelloEvent e1) {
      System.out.println("Hello!");
    } catch(LogicEvent e2) {
      System.out.println("10 + 11 = 101");
    }
    // the other catches won't run since they inherit ThrowableEvent,
    // but I put in the verbose catch statements for an example
  }
}
</code>```

答:
I don't understand how would something like that work. After a method throws an exception, it stops executing and permanently gives up control to some exception handler. But after a method raises an event, it gives up control to the event handler only temporarily, and then continues executing.

I don't see how could you emulate temporarily giving up control using something that permanently gives up control very well. Exceptions were never meant for something like that, and I don't think you can make them do it.


答:
Would it be abusive to create an event system that uses try-catch statements and throwables, which are really made for error handling?

Abusive is an emotionally loaded term.  And it is blatantly subjective ... unless you are measuring a standard that everyone concerned can agree is applicable.

What could that standard be?

It could be a particular style guide that the concerned parties have agreed to use.

"Industry Best Practice" is NOT a suitable standard because: 1) it is not codified, and 2) it changes, and 3) you won't get everyone to agree what it actually is.

It could be a set of "best practice" rules that the concerned parties have agreed on.

And who are the concerned parties?  That is easy:

If this is personal project - it is just you.

If this is a project that someone is being paid to implement - the project team, maintenance team and (maybe) the customer.

If this is an open source project - the developers.  (Downstream folks may want to have a say, but the reality is that they only have "rights" if they are contributing.)

And so on.

For the record, neither the old Sun Java Code Conventions or the Google Java style guide says anything about whether what you are proposing would be appropriate.

There is a common dogma that says that "exceptions should not be used for normal flow control" ... but it is based on a circular definition, and (IMO) not helpful.

This dogma is based (in part) on advice from the the Java designers.  (That advice was influenced by the fact that early JVMs were not optimized with "exceptions as normal flow control" in mind. Again, there is circularity in the logic here.)  However, I haven't yet managed to find this advice in any current normative Java documentation.  (Tutorials are not normative ...)

And would there be performance issues compared to a "vanilla" interface-Listener-with-Event-object event system?

Potentially, yes.

One problem is that creating a Throwable instance results in the capture of the call stack.  This is expensive.  You can do things to optimize this:

Overriding the fillInStackTrace method to do nothing gets rid of most of the overhead.

In Java 7 and onwards, the JIT compiler can optimize some cases where exception stacks don't need to be captured.

The other think you have missed is that you can only use exceptions for event signalling within a single call stack, and for patterns of event handling where events are handled further up the call stack.  These are significant limitations, and will render this approach impractical for many use-cases.

In short, this won't work as a general event handling system.

Title: Would implementing a "Throwable Event System" be abusive?

Body:
I have been thinking for a couple years now about using Throwable events and implementing a sort of event system that uses throw to dispatch an event, or let a different method handle it with throws.

The only problem is, Throwable is reserved for Errors and Exceptions. A google search shows zero (relevant) results on something like this. I'm assuming this is completely original or in the minority of event systems out there.

I know that the C# event system is similar to my idea (though I've never used it, only seen code fragments).

The question here is would it be abusive to create an event system that uses try-catch statements and throwables, which are really made for error handling? And would there be performance issues compared to a "vanilla" interface-Listener-with-Event-object event system?

Regardless, I will probably make an event system using this idea just to try it out (a little exercise).

I have made two examples. One of which uses "vanilla" event system, the other uses Throwables.

Vanilla:

```<code>public class Entity implements EntityListener {
  @Override
  public void entityEvent(EntityEvent e) {
    //...
  }
}

public interface EntityListener {
  public void entityEvent(EntityEvent e);
}

public static void main(String... args) {
  new Entity().entityEvent(new EntityEvent());
}
</code>```

Throwable:

```<code>public class Class1 {

  public void logicalThrow() throws ThrowableEvent, HelloEvent, LogicEvent {
    if(something)
      throw new ThrowableEvent();
    else if (sayHello)
      throw new HelloEvent();
    else
      throw new LogicEvent();
  }
}

public class Class2 {
  private Class1 class1 = new Class1();

  public static void main(String... args) {
    try {
      class1.logicalThrow();
    } catch(ThrowableEvent e) {
      System.out.println("Event thrown: " + e.getClass().getName());
    } catch(HelloEvent e1) {
      System.out.println("Hello!");
    } catch(LogicEvent e2) {
      System.out.println("10 + 11 = 101");
    }
    // the other catches won't run since they inherit ThrowableEvent,
    // but I put in the verbose catch statements for an example
  }
}
</code>```


问:
Avoid numeric errors in Naive Bayes method
I am implementing the Naive Bayes method with Gaussian distribution.

The problem that I have is that the variance used on the Gaussian curve (calculated from a training set) is REALLY small. They are on the order of e-07. That means the whole equation,

```<code>(1/:math.sqrt(2*:math.pi*:math.sqrt(variance))) *
:math.exp(-0.5*(:math.pow(elem - mean, 2) / variance))
</code>```

results in really high values (such as 500, or even more). That becomes a problem later, when I multiply every probability p(x|C) together (it is a vector of 256 features).

I heard that is possible to use logarithms to avoid these kind of numbers. I searched on google but didn't find anything related to the subject. Does anyone know about that?

答:
Your problem is likely a typo: you calculate 1 / sqrt(2 * pi * sqrt(variance)), while the formula expectedly has 1 / sqrt(2 * pi * variance**2). (Square root from variance taken twice is highly unlikely in a normalizing factor.)

While we're at it, I don't think rounding errors have anythig to do with your formula's problem.

With usable range of a 64-bit floating point number being around 1e+308, I'd not call 1e-7 "really small". Even if you use 32-bit floats (with range around 1e+38), things are not that bad.

Common sources of rounding errors is operations with wildly different magnitudes: 1e+15 + 0.2 gives you a number which is suddenly 1000000000000000.25. Also, sqrt, exp, and pow are complex computations that remove some of the precision. I bet pow(x, 2) differs slightly form x * x for many values of x.

Obviously, log(a * b) = log(a) + log(b), and exp(a + b) = exp(a) * exp(b). I don't see, though, how this could help your case: calculating exp twice will introduce more error than calculating it once.


问:
Where should my team start with becoming "modern"?
I'm a relatively new developer, fresh from college. While in college and during subsequent job-seeking, I realized that there were a lot of "modern" software development methodologies that my education was lacking: unit testing, logging, database normalization, agile development (vs. generic agile concepts), coding style guides, refactoring, code reviews,  no standardized documentation methods (or even requirements), etc.

Overall, I didn't see this is a problem. I expected my first job to embrace all of these ideas and to teach them to me on the job. Then I got my first job (full stack web development) at a big corporation and I realized that we do none of these things. In fact I, the least experienced on the team, am the one who is spearheading attempts to bring my team up to speed with "modern" programming techniques - as I worry that not doing so is professional suicide down the road.

First I began with logging software (log4J), but then I quickly moved on to writing my own styleguide, then abandoning it for the Google styleguide - and then I realized that our Java web development used hand-written front controllers, so I pushed for our adoption of Spring - but then I realized we had no unit tests, either, but I was already learning Spring... and as you can see, it becomes overwhelming all too quickly, especially when paired with normal development work. Furthermore, it is difficult for me to become "expert" enough in these methodologies to teach anyone else in them without devoting too much time to a single one of them, let alone them all.

Of all these techniques, which I see as "expected" in today's software development world, how do I integrate them into a team as a new player without overwhelming both myself and the team?

How can I influence my team to become more agile? is related, but I'm not an Agile developer like the asker here, and I'm looking at a much broader set of methodologies than Agile.

答:
There have been plenty of proposals for improving the programming paradigm.  The hottest buzzwords now seem to be agile programming and object-oriented.  Or are they?  Both have faded substantially compared to what they were just five years ago.

You can be fairly confident that whatever methodology put in place is trying to accomplish the same end result:  help engineers economically produce a final product which is good enough.

There is one paradigm that was controversially introduced in the 1960s:  structured programming:  only use "high level" constructs like while, for, repeat, if/then/else, switch/case statements instead of the heavily used goto statement which had been accepted by default.  There are still debates about whether goto has any legitimate use at all.

I accept that minimizing use of goto is a good thing, but like all good things, it is possible to go too far.

You mention agile methodologies as something positive.  I was in one development team for about six months that intentionally followed a prescribed agile regimen.  I found it to be just like enlightened project management methodologies from decades ago, except everything is renamed.  Perhaps by re-bundling and reselling ideas for communicating someone makes a living and companies can feel good about "seeing" the emperor's new clothes.

Agile's most valuable lesson, which was known long ago, is that flexibility to find a better path to the finished product is a good thing and the ability to find that path can come from anyone—not just upper management.

From a writing by anti-goto ringleader Edsger Dijkstra:

The art of programming is the art of organizing complexity, of mastering multitude and avoiding its bastard chaos as effectively as possible.

—Dijkstra, in: Dahl, Dijkstra & Hoare 1972, pg. 6.  (see page 6 here.)


问:
Domain driven design, can two aggregates have the same root?
For the purpose of separating different functionality into different classes, I have two following Aggregates:

ActiveEmployee

AssignTask ()

ReassignManager ()

Deactivate (string reason)

InactiveEmployee

GetReasonForDeactivation ()

Reinstate ()

Both aggregates share the same root, dbo.Employee.

EmployeeID servers as a primary key for both Aggregates.

The repository instantiates the first one, or the second one based on a boolean flag dbo.Employee.IsActive.

Since I follow the rule that only one aggregate can be modified in one transaction, I will never encounter a situation where I load both aggregates with same ID, ending up with InactiveEmployee with ID 3 and ActiveEmployee with ID 3 in same transaction.

Is this good DDD? Does DDD allow for having two aggregates with same root?
Can we differentiate Aggregate types based on a flag?

UPDATE 1:

When I said that both aggregates share the same root, what I meant was that both Aggregates represent a row in dbo.Employee table.

In my understanding, a root of the Aggregate is the entity which is uniquely defined in our domain. It does not mean that that entity has to exist as a real class, it's identity is what matters. Every other Aggregate that wants to reference Inactive/ActiveEmployee will hold a reference to the EmployeeID, not the reference to object instance.

答:
If Employee is an aggregate root, it means that all the outside objects can reference only the Employee (and not the ActiveEmployee/InactiveEmployee).

Any references from outside the aggregate should only go to the aggregate root.
  DDD aggregate by Martin Fowler

I don't think that's your intent.

I think ActiveEmployee and InactiveEmployee are both independent aggregate roots in your example.

These two are completely different. They expose different APIs and require different handling.
They do share some information (Employee table), but that aside they have no interaction with one another. They cannot substitute one another and their APIs can't be invoked without checking the Employee status first

This situation looks a lot like violation of the Liskov Substitution principle to me.


答:
In addition to the other drawbacks that other answers have posited, another is that the Throwable mechanism is designed to be overbearing i.e., it short-circuits normal processing wherever present. Imagine the following

```<code> public void doSomething(){
    Foo it = new Foo();

    Bar something = it.doesSomething(); //anything thrown here will cause a hard stop here

    it.continuesDoingStuff(); //doesn't get executed

 }
</code>```

In the snippet above, throwing an "event" in doesSomething will alter the flow of doSomething in what is arguably an unpleasant way; to the unwary user of your API, it may cause the program to skip continuesDoingStuff altogether. The event will register more as a side-effect, than an expected outcome, which arguably defeats the purpose of event-driven programming.

Body:
In addition to the other drawbacks that other answers have posited, another is that the Throwable mechanism is designed to be overbearing i.e., it short-circuits normal processing wherever present. Imagine the following

 public void doSomething(){
    Foo it = new Foo();

    Bar something = it.doesSomething(); //anything thrown here will cause a hard stop here

    it.continuesDoingStuff(); //doesn't get executed

 }

In the snippet above, throwing an "event" in doesSomething will alter the flow of doSomething in what is arguably an unpleasant way; to the unwary user of your API, it may cause the program to skip continuesDoingStuff altogether. The event will register more as a side-effect, than an expected outcome, which arguably defeats the purpose of event-driven programming.


问:
Dijkstra function for navigation for disadvantaged
Is there a way we can write a function for Dijkstra to determine which node to enqueue and which to discard. This is for a navigation solution for people with disabilities where path to stairs may be shorter but not preferable to wheelchair bound individuals. The navigation solution should also support all individuals and only give a path discarding stairs if the specified user group is someone who is wheelchair bound etc. So basically i am attempting to write a function that checks if user group = wheelchair bound then removes the shortest path to stairs and gives the path to the nearest elevator. I am pretty new to this so any assistance would be very much appreciated.</p>

答:
Lot's of edges (stairs) will be disabled in the graph for people with disabilities.
You can either filter them out before you build your graph (collection of edges), or add logic at 'calculating the tentative distances' step. (Step 3) in the Algorithm</p>


答:
Given that Dijkstra's algorithm requires a starting point (usually taken to be the person's current position), each run of the algorithm is already made specifically to the person's request. Because of this, you can prune the graph to remove edges that are inaccessible to that person (as DanielS already pointed out), before running the algorithm.

If you plan to use a pathfinding algorithm that uses some kind of precomputation, perhaps you can give more details about your plan, so that better answers can be given.

Title: Dijkstra function for navigation for disadvantaged

Body: Is there a way we can write a function for Dijkstra to determine which node to enqueue and which to discard. This is for a navigation solution for people with disabilities where path to stairs may be shorter but not preferable to wheelchair bound individuals. The navigation solution should also support all individuals and only give a path discarding stairs if the specified user group is someone who is wheelchair bound etc. So basically i am attempting to write a function that checks if user group = wheelchair bound then removes the shortest path to stairs and gives the path to the nearest elevator. I am pretty new to this so any assistance would be very much appreciated.</p>


问:
Why do people still say Java is slow?
For a long time in SO and in other places Java has the reputation of being slow. From jokes to many comments in questions and answers, people still believe Java is slow based solely on experience with it in the 90s.

This is my issue: we have disproved (most) of the reasons that people believe Java is slow. Outside of small things, Java is pretty fast.

So why is it that people still refuse to believe Java is fast now? Is it part of their mindset that anything thats not C/C++ is slow? Is it because people don't check over time? Is it because people are just biased?

答: Circa 1997 I used a HP Vectra VE (200 MHz) and Windows 95. Most applications ran very fast on this, but then I tried a few applications written in Java (IDEs, if I recall correctly). They were very slow, at least the GUI parts of them. They took long time to start, and the GUI elements (e.g. menus) were not very responsive -- there were delays in the visual feedback. Also, since Java GUI applications had (has) a rather distinctive look, I learned to associate this look (and Java) with poor performance.</p>

Title: Why do people still say Java is slow?


问:
How do I deal with the following technical issue?
I am a Java Programmer and I am relatively new to Java(1 Year). I am working for a small startup company.

My problem is a bit strange and I am facing it a bit difficult to deal with and explain also.

My director in the company usually assigns some programming tasks on the product we are developing. He is not from Java background, but from databases background. Usually he cares about application configuration and pluggable architecture which is very much desirable.

What according to him is pluggable is obtaining object instances through Java Reflection. Always he insists us to write a class that reads an xml file where it is written which class has to be instantiated and do actual work
from that object instantiated using reflection. I tried to explain about DI frameworks such as Spring and Java EE CDI, but of no use.

And he thinks that whenever an xml file structure is changed, its parsing code or writing code need not be changed. We, the programmers, prefer using JAXB for marshalling and unmarshalling the xmls as it is intuitive.

Very frequently he complains that the code is slow, or the programmers are incapable of providing an architecture that allows absolutely no change in Java code but all changes in xml configuration/data are consumed by the application.

And every single possible decision we make are with his consent regarding finalising the xmls structure. Accordingly we code and develop things. But after some period he finds something else is fascinating and asks us to change the whole structure of the xml. Change in requirements is not a problem, but he thinks Java code need never be changed and keeps blaming that the programmers are incapable of writing code in such a way.

Is it really possible? How do we convince him or explain?

答: A few benchmark runs might help establish why your applications are slow.  Then a demonstration of a dramatic improvement by a change in methodology could be suggested.</p>


问:
Is Objective-C the only language with infix arguments?
One of the things I like about Objective-C is the use of infix arguments when calling a method.

[myDictionary setObject:myObject forKey:@"key"];

where the method name is setObject:forKey:.

Does any other language do this?

答: Since Objective-C inherited its core object-oriented features (minus categories and protocols), including the syntax, from Smalltalk, there's obviously at least Smalltalk that has the same syntax. Plus, all of the Smalltalk descendants such as Self, Newspeak and Fancy.</p>


问:
Does needing the ability to extend a class at runtime imply poor design?
Aadit M Shah states in Benefits of prototypal inheritance over classical:

One of the most important advantages of prototypal inheritance is that you can add new properties to prototypes after they are created. ... This is not possible in classical inheritance because once a class is created you can't modify it at runtime.

But it seems to me that needing the ability to add new properties/methods to your classes at runtime would be indicative of the code author not fully anticipating the needs and responsibilities of the class when defining it.

Is this the case?

答:
First off, the premise is flawed. You most definitely can modify classes at runtime, e.g. in Ruby:

class Foo; end

foo = Foo.new

foo.bar
# NoMethodError: undefined method `bar' for #<Foo:0xdeadbeef4815162342>

class Foo; def bar; 'Hello' end end

foo.bar
# => 'Hello'
```

<p>Python:</p>

<pre class="lang-python prettyprint-override"><code>class Foo: pass

foo = Foo()

foo.bar()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: Foo instance has no attribute 'bar'

Foo.bar = lambda self: "Hello"

foo.bar()
# => "Hello"
</code>```

On the other hand, there are prototype-based languages, which do not allow you to modify the prototype at runtime, most notably the statically typed prototype-based languages.

Now, to answer your question:

But it seems to me that needing the ability to add new properties/methods to your classes at runtime would be indicative of the code author not fully anticipating the needs and responsibilities of the class when defining it.

Yes. It’s Difficult to Make Predictions, Especially About the Future. Therefore, it is sometimes hard if not impossible to know what the shape of an object will be until runtime. Think, for example, of an XML deserializer, which creates objects described by an XML document, whose shape is described by an XML Schema, both of which are passed as command line arguments at runtime.

Steve Yegge's classic rant about The Universal Design Pattern is another example, where being able to dynamically add and remove properties from objects is desirable. He gives several case studies, where people have re-invented prototypes and dynamic properties on top of languages that don't have them natively, including inside the Eclipse JDT written in Java and Steve Yegge's own multiplayer role-playing game Wyvern, also written in Java. In Wyvern, property bags with prototypes are being used to model more or less all game objects.

Body:
First off, the premise is flawed. You most definitely can modify classes at runtime, e.g. in Ruby:

class Foo; end

foo = Foo.new

foo.bar
# NoMethodError: undefined method `bar' for #<Foo:0xdeadbeef4815162342>

class Foo; def bar; 'Hello' end end

foo.bar
# => 'Hello'

Python:

class Foo: pass

foo = Foo()

foo.bar()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: Foo instance has no attribute 'bar'

Foo.bar = lambda self: "Hello"

foo.bar()
# => "Hello"

On the other hand, there are prototype-based languages, which do not allow you to modify the prototype at runtime, most notably the statically typed prototype-based languages.

Now, to answer your question:

But it seems to me that needing the ability to add new properties/methods to your classes at runtime would be indicative of the code author not fully anticipating the needs and responsibilities of the class when defining it.

Yes. It’s Difficult to Make Predictions, Especially About the Future. Therefore, it is sometimes hard if not impossible to know what the shape of an object will be until runtime. Think, for example, of an XML deserializer, which creates objects described by an XML document, whose shape is described by an XML Schema, both of which are passed as command line arguments at runtime.

Steve Yegge's classic rant about The Universal Design Pattern is another example, where being able to dynamically add and remove properties from objects is desirable. He gives several case studies, where people have re-invented prototypes and dynamic properties on top of languages that don't have them natively, including inside the Eclipse JDT written in Java and Steve Yegge's own multiplayer role-playing game Wyvern, also written in Java. In Wyvern, property bags with prototypes are being used to model more or less all game objects.


问:
How do hybrid interpreter-JIT compilers work?
Chrome's V8 compiler, the Java HotSpot compiler, and many more have multiple tiers of interpretation and compilation.

A function starts off as interpreted in HotSpot and then, if it is run often enough, it is compiled to native code (and later optimized). How does the interface between such layers work?

For example, if you have 2 functions: Function A and Function B. If Function A is compiled and calls Function B, which is interpreted at the time Function A is compiled, Function A simply has a few instructions to trigger the interpreter for Function B, right?

But, what happens if, at some point after Function A is compiled, Function B is compiled too? Then, Function A will end up calling an interpreted version of Function B despite Function B having a faster, compiled, version.

So, what happens in modern compilers? Do they hot patch Function A to point to the new code for Function B? Do they add a layer of indirection and hot patch that instead of patching every single function that references Function B? Or something else entirely?

答:
You can split any code into pieces consisting of a linear sequence of steps that are separated by control flow changes (branches, function calls, returns, etc).

To do JIT compiling, you'd start immediately after a change in control flow, scan ahead until you find the next control flow change, convert the linear sequence of steps into native code, optimise the native code, place a "terminating control flow change" at the end of it, then store the result (lets call it "a trace") in some sort of "trace cache" and execute the trace. If there's no trace in the cache for the next piece of code then that "terminating control flow change" can pass control flow back to the virtual machine. If there is a trace for the next piece of code then that "terminating control flow change" can pass control directly (or indirectly) to the next trace. Note: I am over-simplifying here - that "terminating control flow change" may have 2 or more destinations (e.g. it may be a branch, where one destination is the "true" path and the other is the "false" path), and may need assistance from the virtual machine even if the next trace is in the cache.

The problem here is that it's all expensive (and the harder you try to optimise the native code being generated the more expensive it gets). If the sequence of code is run often then the overhead of JIT compiling becomes insignificant and there's a performance gain. If the sequence of code is not run often then the cost of JIT compiling can easily exceed the benefits.

Now; if there's no trace for the next piece of code then that "terminating control flow change" can pass control flow back to the virtual machine. Instead of JIT compiling, nothing prevents the virtual machine from interpreting at this point. If you decide to do JIT compiling you can patch the previous trace's "terminating control flow change" so that it points to the new trace that you generate. If you decide to interpret instead; then that's fine - immediately after the interpreter interprets a change in control flow it checks the trace cache to see if there's an "already native" trace for the next piece. If there is it can execute the already compiled trace, and if there isn't it can just keep interpreting or decide to switch to JIT compiling.

The only other thing you'd need to do is decide when to use JIT and when to interpret. Typically there are a few hints you can use to infer that JIT is likely to be worthwhile (specifically, taken conditional branches where the destination is at a lower address typically indicate loops, and loops are good candidates for JIT compiling). Beyond that you'd need to maintain some statistics (like the number of times something has been interpreted) and use them as the basis for the "JIT or interpret" decision.