问:
Why is software OS specific?
I'm trying to determine the technical details of why software produced using programming languages for certain operating systems only work with them.

It is my understanding that binaries are specific to certain processors due to the processor specific machine language they understand and the differing instruction sets between different processors. But where does the operating system specificity come from?
I used to assume it was APIs provided by the OS but then I saw this diagram in a book:

Operating Systems - Internals and Design Principles 7th ed - W. Stallings (Pearson, 2012)

As you can see, APIs are not indicated as a part of the operating system.

If for example I build a simple program in C using the following code:

```<code>#include<stdio.h>

main()
{
    printf("Hello World");

}
</code>```

Is the compiler doing anything OS specific when compiling this?

答:
The diagram has the "application" layer (mostly) separated from the "operating system" layer by the "libraries", and that implies that "application" and "OS" don't need need to know about each other. That is a simplification in the diagram, but it's not quite true.

The problem is that the "library" has actually three parts to it:  the implementation, the interface to the application, and the interface to the OS. In principle, the first two can be made "universal" as far as the OS is concerned (it depend on where you slice it), but the third part - the interface to the OS - generally cannot. The interface to the OS will necessarily depend on the OS, the APIs it provides, the packaging mechanism (e.g. the file format used by Windows DLL), etc.

Because the "library" is generally made available as a single package, it means that once the program picks a "library" to use, it commits to a specific OS. This happens one of two ways: a) the programmer picks completely in advance, and then the binding between the library and the application can be universal, but the library itself is bound to the OS; or b) the programmer sets things up so the library is selected when you run the program, but then the binding mechanism itself, between the program and the library, is OS-dependent (e.g. The DLL mechanism in Windows). Each has it's advantages and disadvantages, but either way you have to make a choice in advance.

Now, this doesn't mean that it's impossible to do, but you have to be very clever. To overcome the problem, you would have to go the route of picking the library at run-time, and you would have to come up with a universal binding mechanism that doesn't depend on the OS (so you are responsable to maintain it, a lot more work). Some times it's worth it.

You don't have to, but if you are going to put the effort to do that, there is a good chance you don't want to be tied to a specific processor either, so you will write a Virtual Machine and you will compile your program to a processor neutral code format.

By now you should have noticed where I'm going. Language-platforms like Java do exactly that. The Java runtime (library) defines the OS-neutral binding between your Java program and the library (how the Java runtime opens and runs your program), and it provides an implementation specific to the current OS. .NET does the same thing to an extent, except that Microsoft doesn't provide an "library" (runtime) for anything but Windows (but others do - see Mono). And, actually, Flash also does the same thing, although it's more limited in scope to the Browser.

Finally, there are ways to do the same thing without a custom binding mechanism. You could use conventional tools, but defer the binding step to the library until the user picks the OS. That's exactly what happens when you distribute the source code. The user takes your program and binds it to the processor (compile it) and OS (link it) when the user is ready to run it.

It all depends on how you slice the layers. At the end of the day, you always have a computing device made with specific hardware running specific machine code. The layers are there largely as a conceptual framework.

Title: Why is software OS specific?


问:
Why no developer API in C++ for Google or Yahoo mail?
I was trying to do some C++ coding that can send files from my laptop to my webmail account. It took me about 10 minutes to realize that there is no easy way to do this. Look into these links:

GMAIL: http://code.google.com/apis/gmail/oauth/code.html

YAHOO: http://developer.yahoo.com/mail/

I am trying to understand why PHP or Python or Java support exist but no C++. No flame wars, I love all programming languages and their creators equally but I am curious to understand the logic behind such implementation choices.

答:
There are some C++ or C libraries to send email (using SMTP): VMIME, libsmtp, etc. You could also find IMAP libraries

And you could write C++ web applications, e.g. using an HTTP server library like libonion or wt, or making it a FastCGI client. You can do HTTP client processing using libcurl

However, most people prefer coding web app in e.g. PHP. But you could use Ocaml with ocsigen, or opa or Hop

But your question is probably off-topic here.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Do you have any techniques to help you get started in the morning?
I'm not a morning person.  I got into the habit of working from 10 to 7/8, sometimes 9.

Nevertheless, many of the places I've worked for have asked for something more like 8 to 6 or 9 to 6.

Honestly, I have a real tough time getting my brain going in the morning and getting into the code.  Once I do, I can concentrate for a long time and be quite productive.

It's getting into the code and starting to get going with it that I have trouble with.  Sometimes I will waste time in the morning just because I can't focus on the problem (yes, I am writing this in the morning).

I've put all my busy work in the morning, but as a developer, I don't have a lot of busy work.

It kind of becomes a self reinforcing thing; because you don't get things done in the morning, you have to stay later.  Because you have to stay later, then its harder to get started the next morning, etc.

Do other people have trouble with this?  If so, any techniques you've learned?

Thanks!

答:
When I find myself procrastinating I start with an easy or trivial task that needs doing. Starting off with something simple eases in the brain ready for the deeper stuff that requires more thought and flow.

Whenever I took college exams I always started with the easiest questions to get into a rhythm.


问:
How to test and optimize when you can't reproduce the environment?
In the past, I've worked in a variety of environments. Desktop apps, games, embedded stuff, web services, command line jobs, web sites, database reporting, and so on. All of these environments shared the same trait: no matter their complexity, no matter their size, I could always have a subset or slice of the application on my machine or in a dev environment to test.

Today I do not. Today I find myself in an environment whose primary focus is on scalability. Reproducing the environment is prohibitively costly. Taking a slice of the environment, while plausible (some of the pieces would need to be simulated, or used in a single-instance mode that they're not made to do), kinda defeats the purpose since it obscures the concurrency and loading that the real system encounters. Even a small "test" system has its flaws. Things will behave differently when you've got 2 nodes and when you have 64 nodes.

My usual approach to optimization (measure, try something, verify correctness, measure differences, repeat) doesn't really work here since I can't effectively do steps 2 and 3 for the parts of the problem that matter (concurrency robustness and performance under load). This scenario doesn't seem unique though. What is the common approach to doing this sort of task in this sort of environment?

There are some related questions:

this question has to do with hardware (like spectrum analyzers) being unavailable, which can be (relatively) easily emulated.

this question is about tracking down bugs that only exist in production environments, which is helpful - but a different sort of activity.

答:
If you can't reproduce the live environment, the uncomfortable reality is that whatever you do, it won't have been sufficiently tested.

So, what can you do?

Well, whatever has to scale, be it a process, server cluster or database volume should be tested with the zero, one, infinity rule in mind to tease out where the potential bottlenecks/limitations are be it IO, CPUs, CPU load, inter-process communication etc.

Once you have this, you should get a feel for what kind of testing is affected. If it is unit testing, then this traditionally sits with the developer, if it is integration/system testing then there may be touch points with other teams who may be able to assist with additional expertise or better still, tools.

Speaking of tools, it isn't really the remit of the developer to load test a system beyond what is possible in their development environment. This should be pushed onto the test department or other 3rd party.

The elephant in the room of course is that systems do not always scale in predictable ways!

In a former life, I was a DBA for bank databases with billions of rows and armed with execution plans we could generally predict how long queries would take on an idle database given the input volumes. However, once these volumes got to a certain size, the execution plan would change and performance would rapidly deteriorate unless the query/database was tuned.


问:
Why do some functional programming languages use a space for function application?
Having looked at some languages for functional programming, I always wondered why some fp-languages use one or more whitespace characters for function application (and definition), whereas most (all?) imperative/object-oriented languages are using parentheses, which seems to be the more mathematical way. I also think that the latter style is much more clear and readable than without the parens.

So if we have a function f(x) = x² there are the two alternatives to calling it:

FP: f x

Examples:

ML, Ocaml, F#

Haskell

LISP, Scheme (somehow)

Non-FP: f(x)

Examples:

Almost all imperative languages (I know, see the comments/answers)

Erlang

Scala (also allows "operator notation" for single arguments)

What are the reasons for "leaving out" the parentheses?

答:
The basic idea is to make the most important operation (function application) easiest to read and easiest to write. A space is very unintrusive to read and very easy to type.

Note that this is not specific to functional languages, e.g. in Smalltalk, one of the first OO languages and languages inspired by it (Self, Newspeak, Objective-C), but also in Io and languages inspired by it (Ioke, Seph), whitespace is used for method calls.

Smalltalk-style:

```<code>anArray sort
anArray add: 2
aString replace: "a" with: "b"
</code>```

(In the latter case, the name of the method is replace:with:.)

Io-style:

```<code>anArray sort
anArray add(2)
aString replace("a", "b")
</code>```

Scala also allows whitespace for method calls:

```<code>foo bar(baz)
</code>```

And leaving off the parentheses if there is only one argument:

```<code>foo bar baz
</code>```

Ruby also allows you to leave off the parentheses:

```<code>an_array.sort
an_array.add 2
a_string.replace "a", "b"
</code>```

using parentheses, which seems to be the more mathematical way

Not really:

```<code>f(x)
sin x
x²
|x|
x!
x + y
xy
½
</code>```

Math notation has evolved over a long time in a horribly inconsistent way.

If at all, functional languages take their inspiration from λ-calculus where function application is written using whitespace.

Body:
The basic idea is to make the most important operation (function application) easiest to read and easiest to write. A space is very unintrusive to read and very easy to type.

Note that this is not specific to functional languages, e.g. in Smalltalk, one of the first OO languages and languages inspired by it (Self, Newspeak, Objective-C), but also in Io and languages inspired by it (Ioke, Seph), whitespace is used for method calls.

Smalltalk-style:

anArray sort
anArray add: 2
aString replace: "a" with: "b"

(In the latter case, the name of the method is replace:with:.)

Io-style:

anArray sort
anArray add(2)
aString replace("a", "b")

Scala also allows whitespace for method calls:

foo bar(baz)

And leaving off the parentheses if there is only one argument:

foo bar baz

Ruby also allows you to leave off the parentheses:

an_array.sort
an_array.add 2
a_string.replace "a", "b"

using parentheses, which seems to be the more mathematical way

Not really:

f(x)
sin x
x²
|x|
x!
x + y
xy
½

Math notation has evolved over a long time in a horribly inconsistent way.

If at all, functional languages take their inspiration from λ-calculus where function application is written using whitespace.


问:
Is it good practice declare a function inline?
I'm writing a method and depending on a config field I need to change where I get my data from. What this results in me having to write code that looks like this:

```<code>List<string> result = new List<string>();
if (configField)
{
    result.Add(fieldA);
}
else
{
    result.Add(...BusinessLogic...);
}
</code>```

I'll have to write that if statement many many times so of course I want to turn it into a method instead so I can just write result.Add(newMethod(configField, fieldA, dataForBusinessLogicToParse)). This method would be useless to anyone not writing the specific method I'm writing so does it make sense to declare this method as a separate private method or can I just declare it inline as a delegate like this:

```<code>Func<Enum, int, int> newMethod =
    (configField, fieldA, dataForBusinessLogicToParse) => ...businessLogic...
</code>```

I'm worried declaring it inline might make the code more difficult to understand but I think it makes the class cleaner.

答:
If newMethod never changes its value after initialization (it could be declared const or readonly, I guess), you should better write a standard private method. Using delegates without a reason can make the code confusing (at least in C#), even for experienced programmers. Comparing

```<code> private Action<Enum, int, int> newMethod = (configField, fieldA, dataForBusinessLogicToParse) ...
</code>```

vs.

```<code> private void NewMethod(Enum  configField, int fieldA, int dataForBusinessLogicToParse)
 {
 }
</code>```

the latter is much more readable for me, because I see immediately which parameter has which type, whilst for the first construct I have to count parameters (especially when the number of parameters becomes more than 3).

ContentLicense: CC BY-SA 4.0

Body:
If newMethod never changes its value after initialization (it could be declared const or readonly, I guess), you should better write a standard private method. Using delegates without a reason can make the code confusing (at least in C#), even for experienced programmers. Comparing

 private Action<Enum, int, int> newMethod = (configField, fieldA, dataForBusinessLogicToParse) ...

vs.

 private void NewMethod(Enum  configField, int fieldA, int dataForBusinessLogicToParse)
 {
 }

the latter is much more readable for me, because I see immediately which parameter has which type, whilst for the first construct I have to count parameters (especially when the number of parameters becomes more than 3).


问:
Repository pattern implementation that knows nothing about the database table and column names
I've seen around the Internet and Github, implementations for the design pattern Repository that knows about database table and column names. I was think, if I want to work with the database as a plugin, that I can unplug and plug another respecting Open/Closed for the rest of my code, my repository should not know about the column names of the database I'm using. So how to implement this pattern in a way that it can transform the result from the database into a Entity of my domain, without knowing about the database table and column names?

As my main language is PHP, I saw that in Doctrine\ORM you can easily pass different yamls or xmls config files, mapping the column names to property names on the Entity, but... I cant be a hostage of a library implementation, if I want to implement raw PDO, or any other library for my repositories that doesn't make this hydration out-of-the-box, my implementation should do, so how?

Update

Update 2

Please, take a look at: http://leocavalcante.github.io/patterns/2014/07/11/repository-pattern-and-database-schema.html

答:
What you're talking about here is dependency inversion and encapsulation. You consuming code wants to hold a dependency on some means of getting hold of domain entities, without needing to know how that happens. It wants a set of methods on a black box, which it expects to give some inputs and get some outputs: an interface.

Instead of having your code depend on some concrete implementation of data access, you rely on an abstraction: the interface. So long as your calling code knows only about the abstraction, then it doesn't matter how you fulfill that interface, so long as you do it correctly.

Taking the Doctrine and raw PDO examples from your question, you might define an interface as:

```<code>interface FooRepositoryInterface {
    public function getAFoo($id);
}
</code>```

With the interface in place, you can implement it in any way you see fit:

```<code>public class DoctrineFoo implements FooRepositoryInterface {
    public function __construct(EntityManager $em){ ... }
    public function getAFoo($id){
        return $this->em->find("\Entity\Foo", $id);
    }
}

public class PDOFoo implements FooRepositoryInterface {
    public function __construct(PDO $pdo){ ... }
    public function getAFoo($id){
        $pdo->prepare("sql ...");
        $row = $pdo->fetchOne();
        return $this->makeFooFromRow($row);
    }
}
</code>```

This allows your other modules to happily depend on data acess in terms of the interface:

```<code>class FooBazer {
    public function doBaz(FooRepositoryInterface $repository, $id) {
        $foo = $repository->getAFoo($id);
        $foo->baz();
    }
}
</code>```

Body:
What you're talking about here is dependency inversion and encapsulation. You consuming code wants to hold a dependency on some means of getting hold of domain entities, without needing to know how that happens. It wants a set of methods on a black box, which it expects to give some inputs and get some outputs: an interface.

Instead of having your code depend on some concrete implementation of data access, you rely on an abstraction: the interface. So long as your calling code knows only about the abstraction, then it doesn't matter how you fulfill that interface, so long as you do it correctly.

Taking the Doctrine and raw PDO examples from your question, you might define an interface as:

interface FooRepositoryInterface {
    public function getAFoo($id);
}

With the interface in place, you can implement it in any way you see fit:

public class DoctrineFoo implements FooRepositoryInterface {
    public function __construct(EntityManager $em){ ... }
    public function getAFoo($id){
        return $this->em->find("\Entity\Foo", $id);
    }
}

public class PDOFoo implements FooRepositoryInterface {
    public function __construct(PDO $pdo){ ... }
    public function getAFoo($id){
        $pdo->prepare("sql ...");
        $row = $pdo->fetchOne();
        return $this->makeFooFromRow($row);
    }
}

This allows your other modules to happily depend on data acess in terms of the interface:

class FooBazer {
    public function doBaz(FooRepositoryInterface $repository, $id) {
        $foo = $repository->getAFoo($id);
        $foo->baz();
    }
}


答:
My advice would be 1. don't feel bad and 2. don't fight it.  As much as most companies would like to think of programming as similar exercise to flipping burgers all day, it's not.  When I was a developer, I spent a ton of time not developing mostly thinking and letting my active mind or my sub-conscious dwell on problems or best approaches.  I'd come in late, take coffee breaks, go on starbucks breaks.  But, when my brain wanted to code, I let it code and I was by far the most productive on the team.  Productivity is the key in our industry, not punching a clock.  Embrace what makes you productive and you will not look back.

Edit for comments:  Agreed.  You have to find an organization and manager that "get you".  But, I won't settle for the Office Space "I stare at my monitor for 15 minutes.  It looks like I'm working, but I'm not."  That does not help anyone. :)

Title: Do you have any techniques to help you get started in the morning?

Body:
I'm not a morning person.  I got into the habit of working from 10 to 7/8, sometimes 9.

Nevertheless, many of the places I've worked for have asked for something more like 8 to 6 or 9 to 6.

Honestly, I have a real tough time getting my brain going in the morning and getting into the code.  Once I do, I can concentrate for a long time and be quite productive.

It's getting into the code and starting to get going with it that I have trouble with.  Sometimes I will waste time in the morning just because I can't focus on the problem (yes, I am writing this in the morning).

I've put all my busy work in the morning, but as a developer, I don't have a lot of busy work.

It kind of becomes a self reinforcing thing; because you don't get things done in the morning, you have to stay later.  Because you have to stay later, then its harder to get started the next morning, etc.

Do other people have trouble with this?  If so, any techniques you've learned?

Thanks!


问:
How bad is using underscore in names?
I am mainly a C programmer. In my world, writing likeThis or like_this is just a matter of style. In Haskell however, it seems that camelCase is the definite choice. Personally, I find the later much more readable. Think pthread_mutexattr_init vs PthreadMutexAttrInit.

What's more, I have configured vim to swap the numbers and their alternate symbols (in C), since numbers happen to be written much less frequently than symbols such as parentheses, star, ampersand etc, which makes life easier on my wrist. As a bonus, this lets me write this_sort_of_thing without using the shift key.

My question is, from the Haskell programmers, whether using underscore in names is acceptable to the Haskell community or not. Is camelCase an unwritten rule or common convention? Would it be ok to make the public functions likeThis but internally write like_this?

答:
There’s nothing particularly bad about using underscores in Haskell. One convention I have seen is to use underscore_case for local bindings and camelCase for top-level functions, or to prefix fields of a record with the record name and an underscore:

```<code>data These a = These { these_fooBar, these_barBaz :: a }
</code>```

However, I prefer to use camelCase everywhere since it’s not worth fretting over, that’s what a majority of Haskell code is like, and it’s consistent with module names and constructors—unless you like This_Sort_of_Thing.

Title: How bad is using underscore in names?

Body:
There’s nothing particularly bad about using underscores in Haskell. One convention I have seen is to use underscore_case for local bindings and camelCase for top-level functions, or to prefix fields of a record with the record name and an underscore:

data These a = These { these_fooBar, these_barBaz :: a }

However, I prefer to use camelCase everywhere since it’s not worth fretting over, that’s what a majority of Haskell code is like, and it’s consistent with module names and constructors—unless you like This_Sort_of_Thing.


答:
Although there's a lot of truth in Simon's answer, I think there's also a much more practical reason.  The nature of functional programming tends to generate a lot more parentheses than imperative programming, due to function chaining and composition.  Those patterns of chaining and composition also usually happen to be able to be unambiguously represented without parentheses.

The bottom line is, all those parentheses get annoying to read and track.  It's probably the number one reason LISP isn't more popular.  So if you can get the power of functional programming without the annoyance of excess parentheses, I think language designers are going to tend to go that way.  After all, language designers are also language users.

Even Scala allows the programmer to omit parentheses in certain circumstances, which happen to come up fairly frequently when programming in a functional style, so you sort of get the best of both worlds.  For example:

```<code>val message = line split "," map (_.toByte)
</code>```

The parens at the end are necessary for associativity, and the others are left off (as well as the dots).  Writing it this way emphasizes the chained nature of the operations you're performing.  It might not be familiar to an imperative programmer, but to a functional programmer it feels very natural and flowing to write this way, without having to stop and insert syntax that adds no meaning to the program, but is just there to make the compiler happy.

Title: Why do some functional programming languages use a space for function application?

Body:
Having looked at some languages for functional programming, I always wondered why some fp-languages use one or more whitespace characters for function application (and definition), whereas most (all?) imperative/object-oriented languages are using parentheses, which seems to be the more mathematical way. I also think that the latter style is much more clear and readable than without the parens.

So if we have a function f(x) = x² there are the two alternatives to calling it:

FP: f x

Examples:

ML, Ocaml, F#

Haskell

LISP, Scheme (somehow)

Non-FP: f(x)

Examples:

Almost all imperative languages (I know, see the comments/answers)

Erlang

Scala (also allows "operator notation" for single arguments)

What are the reasons for "leaving out" the parentheses?

Body:
Although there's a lot of truth in Simon's answer, I think there's also a much more practical reason.  The nature of functional programming tends to generate a lot more parentheses than imperative programming, due to function chaining and composition.  Those patterns of chaining and composition also usually happen to be able to be unambiguously represented without parentheses.

The bottom line is, all those parentheses get annoying to read and track.  It's probably the number one reason LISP isn't more popular.  So if you can get the power of functional programming without the annoyance of excess parentheses, I think language designers are going to tend to go that way.  After all, language designers are also language users.

Even Scala allows the programmer to omit parentheses in certain circumstances, which happen to come up fairly frequently when programming in a functional style, so you sort of get the best of both worlds.  For example:

val message = line split "," map (_.toByte)

The parens at the end are necessary for associativity, and the others are left off (as well as the dots).  Writing it this way emphasizes the chained nature of the operations you're performing.  It might not be familiar to an imperative programmer, but to a functional programmer it feels very natural and flowing to write this way, without having to stop and insert syntax that adds no meaning to the program, but is just there to make the compiler happy.


问:
Does ES6 help grow the Ecmascript standard library?
With all the noise about EC6, one thing that I realized I haven't heard about is expanding Javascript's standard library. Javascript has a fairly sparse standard library. You need a 3rd party library to do many basic things like date manipulation.

I'd rather have more built into the browser via a standard library then have to download Javascript to do basic things.

Is this a focus of the standards body? Is it contingent on ES6 modules? Is it even correct to discuss an "Ecmascript standard library" (does the standard specify a std lib like say C++'s spec does) or is it something specific to the Javascript implementation of the Ecmascript standard?

答:
It’s certainly something that’s considered in every standard, but I would say that yes, a more comprehensive standard library is a focus of ES6; comparing it to the changes in every other revision of JavaScript (which have, for the most part, added functions to existing types), you’ll notice that it’s… a lot more. No, the changes are not contingent on modules.

Truly new in ES6 (i.e. not a renamed or improved version of something else):

Array.from, Array#fill, Array#find, Array#findIndex

Map, WeakMap, and Set types

Number.isInteger

String.fromCodePoint, String#codePointAt, String#startsWith, String#endsWith, String#contains, String#repeat, String#normalize – lots to do with Unicode, not just UTF-16

Object.is, Object.setPrototypeOf, Object.assign, Object.observe

Math.imul, Math.clz32, Math.fround – performance things

Promise – hugely important for asynchronous code

All in all, several things that would be very nice to have in the JavaScript standard library.

… I would rather have had more of this than modules and other breaking changes.


问:
What is a helper? Is it a design pattern? Is it an algorithm?
Maybe a little tongue-in-cheek, but as I can't find this answer anywhere through Google, so to ensure Software Engineering has the answer:

What is a helper?

I have seen the name being used everywhere (module names, class names, method names), as if the semantics were deep and meaningful, but in the context of Computer Science (although I don't have a degree in it), I've never seen a description or definition anywhere!

Is it a design pattern? Is it an algorithm? I once worked on a program in which the module and class were both called somethingsomethinghelper (where somethingsomething was fairly generic too) and I promptly renamed it to something that made sense to me, but I feel like I'm missing something here!

答:
A Helper class is a lesser known code smell where a coder has identified some miscellaneous, commonly used operations and attempted to make them reusable by lumping them together in an unnatural grouping. Successive developers have then come onto the project and not realised that the helper class exists, and have consequently rewritten the same common operations, or even created more Helper classes.

But seriously, the main problem with Helper classes is that they are usually operations that act on a specific class, which obviously means in OO terms that they are suffering from an acute case of Feature Envy. This failure to package the behaviour with the data it acts on is why developers so often (in my experience) fail to find it.

In addition to this, as you have already identified SomethingSomethingHelper is actually a terrible name. It is undescriptive, and gives you no real inkling of what sort of operations the class does (it helps?), which also means that it's not obvious when adding new behaviours whether they belong in the Helper class or not. I would break up such classes along the lines of related behaviour that logically group together, and then rename the new classes to reflect what it does.


问:
What do you use string reversal for?
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.

答: I flip phone numbers and certain strings for searches from time to time</p>

Title: What do you use string reversal for?


问:
MVC and the business rule
I need to know where in the MVC should I apply the business rule.

Imagine the situation: I have a school and I need to generate a calendar of classes for teachers. Each teacher has a school subject and is only available certain times. I need to generate this calendar in such a way that teachers can performing without timing conflicts.

Here are my questions:

What part of MVC the teacher should be part of? Taking into mind that your timings data are stored externally (such as a SQL database or an XML), it should be a Model, correct?

Now, where in the MVC the business rule that will compile the calendar should be developed? Like Controller or a Library?

These data could be worked directly into the Model, or perhaps a specific Model to work with other Models?

Now a bit of my vision: (please, correct me if I'm wrong)

The data from the teachers should be handled by a Model. So that I could, for example, get the timing available to him and his school subject. So, Teacher is Model.

The compilation of the calendar could be done in a controller or library. Question: but, controllers should be related to routes, and libraries to an API?

答:
Within the context of the MVC pattern, the Controller and View components are only concerned with user interactions (the Controller with reacting to requests and the View with presenting the UI). All other code, including the business logic and database access goes in the Model component.

As the Model is usually quite large, it should have an additional internal structure, but that goes beyond the scope of the MVC pattern.

Commonly, the Model is structured in layers, with a layer for the business logic, a separate layer for the database access, and possibly additional layers.

As a side note, don't make too much of the fact that libraries have API's. The API of a library is by definition the set of classes and functions that the library provides to the outside world for their use. Every library has an API, but that only becomes important when you need to provide backwards compatibility to code that was written to use older versions of the library. This is usually not needed for libraries that are used only by one application.

Title: MVC and the business rule


问:
Way for java program to read file from when it was stopped
I am working on an application that reads a log file, looks for a specific string, sends alert emails and saves data from the file into a database. The reading functionality is working well, but I am coming across an issue when I stop and restart my program. Basically, it always starts from the beginning of the log file, so I am rereading information I have already read. Please reference the example below.

Consider I have the log file with the following lines

```<code>1 0708 1200 Error in log
2 0708 1230 Received invoice 00001
3 0708 1231 Received invoice 00002
4 0708 0130 Error in log
5 0708 0135 Received invoice 00003
6 0708 0200 Received invoice 00004
7 0708 0230 Received invoice 00005
8 0708 0235 Error in log
</code>```

In this example, say I ran the application. The application would start reading at line 1 and continue until I stop the application (picking up any lines that are added to the file as well). Let's say I stop the application when I get to line 5. If this were the case, I would have received an alert e-mail from line 1 and line 4. I would have also saved lines 2 and 3 in the database.

My problem/question comes from when I want to restart the application again. Currently, the application will start reading at line 1 again. This is not an issue when it comes to saving data because I have placed a clause to not save if the line has already been added. However, when it comes to sending e-mails I will receive an e-mail for lines 1 and 4 again.

After all of the that rambling, I will present my actual question / inquery. Is there a way to stop a program (it completely stops the process) and begin reading from the spot in which I stopped reading from? I cannot think of a way to save the place holder for the file and use it once I start the program again.

I have considered saving the file pointer value to a text file and reading from there at every start up, but I was wondering if there was another way or any suggestions to improve this process. I know this question is abstract, but I am reaching out for extra brains on this issue.

Little information:

This is a java program

This is a web app running on a tomcat server

The server that tomcat is running on is a unix server

This is a constantly running application that should only be shut off during an issue or change

The logs being scanned are very large with 500,000+ lines

The logs turn around (get replaced with empty log) once they reach a certain size. This means that when I save the file pointer, I have to make sure I am in the same file before I start reading again, otherwise I want to start from the beginning

Any help / suggestions would be very helpful. Sorry for the wordy question, please let me know if anything is unclear. Thanks!

答:
One of the ways I can think is to store the line number of the previous read and then start from that position, something like this and keep reading until eof.

```<code>public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader (new FileReader("Profiles.ini"));

String info = "";
int startLine = 17;
int endLine = 22; //EOF in your case

for (int i = 0; i < startLine; i++) { info = in.readLine(); }
   for (int i = startLine; i < endLine + 1; i++) {
       info = in.readLine();
       System.out.println(info);
   }

   in.close();
}
</code>```

I got this extract from here.

OR

Take a look at this thread : https://stackoverflow.com/questions/2312756/in-java-how-to-read-from-a-file-a-specific-line-given-the-line-number

Body:
One of the ways I can think is to store the line number of the previous read and then start from that position, something like this and keep reading until eof.

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader (new FileReader("Profiles.ini"));

String info = "";
int startLine = 17;
int endLine = 22; //EOF in your case

for (int i = 0; i < startLine; i++) { info = in.readLine(); }
   for (int i = startLine; i < endLine + 1; i++) {
       info = in.readLine();
       System.out.println(info);
   }

   in.close();
}

I got this extract from here.

OR

Take a look at this thread : https://stackoverflow.com/questions/2312756/in-java-how-to-read-from-a-file-a-specific-line-given-the-line-number


问:
Why isn't there a next operation on enums?
In most popular programming languages like Java and C# there is a way to define enums, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek.

The problem is, given a value, e.g. DayOfWeek.Monday, how do I get the next value of the enum, in this particular case DayOfWeek.Tuesday?

I realize that not all enums are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next operation would be sufficient in most cases. In fact, since the set of values in a enum is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.

So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next value for a enum? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.

I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place.

答:
Technically speaking, there is a way to perform a next operation in both languages, though it varies between Java and C#.

C#

In C#, enumerations are number types at their core.  You can simply perform addition with integers:

```<code>var day = DayOfWeek.Sunday;
foreach(var n in Enumerable.Range(0, 7))
    Console.WriteLine("Day of week: {0}", day + n);
</code>```

note: the above works the same way with day++

Output:

```<code>Day of week: Sunday
Day of week: Monday
Day of week: Tuesday
Day of week: Wednesday
Day of week: Thursday
Day of week: Friday
Day of week: Saturday
</code>```

Java

Java allows you to define enums as full-blown object types.  As a result, you cannot simply increment it.  However, StackOverflow shows several alternatives.

TL;DR: there's a somewhat hackish way of incrementing an enum, but the suggested way is to implement a next() function in the enum.

Body:
Technically speaking, there is a way to perform a next operation in both languages, though it varies between Java and C#.

C#

In C#, enumerations are number types at their core.  You can simply perform addition with integers:

var day = DayOfWeek.Sunday;
foreach(var n in Enumerable.Range(0, 7))
    Console.WriteLine("Day of week: {0}", day + n);

note: the above works the same way with day++

Output:

Day of week: Sunday
Day of week: Monday
Day of week: Tuesday
Day of week: Wednesday
Day of week: Thursday
Day of week: Friday
Day of week: Saturday

Java

Java allows you to define enums as full-blown object types.  As a result, you cannot simply increment it.  However, StackOverflow shows several alternatives.

TL;DR: there's a somewhat hackish way of incrementing an enum, but the suggested way is to implement a next() function in the enum.


答:
Business rules are a pervasive responsibility of the application. The view should prevent the creation of conflicting schedules by not allowing them as an option; the controller should identify interactions and prevent their being formed in conflict. The model should prevent storage of conflicting schedules.

While you have an overarching rule ("no conflicts"), the rule manifests itself in sub-rules in the various domains that affect or are affected by the rule.

Title: MVC and the business rule

Body:
I need to know where in the MVC should I apply the business rule.

Imagine the situation: I have a school and I need to generate a calendar of classes for teachers. Each teacher has a school subject and is only available certain times. I need to generate this calendar in such a way that teachers can performing without timing conflicts.

Here are my questions:

What part of MVC the teacher should be part of? Taking into mind that your timings data are stored externally (such as a SQL database or an XML), it should be a Model, correct?

Now, where in the MVC the business rule that will compile the calendar should be developed? Like Controller or a Library?

These data could be worked directly into the Model, or perhaps a specific Model to work with other Models?

Now a bit of my vision: (please, correct me if I'm wrong)

The data from the teachers should be handled by a Model. So that I could, for example, get the timing available to him and his school subject. So, Teacher is Model.

The compilation of the calendar could be done in a controller or library. Question: but, controllers should be related to routes, and libraries to an API?


答:
Actually its tough, but I am sure in lots of comparable situations it is primarily an organizational problem. The only viable approach is probably a mixture of combined measures, not just "one silver bullet". Some things you can try:

logging: as I wrote already in a comment, excessive time and resource logging (which is a kind of profiling) can help you to identify the real bottlenecks in production. This may not tell you if an alternative implementation will work better, but it will surely help you to avoid optimizing the completely wrong part of your application.

test what you can test beforehand - thoroughly, with a lot of upfront planning. Sure, things will behave different in production, but not all things. The correctness of a different implementation often can be checked beforehand - if an implementation scales well, is a different question. But planning can help a lot. Think hard about the problems your test environment can solve for you, and which are not. There are almost always things where you believe at a first glance "it cannot be tested beforehand", but if you think twice, there is often more possible.

Work as team. When trying a new approach or idea, discuss it with at least one other person of your team. When you implement a different algo, insist about code inspections and QA. The more bugs and problems you can avoid beforehand, the less serious problems you will have to solve in production.

Since you cannot test everything beforehand, expect problems showing up in production. Thus try to prepare a really good fall-back strategy when bringing new code into production. When your new code has the risk of beeing slower than the old solution, or if it has the risk of crashing, make sure you can change to the previous version ASAP. If it has the risk of destroying production data, make sure you have a good backup/recovery in place. And make sure you detect such failures by adding some validation mechanism into your system.

keep a project diary or a solution log - seriously. Each day you find out something new about the environment, write it down - success stories as well as failure stories. Don't make the same failure twice.

So the gist is - when you cannot go with try-and-error, your best option are  conservative, classic upfront planning and QA techniques.

Title: How to test and optimize when you can't reproduce the environment?

Body:
In the past, I've worked in a variety of environments. Desktop apps, games, embedded stuff, web services, command line jobs, web sites, database reporting, and so on. All of these environments shared the same trait: no matter their complexity, no matter their size, I could always have a subset or slice of the application on my machine or in a dev environment to test.

Today I do not. Today I find myself in an environment whose primary focus is on scalability. Reproducing the environment is prohibitively costly. Taking a slice of the environment, while plausible (some of the pieces would need to be simulated, or used in a single-instance mode that they're not made to do), kinda defeats the purpose since it obscures the concurrency and loading that the real system encounters. Even a small "test" system has its flaws. Things will behave differently when you've got 2 nodes and when you have 64 nodes.

My usual approach to optimization (measure, try something, verify correctness, measure differences, repeat) doesn't really work here since I can't effectively do steps 2 and 3 for the parts of the problem that matter (concurrency robustness and performance under load). This scenario doesn't seem unique though. What is the common approach to doing this sort of task in this sort of environment?

There are some related questions:

this question has to do with hardware (like spectrum analyzers) being unavailable, which can be (relatively) easily emulated.

this question is about tracking down bugs that only exist in production environments, which is helpful - but a different sort of activity.


问:
Pointer indexing
I am currently reading a book titled "Numerical Recipes in C". In this book, the author details how certain algorithms inherently work better if we had indices starting with 1 (I don't entirely follow his argument and that isn't the point of this post), but C always indexes its arrays starting with 0. In order to get around this, he suggests simply decrementing the pointer after allocation, e.g.:

```<code>float *a = malloc(size);
a--;
</code>```

This, he says, will effectively give you a pointer that has an index starting with 1, which will then be free'd with:

```<code>free(a + 1);
</code>```

As far as I'm aware, though, this is undefined behavior by the C standard. This is apparently a highly reputable book within the HPC community, so I don't want to simply disregard what he's saying, but simply decrementing a pointer outside of the allocated range seems highly sketchy to me. Is this "allowed" behavior in C? I have tested it out using both gcc and icc, and both of those results appear to indicate that I'm worrying over nothing, but I want to be absolutely positive.

答:
First, it's undefined behaviour. Some optimising compilers nowadays get very aggressive about undefined behaviour. For example, since a-- in this case is undefined behaviour, the compiler could decide to save an instruction and a processor cycle and not decrement a. Which is officially correct and legal.

Ignoring that, you might subtract 1, or 2, or 1980. For example if I have financial data for the years 1980 to 2013, I might subtract 1980. Now if we take float* a = malloc (size); there is surely some large constant k such that a - k is a null pointer. In that case, we really expect something to go wrong.

Now take a big struct, say a megabyte in size. Allocate a pointer p pointing to two structs. p - 1 might be a null pointer. p - 1 might wrap around (if a struct is a megabyte, and the malloc block is 900 KB from the start of address space). So it could be without any malice of the compiler that p - 1 > p. Things may get interesting.

Title: Pointer indexing


答:
The Model is your data: teachers and classes.

Your Controller, among other things, composes the model data in such a way that the View can easily digest and display it. Composing a ViewModel is a good way to do this if the logic behind displaying the data is complex.

Your View takes the data that the Controller has prepared for it, if any, and renders it.

It is popular to abstract the Model (into layers), and handle business logic behind the veil.

Title: MVC and the business rule


答:
I establish a routine and leave myself notes from the day before and make sure I write in the task to start with in the morning.

My typical morning at work looks something like this:

Get in, get settled.

Grab some coffee or tea. Coffee is preferable for flavour, but tea will do. The warm drink is the important part for me here.

Read my notes from last night, see where I left off.

Do whatever I thought last night would be a good idea to do next. The me from yesterday that left the note had the entire task context in her head, so she must be right. :P

Just keep moving down my list of things to do from there.

It's gotten to the point that I kind of look forward to the "sit down and look over my notes" part of the day. It's almost as good as sitting down at home on the weekend with some RSS feeds or a newspaper.

I also found that listening to a dev-related podcast on the way to work can help get my brain into work mode by the time I actually get to my desk, but I leave that out of my actual routine.


答:
If I were you I would simply keep a place holder in a separate file.

If you are looking for alternatives though, you could place a special character directly in the log. Like a flag/number as the first line of the log that would update after reading every line. If you are working with several files, you could check each file for that first line flag or modify the file name to denote whether or not it is currently in use.

Title: Way for java program to read file from when it was stopped

Body:
I am working on an application that reads a log file, looks for a specific string, sends alert emails and saves data from the file into a database. The reading functionality is working well, but I am coming across an issue when I stop and restart my program. Basically, it always starts from the beginning of the log file, so I am rereading information I have already read. Please reference the example below.

Consider I have the log file with the following lines

```<code>1 0708 1200 Error in log
2 0708 1230 Received invoice 00001
3 0708 1231 Received invoice 00002
4 0708 0130 Error in log
5 0708 0135 Received invoice 00003
6 0708 0200 Received invoice 00004
7 0708 0230 Received invoice 00005
8 0708 0235 Error in log
</code>```

In this example, say I ran the application. The application would start reading at line 1 and continue until I stop the application (picking up any lines that are added to the file as well). Let's say I stop the application when I get to line 5. If this were the case, I would have received an alert e-mail from line 1 and line 4. I would have also saved lines 2 and 3 in the database.

My problem/question comes from when I want to restart the application again. Currently, the application will start reading at line 1 again. This is not an issue when it comes to saving data because I have placed a clause to not save if the line has already been added. However, when it comes to sending e-mails I will receive an e-mail for lines 1 and 4 again.

After all of the that rambling, I will present my actual question / inquery. Is there a way to stop a program (it completely stops the process) and begin reading from the spot in which I stopped reading from? I cannot think of a way to save the place holder for the file and use it once I start the program again.

I have considered saving the file pointer value to a text file and reading from there at every start up, but I was wondering if there was another way or any suggestions to improve this process. I know this question is abstract, but I am reaching out for extra brains on this issue.

Little information:

This is a java program

This is a web app running on a tomcat server

The server that tomcat is running on is a unix server

This is a constantly running application that should only be shut off during an issue or change

The logs being scanned are very large with 500,000+ lines

The logs turn around (get replaced with empty log) once they reach a certain size. This means that when I save the file pointer, I have to make sure I am in the same file before I start reading again, otherwise I want to start from the beginning

Any help / suggestions would be very helpful. Sorry for the wordy question, please let me know if anything is unclear. Thanks!


答:
enums are replaced with their constant values in the executable. they can not be traversed at runtime.

in C enum are part of the source code and the compiler replaces the enum with the constant int.

```<code>     // C source - enum gets replaced with constant
enum _tenum { A, B, C};
_tenum ft;
ft = B;
     // assembler enum is gone. only constant value 1 remains
mov DWORD PTR _ft$[ebp], 1

if (ft == B) {

cmp DWORD PTR _ft$[ebp], 1
jne SHORT $LN1@main
</code>```

in Java enum are also part of the source file and the byte code generator replaces the enum with the public final static value.

Here is an explaination
  http://boyns.blogspot.com/2008/03/java-15-explained-enum.html

Title: Why isn't there a next operation on enums?

Body:
In most popular programming languages like Java and C# there is a way to define enums, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek.

The problem is, given a value, e.g. DayOfWeek.Monday, how do I get the next value of the enum, in this particular case DayOfWeek.Tuesday?

I realize that not all enums are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next operation would be sufficient in most cases. In fact, since the set of values in a enum is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.

So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next value for a enum? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.

I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place.

Body:
enums are replaced with their constant values in the executable. they can not be traversed at runtime.

in C enum are part of the source code and the compiler replaces the enum with the constant int.

     // C source - enum gets replaced with constant
enum _tenum { A, B, C};
_tenum ft;
ft = B;
     // assembler enum is gone. only constant value 1 remains
mov DWORD PTR _ft$[ebp], 1

if (ft == B) {

cmp DWORD PTR _ft$[ebp], 1
jne SHORT $LN1@main

in Java enum are also part of the source file and the byte code generator replaces the enum with the public final static value.

Here is an explaination
  http://boyns.blogspot.com/2008/03/java-15-explained-enum.html


问:
Guidance on android type app to connect to sql-server
Excuse my ignorance but we've got an application that we'd like to sample out on a mobile app The app is a C#/asp.net application connected to our sql server database.  If we are going to write an android application for this app how exactly does one connect to the sql server instance?  I've tried to find many articles, some say via a web service others say jdbc drivers, etc.  I don't know too much about this because we've never done mobile development.

If we were to write up a web service, is the web service simply responsible for connecting to the database layer and fetching records?  Any examples would be greatly appreciated.

答:
You need to write and deploy a REST service which your Android app can communicate with.  There are a number of ways you can accomplish that: ASP.NET MVC, Web API, WCF, etc.  The REST service connects with the SQL Server instance.

The web service is responsible for what you want it to be responsible for.  It can contain business logic, transactions, data lookup, whatever.


答:
From another answer of mine:

Consider early DOS
  machines, and what Microsoft's real contribution to the world was:

Autocad had to write drivers for each printer they could print to. So
  did lotus 1-2-3. In fact, if you wanted your software to print, you
  had to write your own drivers. If there were 10 printers, and 10
  programs, then 100 different pieces of essentially the same code had
  to be written separately and independently.

What windows 3.1 tried to accomplish (along with GEM, and so many
  other abstraction layers) is make it so the printer manufacturer wrote
  one driver for their printer, and the programmer wrote one driver for
  the windows printer class.

Now with 10 programs and 10 printers, only 20 pieces of code have to
  be written, and since the microsoft side of the code was the same for
  everyone, then examples from MS meant that you had very little work to
  do.

Now a program wasn't restricted to just the 10 printers they chose to
  support, but all the printers whose manufacturers provided drivers for
  in windows.

So the OS provides services to the applications so the applications don't have to do work that is redundant.

Your example C program uses printf, which sends characters to stdout - an OS specific resource that will display the characters on a user interface.  The program doesn't need to know where the user interface is - it could be in DOS, it could be in a graphical window, it could be piped to another program and used as input to another process.

Because the OS provides these resources, programmers can accomplish much more with little work.

However, even starting a program is complicated.  The OS expects an executable file to have certain information at the beginning that tells the OS how it should be started, and in some cases (more advanced environments like android or iOS) what resources will be required that need approval since they touch resources outside the "sandbox" - a security measure to help protect users and other apps from misbehaving programs.

So even if the executable machine code is the same, and there are no OS resources required, a program compiled for Windows won't run on an OS X operating system without an additional emulation or translation layer, even on the same exact hardware.

Early DOS style operating systems could often share programs, because they implemented the same API in hardware (BIOS) and the OS hooked into the hardware to provide services.  So if you wrote and compiled a COM program - which is just a memory image of a series of processor instructions - you could run it on CP/M, MS-DOS, and several other operating systems.  In fact you can still run COM programs on modern windows machines.  Other operating systems don't use the same BIOS API hooks, so the COM programs won't run on them without, again, an emulation or translation layer. EXE programs follow a structure that includes much more than mere processor instructions, and so along with the API issues it won't run on a machine that doesn't understand how to load it into memory and execute it.

Title: Why is software OS specific?

Body:
I'm trying to determine the technical details of why software produced using programming languages for certain operating systems only work with them.

It is my understanding that binaries are specific to certain processors due to the processor specific machine language they understand and the differing instruction sets between different processors. But where does the operating system specificity come from?
I used to assume it was APIs provided by the OS but then I saw this diagram in a book:

Operating Systems - Internals and Design Principles 7th ed - W. Stallings (Pearson, 2012)

As you can see, APIs are not indicated as a part of the operating system.

If for example I build a simple program in C using the following code:

```<code>#include<stdio.h>

main()
{
    printf("Hello World");

}
</code>```

Is the compiler doing anything OS specific when compiling this?


问:
Scripts to run Java programs - e.g. Ant
My team currently use an Ant script to execute various Java programs.

Note that I am not asking about managing the build/deployment cycle for which we are already using Maven (quite happily).

For example, we use something like the following:

```<code><path id="lib">
  <fileset dir="path/to/lib" />
</path>

<path id="run" >
  <path refid="lib" />
</path>

<target name="aJavaProgram" >
  <java classname="path.to.AJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>

<target name="anotherJavaProgram" depends="aJavaProgram" >
  <java classname="path.to.AnotherJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>
</code>```

We originally chose Ant for the following reasons (or rather I didn't choose Ant, it was that way when I joined, but I think these are good reasons for the choice):

it was an easy way of managing dependencies (although we now pick up these from Maven)

it allows us to easily build/maintain dependencies between particular jobs

we can deploy the Ant script, and the Java libraries, and easily run particular jobs - i.e.

we don't have to worry about classpaths (configured in the Ant script)

we don't have to worry about building jars with main classes specified in the manifest

we can use Ant to create / store / manage arguments passed to main() methods

we can plug these ant scripts into our IDEs and run the jobs from there.

Generally speaking, we have been very happy with this.

However, an increasing issue is the ant-java-shutdown hook issue - this means that if one of these Java programs fails but doesn't finish, terminating the Ant process from which it was started doesn't terminate the Java process - which then has to be done manually, and is a real bind.

Also, I'm conscious of two other (possible) factors:

this is using Ant in a slightly unusual way, which is perhaps not how Ant was intended to be used (or at least, so it seems to me...)?

I'm not really sure, but it seems that fewer and fewer developers/teams are using Ant these days, with preference for other technologies.

So, to clarify:

I want a flexible approach to execute various Java programs

the approach that we have been using was to do this via Ant scripts, but this had the following problems:

terminating the Ant task does not kill the Java program

this "feels" like Ant is not the right tool for the job

how might we meet the needs specified above?

if not Ant, the solution should not face the termination / shutdown hook issue

答:
It sound like you are running some Java programs in a sequence and basically you were using Ant to call java as java -jar myApplication.jar ...

Normally, I see this done using shell scripts. They are simple, small, and very good for redirecting output to files, other programs, etc...

If you want something that is more cross-platform compatible, you could look into using a scripting language such as Perl or Ruby or Python, they all allow you to call java -jar myApplication.jar and it could be as simple as 1 or 2 lines to run your Java program. There are versions of all of these that are available for Windows, OS X, Linux and Unix. And you get the full flexibility of these languages, should you actually need them.

Additionally, most IDEs support launching "external"/"3rd party" tools from within the IDE, so you can write a shell (or Perl or whatever) script to launch your Java programs, and then in your IDE, it should be possible to create a link/button/whatever to launch myJavaAppRunner.ksh at the click of a button.

Title: Scripts to run Java programs - e.g. Ant


答: Something that has helped people is: in the evening, prepare a list of maximum 3 things to do the next morning, that way you don't have to wonder "so what should I do now ?" in the morning while you're only half-awake.</p>


答:
Since you are already using Maven, you may consider giving the Exec Plugin a shot.

I would rather avoid custom runs scripts if I were you unless the startup and shutdown logic is really complex, since writing them properly may be much harder than it seems, and you can run into issues with cross-platform or even cross-machine compatibility.

If you need lots of custom logic in the build or run process but prefer to stay within the bounds of a build system, you might want to have a look at Gradle which allows you more customization than Maven in some cases since you can add almost any Groovy code into your build process. This approach allows for better integration and may be more portable than writing custom scripts independent of the build system.

Title: Scripts to run Java programs - e.g. Ant

Body:
My team currently use an Ant script to execute various Java programs.

Note that I am not asking about managing the build/deployment cycle for which we are already using Maven (quite happily).

For example, we use something like the following:

```<code><path id="lib">
  <fileset dir="path/to/lib" />
</path>

<path id="run" >
  <path refid="lib" />
</path>

<target name="aJavaProgram" >
  <java classname="path.to.AJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>

<target name="anotherJavaProgram" depends="aJavaProgram" >
  <java classname="path.to.AnotherJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>
</code>```

We originally chose Ant for the following reasons (or rather I didn't choose Ant, it was that way when I joined, but I think these are good reasons for the choice):

it was an easy way of managing dependencies (although we now pick up these from Maven)

it allows us to easily build/maintain dependencies between particular jobs

we can deploy the Ant script, and the Java libraries, and easily run particular jobs - i.e.

we don't have to worry about classpaths (configured in the Ant script)

we don't have to worry about building jars with main classes specified in the manifest

we can use Ant to create / store / manage arguments passed to main() methods

we can plug these ant scripts into our IDEs and run the jobs from there.

Generally speaking, we have been very happy with this.

However, an increasing issue is the ant-java-shutdown hook issue - this means that if one of these Java programs fails but doesn't finish, terminating the Ant process from which it was started doesn't terminate the Java process - which then has to be done manually, and is a real bind.

Also, I'm conscious of two other (possible) factors:

this is using Ant in a slightly unusual way, which is perhaps not how Ant was intended to be used (or at least, so it seems to me...)?

I'm not really sure, but it seems that fewer and fewer developers/teams are using Ant these days, with preference for other technologies.

So, to clarify:

I want a flexible approach to execute various Java programs

the approach that we have been using was to do this via Ant scripts, but this had the following problems:

terminating the Ant task does not kill the Java program

this "feels" like Ant is not the right tool for the job

how might we meet the needs specified above?

if not Ant, the solution should not face the termination / shutdown hook issue


问:
Split work item into prototype and main work item?
During grooming, we usually have work items which get approved based upon the team understanding that what needs to be done? The product owner does not discuss the details of how it will be done and stops the discussion if team tries so. This applies to all work items (new UI, new API or changes to existing UI/API). Product Owner's reasoning is that getting into the details (both technical & functional) of how it will be done is something that needs to happen during sprint and discussing it during grooming is not correct. The effort estimation also happens based upon this discussion.

But during sprint planning, approved items are taken for the sprint and expectation is that if work item is approved, team should know all the details of the solution and should be able to complete the item in sprint. What happens is team spends first 2-3 days in doing the research and getting the PO's approval for the solution (UI design, key business logic clarification). Unless the analysis results in great difference in effort estimate, team is asked to complete the feature. This happens in each sprint.

I dont have a problem with putting extra effort in completing the work item. My question is regarding the process.

Should the team say no in approving the item unless team understands how the solution will look like?

Should the work item be splitted into research/analysis in which solution prototype will be proposed to the PO? Once the PO will approve the prototype, the main work item will be marked approved.

Any other suggestion as to how it can be handled in better way?

答:
In my opinion your problem its here:

"Unless the analysis results in great difference in effort estimate, team is asked to complete the feature."

Another company that want to "be agile" for don't spend time in estimation and a more in depth definition of US (and that its totally ok), but there are not "agile" enough to understand the difference between an estimation and a compromise.

The SM its the one that need to explain this to the management, and if the situation where the team need to work overtime for complete features its the norm sprint after sprint the SM must put immediately and end to this nonsense and recover a sustainable pace for the team.

Having sustainable pace its one the core values of agile, finishing all included US in a sprint of course its not. In the long run the first its much more important than the second, its key to understand this.


问:
AJAX or web sockets for client-server communication?
I recently took a course on AngularJS, and quite frankly I loved the concepts of a website that fetches json to handle subsequent requests, however I still feel like Javascript is far too slow for what I want to do on a server.

I have recently been hired to build an online auction website. I built two mockups, one with AngularJS and one in PHP. The PHP website is much faster on initial load and handling large requests, but the AngularJS-powered site is much more responsive on simultaneous requests, and writing JavaScript and HTML frontend is much easier, so I got to thinking that I might just make a counterpart to AngularJS using PHP, JS, and HTML, giving me the best of both worlds. As I go forward in implementing the design, I started to question if AJAX was the right tool for the job. It seems like I could use a simple node.js websocket server as an intermediary to between the client-side JS and PHP, passing commands from the client over websockets to the server, then passing the data back.

Would you consider this premature optimization, and if not, would removing the HTTP overhead really make much difference at all in terms of bandwidth and request size?

答:
If you want typical request-response client-server communication use ajax.

If you want bidireccional communication and for example sending updates from the server to the clients use web sockets.

"It seems like I could use a simple node.js websocket server as an intermediary to between the client-side JS and PHP, passing commands from the client over websockets to the server, then passing the data back."

I don't see the point in doing something like that. If you want to use websocket use node for the server side of you application, why do you want to use node.js only as a "websocket proxy" and use php for server side operations?. What is the justification for this complexity?


问:
Equidistant polygons
Consider these polygons:

For reasons of simplicity I only consider triangles or polygons with 4 vertices.
These shapes are specified by the vertices, the output of the program should be modified vertices.

I am trying to find an algorithm to create a space between the polygons, the colored area depicts the space:

I have tried these things:

scaling each polygon around it's center of gravity

scaling the bounding box of each polygon

None of those worked.

I am thinking of an algorithm to modify the corner points of each polygon to create the equidistant space.

What would be a feasible algorithm for this problem?

答:
What determines the size of the space?

I think you're focusing on the vertices when you should be focusing on the lines.

Since you've changed the shape as well as the size, it would seem to be pretty easy. Given a gap width W, slice W/2 each side of all internal lines and W away from all borders. Then revise the vertices locations to match the new borders.

Title: Equidistant polygons


答:
In Java, the enum is a reference type (don't let that little 'e' fool you).  You can do neat things with it like define methods.  A classic example of that is the Operation enum being defined as:

public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}
//Elsewhere:
Operation op = Operation.PLUS;
double two = op.eval(1, 1);
```

<p>And you can see... yep, it has methods and so its not a primitive.  They <em>are</em> Objects.</p>

<p>There is also some magic that happens in the compiler as described in the Java Enum Tutorial:</p>

<blockquote>
  <p>The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.</p>
</blockquote>

<p>And I'll certainly agree that its annoying that this isn't mentioned in the javadocs.</p>

<p>The values that are returned from the <code>values()</code> call is an array that one can then iterate over.</p>

<pre class="lang-java prettyprint-override"><code>class Demo {
    enum DayOfWeek {
        U, M, T, W, R, F, S
    }

    public static void main (String[] args) {
        for (DayOfWeek day : DayOfWeek.values()) {
            System.out.println(day.toString());
        }
    }
}
</code>```

This prints out:

```
U
M
T
W
R
F
S
```

Run this code at ideone

Why no next?  Well, given the ability to get the values() array it fills all the use cases for the next() method and is a bit more powerful.

If you really do want the next() method it takes takes a little bit of a hoop to get the array into an Iterator object (which is itself a replacement for the Enumeration type - see the javadoc):

import java.util.*;

class Demo {
    enum DayOfWeek {
        U, M, T, W, R, F, S
    }

    public static void main (String[] args) {
        Iterator days = Arrays.asList(DayOfWeek.values()).iterator();
        while(days.hasNext()) {
            System.out.println(days.next());
        }
    }
}
```

<p><sup><sub>Run this code at ideone</sub></sup></p>

<p>So again, the reason that its not there is that its not needed.  You can get an array back from the enum quite easily and iterate over that, or convert that array into an <code>Iterator</code> allowing you to call <code>next()</code>.</p>

<p>There is also possibly the confusion that would be had trying to make the <code>enum</code> and <code>Enumeration</code> look too similar (they already look too similar) and trying to make the <code>enum</code> look more like the <code>Enumeration</code> with the same method calls  would further confuse things.  That said, this is just speculation.</p>

<p>Fundamentally, the Java <code>enum</code> is much like the C <code>enum</code> with the ability to have some methods on the side.  Its a bit more constrained you can't have them be specific numbers behind the scenes as you can in C:</p>

<pre class="lang-c prettyprint-override"><code>/* This is C */
enum cardsuit {
    CLUBS    = 1,
    DIAMONDS = 2,
    HEARTS   = 4,
    SPADES   = 8
};
</code>```

People sometimes point to Pascal and say succ can be called on an enum there, why not in Java?  Pascal enums are ordinal types while C enums are not.  Java borrows from C rather than Pascal.

There's nothing saying that you can't define your own next() or prev() function. Its rather easy to do after getting around an annoyance of forward references.

class Demo {
    enum DayOfWeek {
        U, M, T, W, R, F, S;

        private DayOfWeek n;
        private DayOfWeek p;

        static {
            U.n = M; U.p = S;
            M.n = T; M.p = U;
            T.n = W; T.p = M;
            W.n = R; W.p = T;
            R.n = F; R.p = W;
            F.n = S; F.p = R;
            S.n = U; S.p = F;
        }

        public DayOfWeek next() { return this.n; }
        public DayOfWeek prev() { return this.p; }

    }

    public static void main (String[] args) {
        System.out.println(DayOfWeek.M.next());
        System.out.println(DayOfWeek.U.prev());
    }
}
```

```
T
S
```

So...

The enum was borrowed from the C tradition of an enum, not the Pascal tradition of ordinal types

They didn't want to confuse enum with Enumeration

You have the ability to get all the values back easily with an iterable type

You can define a next() method that works any way you want it to.

Body:
In Java, the enum is a reference type (don't let that little 'e' fool you).  You can do neat things with it like define methods.  A classic example of that is the Operation enum being defined as:

public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}
//Elsewhere:
Operation op = Operation.PLUS;
double two = op.eval(1, 1);

And you can see... yep, it has methods and so its not a primitive.  They are Objects.

There is also some magic that happens in the compiler as described in the Java Enum Tutorial:

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

And I'll certainly agree that its annoying that this isn't mentioned in the javadocs.

The values that are returned from the values() call is an array that one can then iterate over.

class Demo {
    enum DayOfWeek {
        U, M, T, W, R, F, S
    }

    public static void main (String[] args) {
        for (DayOfWeek day : DayOfWeek.values()) {
            System.out.println(day.toString());
        }
    }
}

This prints out:

U
M
T
W
R
F
S

Run this code at ideone

Why no next?  Well, given the ability to get the values() array it fills all the use cases for the next() method and is a bit more powerful.

If you really do want the next() method it takes takes a little bit of a hoop to get the array into an Iterator object (which is itself a replacement for the Enumeration type - see the javadoc):

import java.util.*;

class Demo {
    enum DayOfWeek {
        U, M, T, W, R, F, S
    }

    public static void main (String[] args) {
        Iterator days = Arrays.asList(DayOfWeek.values()).iterator();
        while(days.hasNext()) {
            System.out.println(days.next());
        }
    }
}

Run this code at ideone

So again, the reason that its not there is that its not needed.  You can get an array back from the enum quite easily and iterate over that, or convert that array into an Iterator allowing you to call next().

There is also possibly the confusion that would be had trying to make the enum and Enumeration look too similar (they already look too similar) and trying to make the enum look more like the Enumeration with the same method calls  would further confuse things.  That said, this is just speculation.

Fundamentally, the Java enum is much like the C enum with the ability to have some methods on the side.  Its a bit more constrained you can't have them be specific numbers behind the scenes as you can in C:

/* This is C */
enum cardsuit {
    CLUBS    = 1,
    DIAMONDS = 2,
    HEARTS   = 4,
    SPADES   = 8
};

People sometimes point to Pascal and say succ can be called on an enum there, why not in Java?  Pascal enums are ordinal types while C enums are not.  Java borrows from C rather than Pascal.

There's nothing saying that you can't define your own next() or prev() function. Its rather easy to do after getting around an annoyance of forward references.

class Demo {
    enum DayOfWeek {
        U, M, T, W, R, F, S;

        private DayOfWeek n;
        private DayOfWeek p;

        static {
            U.n = M; U.p = S;
            M.n = T; M.p = U;
            T.n = W; T.p = M;
            W.n = R; W.p = T;
            R.n = F; R.p = W;
            F.n = S; F.p = R;
            S.n = U; S.p = F;
        }

        public DayOfWeek next() { return this.n; }
        public DayOfWeek prev() { return this.p; }

    }

    public static void main (String[] args) {
        System.out.println(DayOfWeek.M.next());
        System.out.println(DayOfWeek.U.prev());
    }
}

T
S

So...

The enum was borrowed from the C tradition of an enum, not the Pascal tradition of ordinal types

They didn't want to confuse enum with Enumeration

You have the ability to get all the values back easily with an iterable type

You can define a next() method that works any way you want it to.


问:
REPL - Do You Find It Useful?
Recently I started learning Clojure and downloaded Clojure-Box for Windows which came with SLIME and have been fiddling around with Clojure using the REPL mode. Now, I have starting learning many languages that have REPL available (F#, Python, Haskell) but have never used it until I started with Clojure and I realized how much of a help it is.

I was wondering how many people use REPL for the languages that have them available. If you don't use them, what is your reasoning not to? If you do use them, do you use them for testing code or just for learning languages?

答:
For Java with Hotspot-based virtual machines, you can update (with certain rules to obey) classes while running just by saving the revised source code in your IDE.

If your main loop invokes said classes repeatedly you effectively have a simple REPL which is very helpful.

Title: REPL - Do You Find It Useful?


问:
Why do some functional programming languages use a space for function application?
Having looked at some languages for functional programming, I always wondered why some fp-languages use one or more whitespace characters for function application (and definition), whereas most (all?) imperative/object-oriented languages are using parentheses, which seems to be the more mathematical way. I also think that the latter style is much more clear and readable than without the parens.

So if we have a function f(x) = x² there are the two alternatives to calling it:

FP: f x

Examples:

ML, Ocaml, F#

Haskell

LISP, Scheme (somehow)

Non-FP: f(x)

Examples:

Almost all imperative languages (I know, see the comments/answers)

Erlang

Scala (also allows "operator notation" for single arguments)

What are the reasons for "leaving out" the parentheses?

答:
Both premises are wrong.

These functional languages don't use space for function application. What they do is simply parse any expression that comes after a function as an argument.

GHCi> f 3

  4

  GHCi> f(3)

  4

  GHCi> (f)3

  4

course if you use neither a space nor parens then it normally won't work, simply because the expression isn't properly tokenised

GHCi> f3

  <interactive>:7:1:

      Not in scope: ‘f3’

      Perhaps you meant ‘f’ (line 2)

But if these languages were restricted to 1-character variable names then it would work too.

Nor do mathematics conventions normally require parentheses for function application. Not only will mathematicians often write sin x – for linear functions (usually called linear operators then) it's also very much usual to write the argument without parens, perhaps because (much like any function in functional programming) linear functions are often handled without directly supplying an argument.

So really, your question boils down to: why to some languages require parentheses for function application? Well, apparently some people, like you, consider this more readable. I strongly disagree with that: one pair of parens is nice, but as soon as you have more of two of them nested it starts to get confusing. Lisp code demonstrates this best, and pretty much all functional languages would look similarly cluttered if you needed parens everywhere. This doesn't happen so much in imperative languages, but mainly because these languages aren't expressive enough to write concise, clear one-liners in the first place.