答:
To directly answer your question: Never echo static text or HTML. Leave that outside of your PHP.

```<code><?php echo "<p>Hello World</p>"; // Alway wrong. ?>

<p>Hello World</p>  <!-- Does the same thing, faster, and is more readable. -->
</code>```

Escaping to PHP is a waste if all you are going to do is pass in static text or static html. All code inside of <?php ?> is sent to PHP to be interpreted.
 This means your website is slower and you are wasting electricity if you are passing large amounts of static text to PHP for no reason. (Sometimes there is a reason.)

Best practice is to have your logic and grunt work in files without any HTML, only PHP.

The way I like to do this is with an MVC framework. I have pure PHP in the models and controllers, and a mixture of HTML and PHP in the views. You don't need an MVC framework; you could just stick your mixture of HTML in template files, which you then include in your pure PHP files.

Once you have your variables (which don't include HTML in them) created in pure PHP files, you can pass them off to the file with your HTML. There, and only there, is it fine to mix HTML and PHP. But, and this is an important but, when working with files that have HTML, keep the PHP to a minimum.

Luckily, PHP comes with friendly tools to make PHP easier to read when mixed with html.

Alternative Syntax

The best practice is to use regular PHP syntax when writing pure PHP, but the alternative syntax, when mixing PHP and HTML.

In regular PHP files without any HTML:

```<code>if ($something) {
  do_something(); // do_something() shouldn't echo or print.
}
</code>```

This is beautiful for pure PHP, but not ideal when escaping from HTML. In particular, the closing braces are often hard to understand when they show up in big piles of HTML.

It seems, based on your question that you would have written, in a file mixing HTML and PHP, this:

```<code><?php
  if ($something) {
    echo '<p>Hello World.</p>';
  }
?>
</code>```

For the reasons described above, we want the HTML not to be sent to PHP. We do this like so:

```<code><?php if ($something) { ?>
  <p>Hello World.</p>
<?php } ?>
</code>```

We got our HTML out of our PHP tags, which is an improvement. But we could go further.

Notice how uninformative the closing brace is? We don't know if it is closing a loop or an if statement. This seems trivial in the above example, but there are often dozens of lines of HTML inside of if/endif inside of a loop/endloop.

The best practice is that in a file mixing PHP and HTML, you use the alternative syntax, which omits opening and closing braces ({ }):

```<code><?php if ($something): ?>
  <p>Hello world.</p>
<?php endif; ?>
</code>```

Aside from the semantics of the new syntax (: and endif; instead of { and }), you should notice two things:

Again, the HTML and text, while controlled by PHP, is outside of the <?php ?> tags, so it is not interpreted. For the reasons described above, this is good.

This is much more informative than if this were all php including random closing braces (<?php } ?>) closing things that are hard to find where they opened (because they are mixed with a buch of messy looking HTML). Again, imagine a big HTML file with loops and if statements. Specifying what you are closing can clarify a lot.

The same template friendly syntax can be used for loops as well:

```<code><?php foreach ($things as $thing): ?>
  <li><?php echo $thing; ?></li>
<?php endforeach; ?>
</code>```

Short Tags

Another great tool provided by PHP which, again, you only want to use when mixing PHP and HTML together, is short tags. You might have to turn short tags on in php.ini file. Once turned on, short tags make everything even more readable.

Without short tags, you have to write <?php echo $something; ?> but with short tags you can write <?=$something?> and it will have the exact same result.

When combining short tags and the alternative PHP syntax, you can really write some elegant HTML files, which include PHP elements. Taking our last loop example (just the part inside the loop), short tags allow us to reduce:

```<code><li><?php echo $thing; ?></li>
</code>```

to

```<code><li><?=$thing?></li>
</code>```

which is much more readable.

Could we go further? Yes. Using various templating systems you can do things like:

```<code><li>{thing}</li>
</code>```

Which is amazingly readable. Templating systems, however, are way outside the scope of the original question (which I left a while ago anyway).

Title: Which is better: to include HTML inside PHP code or outside it?

Body:
Look at this:

```<code><?php
echo "Hello World";
?>
<br />
<?php
echo "Welcome";
?>
</code>```

And now look at this:

```<code><?php
echo "Hello World";
echo "<br />";
echo "Welcome";
?>
</code>```

Which one of the above examples is considered to better (at least from performance point of view)?.

I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.

Body:
To directly answer your question: Never echo static text or HTML. Leave that outside of your PHP.

<?php echo "<p>Hello World</p>"; // Alway wrong. ?>

<p>Hello World</p>  <!-- Does the same thing, faster, and is more readable. -->

Escaping to PHP is a waste if all you are going to do is pass in static text or static html. All code inside of <?php ?> is sent to PHP to be interpreted.
 This means your website is slower and you are wasting electricity if you are passing large amounts of static text to PHP for no reason. (Sometimes there is a reason.)

Best practice is to have your logic and grunt work in files without any HTML, only PHP.

The way I like to do this is with an MVC framework. I have pure PHP in the models and controllers, and a mixture of HTML and PHP in the views. You don't need an MVC framework; you could just stick your mixture of HTML in template files, which you then include in your pure PHP files.

Once you have your variables (which don't include HTML in them) created in pure PHP files, you can pass them off to the file with your HTML. There, and only there, is it fine to mix HTML and PHP. But, and this is an important but, when working with files that have HTML, keep the PHP to a minimum.

Luckily, PHP comes with friendly tools to make PHP easier to read when mixed with html.

Alternative Syntax

The best practice is to use regular PHP syntax when writing pure PHP, but the alternative syntax, when mixing PHP and HTML.

In regular PHP files without any HTML:

if ($something) {
  do_something(); // do_something() shouldn't echo or print.
}

This is beautiful for pure PHP, but not ideal when escaping from HTML. In particular, the closing braces are often hard to understand when they show up in big piles of HTML.

It seems, based on your question that you would have written, in a file mixing HTML and PHP, this:

<?php
  if ($something) {
    echo '<p>Hello World.</p>';
  }
?>

For the reasons described above, we want the HTML not to be sent to PHP. We do this like so:

<?php if ($something) { ?>
  <p>Hello World.</p>
<?php } ?>

We got our HTML out of our PHP tags, which is an improvement. But we could go further.

Notice how uninformative the closing brace is? We don't know if it is closing a loop or an if statement. This seems trivial in the above example, but there are often dozens of lines of HTML inside of if/endif inside of a loop/endloop.

The best practice is that in a file mixing PHP and HTML, you use the alternative syntax, which omits opening and closing braces ({ }):

<?php if ($something): ?>
  <p>Hello world.</p>
<?php endif; ?>

Aside from the semantics of the new syntax (: and endif; instead of { and }), you should notice two things:

Again, the HTML and text, while controlled by PHP, is outside of the <?php ?> tags, so it is not interpreted. For the reasons described above, this is good.

This is much more informative than if this were all php including random closing braces (<?php } ?>) closing things that are hard to find where they opened (because they are mixed with a buch of messy looking HTML). Again, imagine a big HTML file with loops and if statements. Specifying what you are closing can clarify a lot.

The same template friendly syntax can be used for loops as well:

<?php foreach ($things as $thing): ?>
  <li><?php echo $thing; ?></li>
<?php endforeach; ?>

Short Tags

Another great tool provided by PHP which, again, you only want to use when mixing PHP and HTML together, is short tags. You might have to turn short tags on in php.ini file. Once turned on, short tags make everything even more readable.

Without short tags, you have to write <?php echo $something; ?> but with short tags you can write <?=$something?> and it will have the exact same result.

When combining short tags and the alternative PHP syntax, you can really write some elegant HTML files, which include PHP elements. Taking our last loop example (just the part inside the loop), short tags allow us to reduce:

<li><?php echo $thing; ?></li>

to

<li><?=$thing?></li>

which is much more readable.

Could we go further? Yes. Using various templating systems you can do things like:

<li>{thing}</li>

Which is amazingly readable. Templating systems, however, are way outside the scope of the original question (which I left a while ago anyway).


问:
What factors should I consider when logging a (JSF) web-app?
I've recently read the article The Problem with logging and was wondering about my current logging strategy.

Usualy I use Log4J in my projects and just have to decide which line/attributes I would like to log.

This strategy worked well for me in the past for all my projects without user-interaction.

Now I want to set up logging for a WebApp with user-interaction like login, session-management,
personalized user pages, etc. and was wondering what would be best practice.

To clarify:

I don't ask you to help me decide what informations I have to log because that I know for myself (or find
information in articles on this site or google).

I'm asking about the things connected with this topic:

should I bind every log message to the corresponding user for traceability

should I open up a new log file for every session

are there other good libraries especially for logging webapps

should I only log fatal errors in file and handle minor errors inside the view (e.g. show user)

and how chatty should I be in those messages shown to the user

I also know that this is a broad topic and that this question can easily be answered by
"it's personal flavor" or "it depends" but I would highly appreciate anyone who's willing to give me
some useful hints.

Thanks in advance

答:
You're right in that this question is very much answered by, "what are your requirements", but this is my opinion.

Be sure that any event initiated by a user is traceable back to the user. Each logged event should state who is executing the event, or at least contains a transaction ID that can be traced back to the user creating the transaction. This will allow you to fulfill non-repudiation requirements where a user would not be able to deny creating the transaction.

I wouldn't recommend creating a new log file for each session. A better approach would be to create new log files once they reach a certain size (10 MB for instance). Or, just creating a new log file each day or week (depending on the size of the files). If there a lot of events being logged, a database may be better as it can handle large volumes of data easier and you will be able to query the results as needed.

For libraries, there are plenty out there for Java EE. Log 4J is fine. I've also used Apache's Commons Logging, but I prefer the combination of SLF4J and Logback personally - they are easy to use and integrate well with other logging frameworks.

You may also want to look into Aspect Oriented Programming to create the common logging events that will appear in a lot of methods. Specifically, AOP can help create debug logging for method enter / exit / throw. I've done AOP with Spring and can say it is very helpful keeping the code clean.

Speaking of logging levels, it will be very beneficial to make good use of each level as appropriate and create a secure way to change the level at runtime if you are experiencing issues.

Log only errors that would be beneficial to have logged. Tautological, maybe, but logging can often get out of hand. Having too many records to sift through means you will not be able to identify outliers or actual problems. Logging too little means you may miss an issue (if you didn't log it, it never happened), so, make good use of logging levels for these reasons as well. There may be no reason to log a user validation error (e.g., creating a new password less than the allowable number of chacters), but system errors should always be logged (e.g., unable to contact the database).

Likewise, only notify the user of what they need to know. They will need to know if the password they entered failed validation and why, but they don't need to know if the database is down (they only need to know that the site is experiencing issues and what they can do in the mean time - i.e., call a support number). Chattiness to the user should be kept to a minimum as constant error notifications that they can't personally resolve would be a poor user experience.

I suggest you take a look at OWASP's Logging Cheat Sheet for some more information on logging best practices.

OwnerDisplayName: SimonSez

ContentLicense: CC BY-SA 3.0


问:
How to execute a Ruby file in Java, capable of calling functions from the Java program and receiving primitive-type results?
I do not fully understand what am I asking (lol!), well, in the sense of if it is even possible, that is. If it isn't, sorry.

Suppose I have a Java program. It has a Main and a JavaCalculator class. JavaCalculator has some basic functions like

```<code>public int sum(int a,int b) {
   return a + b
}
</code>```

Now suppose I have a ruby file. Called MyProgram.rb.

MyProgram.rb may contain anything you could expect from a ruby program. Let us assume it contains the following:

```<code>class RubyMain
  def initialize
    print "The sum of 5 with 3 is #{sum(5,3)}"
  end
  def sum(a,b)
    # <---------- Something will happen here
  end
end

rubyMain = RubyMain.new
</code>```

Good. Now then, you might already suspect what I want to do:

I want to run my Java program

I want it to execute the Ruby file MyProgram.rb

When the Ruby program executes, it will create an instance of JavaCalculator, execute the sum function it has, get the value, and then print it.

The ruby file has been executed successfully.

The Java program closes.

Note: The "create an instance of JavaCalculator" is not entirely necessary. I would be satisfied with just running a sum function from, say, the Main class.

My question: is such possible? Can I run a Java program which internally executes a Ruby file which is capable of commanding the Java program to do certain things and get results? In the above example, the Ruby file asks the Java program to do a sum for it and give the result.

This may sound ridiculous. I am new in this kind of thing (if it is possible, that is).

WHY AM I ASKING THIS?

I have a Java program, which is some kind of game engine. However, my target audience is a bunch of Ruby coders. I don't want to have them learn Java at all. So I figured that perhaps the Java program could simply offer the functionality (capacity to create windows, display sprites, play sounds...) and then, my audience can simply code with Ruby the logic, which basically justs asks my Java engine to do things like displaying sprites or playing sounds.

That's when I though about asking this.

答:
Since you don’t seem to believe us.

Here's how to run ruby code from Java, using JRuby. JRuby is not “a different tool” it is just the JAR file you need to be able to run Ruby on top of Java. It’s as simple as

```<code>package com.example;

import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.ScriptingContainer;

public class Main {

    private ScriptingContainer ruby;

    public static void main(String[] args) {
        new Main().run();
    }

    public void run() {
        ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
            // Assign the Java objects that you want to share
        ruby.put("main", this);
            // Execute a script (can be of any length, and taken from a file)
        Object result = ruby.runScriptlet("main.hello_world");
            // Use the result as if it were a Java object
        System.out.println(result);
    }

    public String getHelloWorld() {
        return "Hello, worlds!";
    }

}
</code>```

As you can see it is even so smart to translate from Ruby’s hello_world to Java’s getHelloWorld naming convention.

Body:
Since you don’t seem to believe us.

Here's how to run ruby code from Java, using JRuby. JRuby is not “a different tool” it is just the JAR file you need to be able to run Ruby on top of Java. It’s as simple as

package com.example;

import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.ScriptingContainer;

public class Main {

    private ScriptingContainer ruby;

    public static void main(String[] args) {
        new Main().run();
    }

    public void run() {
        ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
            // Assign the Java objects that you want to share
        ruby.put("main", this);
            // Execute a script (can be of any length, and taken from a file)
        Object result = ruby.runScriptlet("main.hello_world");
            // Use the result as if it were a Java object
        System.out.println(result);
    }

    public String getHelloWorld() {
        return "Hello, worlds!";
    }

}

As you can see it is even so smart to translate from Ruby’s hello_world to Java’s getHelloWorld naming convention.


问:
Migrating from one PHP framework to another
I'm working with a web company that's approaching a point where it will likely need re-think the product as a V2 - due to outgrowing some of its V1 foundations and principles that have been built into virtually everything, from the data model to the user interfaces. For various reasons, this evolution might involve a migration from CakePHP (with which the V1 has been built) to Symfony or Zend.

I would like to ask for some experienced views on how people might have managed a transition like this for a website that has significant traffic and generates revenue. I don't want to open up a discussion on the pro's & con's of different PHP frameworks, or why this migration might be needed. Rather, I would be very interested in hearing whether there are some practical alternatives to essentially building a V2 from scratch alongside the V1 for a couple of months - and locking up precious coding time for the duration of this intense period. An example of such an alternative might be migrating an app in parts over a longer period of time.

I'd be grateful for any views from people who might have managed or been involved in such transitions.

Thanks in advance.

答:
The first thing to consider is that rewriting a product from scratch is something you should never do. This is particularly true when the current version is already making you money. Basically, you're going to spend 6 months of time, just to get back to where you were 6 months ago. Only now, you've got more bugs (or at least, different bugs), re-introduced bugs that had already been fixed in the old code, and you're six months behind where you could've been at, had you been adding features to the old codebase.

CakePHP, Zend and Symphony are largely the same (i.e. they're all MVC-style frameworks on top of PHP), so I'm not sure what advantage you'd have moving from one to the other. There's certainly differences in feature set, but are they really worth setting yourself back all that time? For the amount of time you'd spend re-writing from scratch in Zend or whatever, could you spend the same amount of time adding the required features to Cake?

In my opinion, you'd be better off slowly refactoring your existing code over time, rather than starting completely from scratch with a new framework.

Of course, this is just my opinion. I know it's tempting to drop existing (ugly, old) code and start from scratch, but for established products that are already working, there is usually little to gain and a whole lot to lose.

ContentLicense: CC BY-SA 2.5


问:
Is there a way to display the stack during recursion method?
I'm trying to learn recursion.  I copied this bit of code from my book and added the displays to help me trace what the method is doing and when.

```<code>public static void main(String[] args) {

    System.out.println(sum(4));

}//main

public static int sum(int n) {
    int sum;
    System.out.println("n = " + n + "\n");
    if (n == 1)
        sum = 1;
    else
        sum = sum(n - 1) + n;
    System.out.println("n after function = " + n + "\n");
    System.out.println("sum after function = " + sum + "\n");
    return sum;
}
</code>```

Here's the results:

n = 4

n = 3

n = 2

n = 1

n after function = 1

sum after function = 1

n after function = 2

sum after function = 3

n after function = 3

sum after function = 6

n after function = 4

sum after function = 10

10

I'm getting hung up on what's being stored in the stack, or perhaps how it's being stored.

Is there a way to display what's in the stack while n is counting down to 1?

This is an odd concept - it's like an invisible loop storing values in a way I don't understand.

答:
You can access the stack, but not the values on the stack.</p>

```<code>public class StackTrace {

    public static void main(String[] args) {
        recurse(10);
    }

    static void recurse(int depth) {
        for (StackTraceElement each: new Exception().getStackTrace()) System.out.println(each);
        if (depth > 0) recurse(depth - 1);
    }

}
</code>```

Body:
You can access the stack, but not the values on the stack.

public class StackTrace {

    public static void main(String[] args) {
        recurse(10);
    }

    static void recurse(int depth) {
        for (StackTraceElement each: new Exception().getStackTrace()) System.out.println(each);
        if (depth > 0) recurse(depth - 1);
    }

}


问:
Presentation VS Application layer in DDD
I have trouble drawing a clear line between Presentation and Application layer in Domain Driven Design.

Where should Controllers, Views, Layouts, Javascript and CSS files go?

Is it in the Application or the Presentation layer?

And if they go all together in the same layer, what contains the other one? Is it empty?

答:
Just because someone created and named "Application Layer" and "Presentation Layer" doesn't mean your application should have them.
You should create layers AFTER you created substantial amount of code which you grouped together and want to name this group for sake of communication between developers and clarity of code.

From point of DDD. Application Layer is everything that is not Domain layer. Which includes application logic, presentation and application services.


答:
Domain Driven Design has nothing to do with either Presentation layer or Application layer. DDD is a methodology whose main focus is on the Domain layer. That is, DDD does not impose any constraints regarding any other layer except for the Domain layer and Your question as well could be asked in the context of any other methodology.

That being said, it's very common to use a four-layer architecture for DDD applications. Here's an example of one such application showing the layers and their intended use: DDDSample Architecture. So, if you choose to use this architecture your views and layouts would go to the Interfaces layer and the controllers, if interface-independent, would go to the Application layer.

You might as well choose any other kind of architecture, as I've said DDD does not impose constraints. There are many MVC frameworks out there that have different structures and yet could also be used for DDD applications. Then, of course, you would place Your views and layouts accordingly.

Title: Presentation VS Application layer in DDD

Body:
I have trouble drawing a clear line between Presentation and Application layer in Domain Driven Design.

Where should Controllers, Views, Layouts, Javascript and CSS files go?

Is it in the Application or the Presentation layer?

And if they go all together in the same layer, what contains the other one? Is it empty?


答:
Of course we could also write a program that maintains its own, C style, stack, where we push all arguments and locals and return values on the stack

```<code>public class Main {

    public static void main(String[] args) {
        new Main().run();
    }

    int[] stack = new int[100];
    int base = 0;

    public void run() {

        // push arguments on stack
        stack[base] = 4;
        // increase base pointer and call method
        base += 1;
        call();
        // retrieve result
        int result = stack[base];
        // print it
        System.out.println(result);

    }

    public void call() {
        // push locals on stack and increase base, now arg n
        // is at base - 2 and local sum is at base - 1
        stack[base] = 0;
        base += 1;
        // test if n equals 1
        if (stack[base - 2] == 1) {
            // if yes set sum to 1
            stack[base - 1] = 1;
        } else {
            // push new argument on stack
            stack[base] = stack[base - 2] - 1;
            // increase base pointer and call method
            base += 1;
            call();
            // add result to sum
            stack[base - 1] += stack[base];
            // add n to sum
            stack[base - 1] += stack[base - 2];
        }
        // cache return value
        int result = stack[base - 1];
        // decrease base pointer by size of both args and locals
        base -= 2;
        // push result on stack
        stack[base] = result;
    }
}
</code>```

the programs uses the calling convention that callers are responsible for pushing arguments and increasing the base pointers, and receivers are responsible for resetting the base pointer  and leaving a return value on the stack.

This is how method calls happen at the machine level.

Title: Is there a way to display the stack during recursion method?

Body:
I'm trying to learn recursion.  I copied this bit of code from my book and added the displays to help me trace what the method is doing and when.

```<code>public static void main(String[] args) {

    System.out.println(sum(4));

}//main

public static int sum(int n) {
    int sum;
    System.out.println("n = " + n + "\n");
    if (n == 1)
        sum = 1;
    else
        sum = sum(n - 1) + n;
    System.out.println("n after function = " + n + "\n");
    System.out.println("sum after function = " + sum + "\n");
    return sum;
}
</code>```

Here's the results:

n = 4

n = 3

n = 2

n = 1

n after function = 1

sum after function = 1

n after function = 2

sum after function = 3

n after function = 3

sum after function = 6

n after function = 4

sum after function = 10

10

I'm getting hung up on what's being stored in the stack, or perhaps how it's being stored.

Is there a way to display what's in the stack while n is counting down to 1?

This is an odd concept - it's like an invisible loop storing values in a way I don't understand.

Body:
Of course we could also write a program that maintains its own, C style, stack, where we push all arguments and locals and return values on the stack

public class Main {

    public static void main(String[] args) {
        new Main().run();
    }

    int[] stack = new int[100];
    int base = 0;

    public void run() {

        // push arguments on stack
        stack[base] = 4;
        // increase base pointer and call method
        base += 1;
        call();
        // retrieve result
        int result = stack[base];
        // print it
        System.out.println(result);

    }

    public void call() {
        // push locals on stack and increase base, now arg n
        // is at base - 2 and local sum is at base - 1
        stack[base] = 0;
        base += 1;
        // test if n equals 1
        if (stack[base - 2] == 1) {
            // if yes set sum to 1
            stack[base - 1] = 1;
        } else {
            // push new argument on stack
            stack[base] = stack[base - 2] - 1;
            // increase base pointer and call method
            base += 1;
            call();
            // add result to sum
            stack[base - 1] += stack[base];
            // add n to sum
            stack[base - 1] += stack[base - 2];
        }
        // cache return value
        int result = stack[base - 1];
        // decrease base pointer by size of both args and locals
        base -= 2;
        // push result on stack
        stack[base] = result;
    }
}

the programs uses the calling convention that callers are responsible for pushing arguments and increasing the base pointers, and receivers are responsible for resetting the base pointer  and leaving a return value on the stack.

This is how method calls happen at the machine level.


问:
For a front-end application broken down in a MV* manner, should I have models dedicated to UI logic?
I am not talking about simple UI logic like clicking a button directs you to another page, but where one action may result in several different of behavior depending on current application state, and may also trigger response in other parts of the application. Currently my view publishes all UI event so the response can be delegated to other parts. The problem is which other part? In order to avoid writing 'fat' controllers that hold arbitrary amount of domain logic, I thought it might be nice to have a non-persistent object that models UI behavior, but am not sure if this makes sense or if I am just pushing the problem around and being object-happy?</p>

答:
Well, in my point of view, whatever logic there is for presentation should go into View Helpers. Controllers should only orchestrate the connection between Views and Models by interpreting user actions.

Models should be bare-bone, minimal. I only use them to validate stuff. And than do all the business related things in your classes related to your business logic. Let the Models be "Request Models" as defined by Robert C. Martin.

Uncle Bob's approach to this problem is great and it really helps. Try it. It may be the answer to all your dilemmas.


问:
Better php framework for shared hosting
I need to develop an app for booking appointments. This is going to be hosted in a shared server. So performance is the most important thing. I have used symfony2. I quite liked the framework. But seems to be heavy.

Which framework would suit me considering my requirements? I have shortlisted three frameworks yii, symfony2 and ZF2. I am not asking which framework is better.

All the three are good frameworks. I want to know which will suit my requirements. My first priority would be performance (I will be using AJAX wherever possible), second would be maintenance and development time and third community support. Or should I use my own handlers to separate views and logic and just use raw php?

答:
I think YII best meets your requirements since:

it is fast

http://www.yiiframework.com/performance/
and even more so if you can implement APC which I was able to do on shared hosting provider blue host using the instructions here: http://rk.md/2011/install-apc-accelerator-bluehost-shared-host/
This speed will allow you to stay longer on a shared host before exhausting resources.

Maintenance is simple by pointing the index file to the latest install, with regression equally simple.

Development time is short due to excellent scaffolding provided by the GII module  http://www.yiiframework.com/doc/blog/1.1/en/prototype.scaffold

Community support is strong with active forums, wiki and extensions.

With the caveat that if you already know Symfony then that will be easiest for you to use, however that is not one of your stated requirements.

Title: Better php framework for shared hosting


答: If this is a commercial application that's your company's business, you may be better off going without a 3rd party framework entirely.  Then when time for v3 comes around, you wont be facing this same problem again.  And you'll never be in a situation where you have to keep adjusting your code in response to updates to the framework.  Frameworks are great for getting things up and running quickly, but if this is something a) core to your business and b) maintained over the long term, the value of the framework diminishes. </p>

Title: Migrating from one PHP framework to another

Body:
I'm working with a web company that's approaching a point where it will likely need re-think the product as a V2 - due to outgrowing some of its V1 foundations and principles that have been built into virtually everything, from the data model to the user interfaces. For various reasons, this evolution might involve a migration from CakePHP (with which the V1 has been built) to Symfony or Zend.

I would like to ask for some experienced views on how people might have managed a transition like this for a website that has significant traffic and generates revenue. I don't want to open up a discussion on the pro's & con's of different PHP frameworks, or why this migration might be needed. Rather, I would be very interested in hearing whether there are some practical alternatives to essentially building a V2 from scratch alongside the V1 for a couple of months - and locking up precious coding time for the duration of this intense period. An example of such an alternative might be migrating an app in parts over a longer period of time.

I'd be grateful for any views from people who might have managed or been involved in such transitions.

Thanks in advance.


问:
Which is better: to include HTML inside PHP code or outside it?
Look at this:

```<code><?php
echo "Hello World";
?>
<br />
<?php
echo "Welcome";
?>
</code>```

And now look at this:

```<code><?php
echo "Hello World";
echo "<br />";
echo "Welcome";
?>
</code>```

Which one of the above examples is considered to better (at least from performance point of view)?.

I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.

答:
It is generally considered bad form to output HTML code from PHP. There are several reasons for this, but the main one is that it is easier, especially in the long run, to maintain code if the HTML and PHP code is separated.

It is just like HTML, CSS and Javascript; it is just much easier and more practical to keep it separate.

Technically, however, it makes absolutely no difference how you output stuff. To PHP it is just bytes in a row.


问:
C++ Design: Functional Programming vs OOP
Design Question

Recently, I've been doing more and more FP in C++, mostly in the form of function templates and lambdas, and heavy overloading of a single function name.  I really like FP for some well-defined operations, but I've also noticed that as with OOP, one could easily fall into anti-patterns of spaghetti-code if one isn't careful (eg circular dependencies, which is a bigger issue for state-based code).

My question is, when thinking about adding new functionality, how do you decide between using a FP-paradigm or a OOP-paradigm?

I'm sensing it may have to do with identifying the invariants in the problem or in the design, but I'm not sure.

For example, without an OOP model/simplification of the real world, it may not be immediately obvious what a Dog or a Cat class is (what are its states?  what are its methods?).  Otoh, from a FP POV, a Eat() function simply allows an Animal to turn Food into Poop and Energy.  It's harder to imagine Eat() being anything else (for me, at least).

I'm looking more for C++ answers, but this question could apply to any sub-module in any language that can handle multiple paradigms.

答:
I think that OOP lends itself best to when you have state that you can't destroy and re-create on a whim, or where that's a bad model- for example, if you consider 3D rendering, then the state of the renderer is not trivially destroyed and recreated, and it would be suicide for your performance to do so each frame.

In C++, then you need to add the fact that it doesn't have garbage collection and many FP techniques depend upon that for remotely acceptable performance.

Otoh, from a FP POV, a Eat() function simply allows an Animal to turn
  Food into Poop and Energy. It's harder to imagine Eat() being anything
  else (for me, at least).

That's completely equivalent to the OOP variant. There's no meaningful difference between

```<code>struct Animal { ... };
std::tuple<Poop, Energy> Eat(Animal*, Food);
</code>```

and

```<code>class Animal {
public:
    std::tuple<Poop, Energy> Eat(Food);
};
</code>```

A functional variation would return a new Animal which has eaten.

Typically, I recursively divide my program to obtain modules/submodules/classes/functions and member functions, then I often attempt to implement those functions or member functions functionally if possible.

Body:
I think that OOP lends itself best to when you have state that you can't destroy and re-create on a whim, or where that's a bad model- for example, if you consider 3D rendering, then the state of the renderer is not trivially destroyed and recreated, and it would be suicide for your performance to do so each frame.

In C++, then you need to add the fact that it doesn't have garbage collection and many FP techniques depend upon that for remotely acceptable performance.

Otoh, from a FP POV, a Eat() function simply allows an Animal to turn
  Food into Poop and Energy. It's harder to imagine Eat() being anything
  else (for me, at least).

That's completely equivalent to the OOP variant. There's no meaningful difference between

struct Animal { ... };
std::tuple<Poop, Energy> Eat(Animal*, Food);

and

class Animal {
public:
    std::tuple<Poop, Energy> Eat(Food);
};

A functional variation would return a new Animal which has eaten.

Typically, I recursively divide my program to obtain modules/submodules/classes/functions and member functions, then I often attempt to implement those functions or member functions functionally if possible.


问:
Domino Solitaire Algorithm
Problem Statement -

Given a 2xN grid of numbers, the task is to find the most profitable tiling combination (each tile covers 2x1 cells; vertically or horizontally) covering all tiles.

I thought of approaching it in the greedy way, enqueuing the max possible for any cell, but it has a fallback that a low-profit choice at i, could yield a greater profit at i+n tiles.

So what should be the approach?

EDIT - Test Data Range - N<=105

Source - INOI 2008 Q Paper

UPDATE -
Working out the plausibility of a Dynamic programming Approach.

UPDATE 2 -
Worked out an answer using DP.

答:
Worked out a Dynamic Programming Approach to the problem -

```<code>int t[n][2]; //Stores grid values
int b[n]; //Stores best solution upto a particular column
b[0]= t[0][1]-t[0][0]; //Compute score for first column (Absolute Value)
b[1]= Max (b[0] + Score for column 1 vertically, Score for first 2 horizontal columns);
for i=0...n
  b[i]= Max ( b[i-1] + Score for column i vertically, b[i-2] + Score for horizontal columns i & i-1);
print b[n-1];
</code>```

Works efficiently on the given data set, with a linear time complexity!

Title: Domino Solitaire Algorithm

Body:
Worked out a Dynamic Programming Approach to the problem -

int t[n][2]; //Stores grid values
int b[n]; //Stores best solution upto a particular column
b[0]= t[0][1]-t[0][0]; //Compute score for first column (Absolute Value)
b[1]= Max (b[0] + Score for column 1 vertically, Score for first 2 horizontal columns);
for i=0...n
  b[i]= Max ( b[i-1] + Score for column i vertically, b[i-2] + Score for horizontal columns i & i-1);
print b[n-1];

Works efficiently on the given data set, with a linear time complexity!


答:
Here is one way to approach/describe the problem:

When looking at the 2xN grid, you can see that any tiling is uniquely defined in the following way:

For the most left block, see if it is horizontal or vertical. Then look at the next block.

Suppose 2 stands for horizontal and 1 stands for vertical your Tiling 1 can be written as: 121
whilst Tiling 2 can be written as 22

Given each vector, calculating the total cost should be straightforward.

Now you can use this algorithm:

Find a starting position (probably your own algorithm can do the trick here)

Given a window length (say 5) try all combinations of ones and zeros within the window and calculate what the maximum improvement is.

Optional: Execute this improvement

Shift the window, so instead of looking at the first 5 odd columns now look at odd column 2 to 6

If you are not yet at the end, go to step 2, else execute the improvement.

Optional: If you found any improvements, you can go to step 1

Title: Domino Solitaire Algorithm

Body:
Problem Statement -

Given a 2xN grid of numbers, the task is to find the most profitable tiling combination (each tile covers 2x1 cells; vertically or horizontally) covering all tiles.

I thought of approaching it in the greedy way, enqueuing the max possible for any cell, but it has a fallback that a low-profit choice at i, could yield a greater profit at i+n tiles.

So what should be the approach?

EDIT - Test Data Range - N<=105

Source - INOI 2008 Q Paper

UPDATE -
Working out the plausibility of a Dynamic programming Approach.

UPDATE 2 -
Worked out an answer using DP.


问:
Did "Viaweb" work in the browser without JavaScript and somehow use only Lisp?
I just read Beating the Averages, and Mr. Graham writes that they had a significant advantage over competitors because they used Lisp.

From what I understand, Viaweb was a WYSIWYG editor that ran in the browser for customers to create their own 'stores'. This is obviously inconceivable now to do without JavaScript, yet there is no talk of it at all on this article. Mr. Graham only talks about Lisp and nothing else.

So is (was?) it somehow possible to bypass JavaScript and use Lisp for the front and back ends?

答: Javascript wasn't widely used at the time. Viaweb was launched in 1995. JavaScript was only released in 1994 and was not in Internet Explorer until 1996. iframes didn't appear until 1996 and XMLHTTP request didn't show up for the first time until 1998, and not in browsers until later, so there was no AJAX when Viaweb was written. It's likely that they did without a client-side scripting language and reloaded the whole page whenever anything was done.</p>


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
Pointer can be thought of as a generalization of an index into an array.

Consider that a big array can be chopped off into a number of smaller, non-overlapping, variable-sized arrays. Now, these smaller arrays are what we usually think of as array. The bigger one is then the computer's entire memory space. The process of chopping off smaller arrays is called memory allocation.

A set of structures which are linked together by some pointers can be thought of as a directed graph.

Each vertex is a variable which can hold some value.

Some variables are pointers, and each pointer can have exactly one outgoing edge into something else.

Variables which are not pointers will not have any outgoing edge. They could have any number of incoming edge.

Title: What's a nice explanation for pointers?


问:
Training Camp Algorithm
Problem Statement -

The task is to find the most profitable contiguous segment of tests, given a sequence of test scores, with being allowed to drop any k tests from a chosen range.

The problem appears to be a DP problem at the outset, but complexity arises when the test drop condition comes into the picture.

What modifications can be made to the classic DP approach for this problem? Or is there a completely different approach to it?

Test Range - N <= 104

Source - INOI 2011 Q Paper

答:
Well, here how I would do it (without getting in too much detail)

I would keep track of the value of the all the results I dropped. I would probably put them in a sorted queue whose size is the allowed number of dropped test. It would sorted such as  the dropped test the nearest to zero is at the start. As I go trough the list with the traditional algorithm, I would do the following :

```<code>if I encounter a negative number
    if the queue is not full
        add it to the queue
    else
        if the new negative number is smaller (farther from zero) than the first number in the queue
            remove the first number from the queue
            add the new number to the queue
            add the removed number to the current subsequence value
        else
            add the new negative number to the current subsequence value
</code>```

That way, you always keep the subsequence without the worst mark of the sequence,  and if you encounter an even worst mark, you can restore the value of a previously  dropped mark to the value of your subsequence.

Title: Training Camp Algorithm

Body:
Well, here how I would do it (without getting in too much detail)

I would keep track of the value of the all the results I dropped. I would probably put them in a sorted queue whose size is the allowed number of dropped test. It would sorted such as  the dropped test the nearest to zero is at the start. As I go trough the list with the traditional algorithm, I would do the following :

if I encounter a negative number
    if the queue is not full
        add it to the queue
    else
        if the new negative number is smaller (farther from zero) than the first number in the queue
            remove the first number from the queue
            add the new number to the queue
            add the removed number to the current subsequence value
        else
            add the new negative number to the current subsequence value

That way, you always keep the subsequence without the worst mark of the sequence,  and if you encounter an even worst mark, you can restore the value of a previously  dropped mark to the value of your subsequence.


问:
How to get rid of my "Factory" class' countless else if statements
This is a web application based on actionscript 3.

I have all of my modules enumerated in a class, but I never know which modules actually come from database.

Let's say I have 20 modules in my application, but the user only has access to 10 of them. All I get are 10 strings from database (the module names) whenever the user clicks a module this string goes through the twenty else if statements until it matches the enumerated value and then it is displayed on screen.

Is there a way to optimize this?

The modules are not flex modules per say, they are just lazy instantiated  components.

答: You've got a key and you're trying to match it to a particular module using ifs, this is a key-value problem which should be solved by a dictionary or hashtable. Not familiar with Actionscript, but it must have dictionaries or hashtables. Does it have polymorphism or is it even strongly typed? Ideally you can put the databases string key into the dictionary as the key, and the associated module in as the value, but this may require the modules use a base type if Actionscript is strongly typed.</p>


问:
In functional programming, does having most of the data structures immutable require more memory usage?
In functional programming since almost all data structure are immutable, when the state has to change a new structure is created. Does this mean a lot more memory usage? I know the object oriented programming paradigm well, now I'm trying to learn about the functional programming paradigm. The concept of everything being immutable confuses me. It would seem like the a program using immutable structures would require much more memory than a program with mutable structures. Am I even looking at this in the right way?</p>

答: The only correct answer to this is "sometimes". There are a lot of tricks that functional languages can use to avoid wasting memory. Immutability makes it easier to share data between functions, and even between data structures, since the compiler can guarantee that the data won't be modified. Functional languages tend to encourage the use of data structures that can be used efficiently as immutable structures (for instance, trees instead of hash tables). If you add laziness into the mix, like many functional languages do, that adds new ways to save memory (it also adds new ways of wasting memory, but I'm not going to go into that).</p>


问:
Installer or Portable
I feared programs that require installation a lot. They leave traces behind the registry even after un-installation, plus, some uninstallers are poorly-programmed (that means, some programs cannot be uninstalled).
That applies to Windows.

The good side of installers, they create shortcuts and file associations. However, the Komodo on Linux uses a shell script to setup and can be safely uninstalled by deleting the folder.

Do you think installers should be all abolished? Do you think the effect of installations should be replaced by shell scripts?
Do you think all computer games should be portable?

Should the "scan the /Applications/${AppName}/Information folder and list app icons" design should be used for future desktop environments?

答:
It depends on your target audience.

As a programmer or a power user, I like my software to be inside a compressed file for portability and to be able to just delete the software without having to worry about it leaving any traces in the registry.

As a regular person (mostly applies to regular Windows users), however, I just want to click setup.exe and have it install itself for me. I don't want to have to bother looking at a README file or following some other form of instruction just to install the software that I want. Don't make me click any more than I could handle.

You should consider who you're making the software for first before deciding whether to make an installer or not.

Title: Installer or Portable


答:
In functional programming since almost all data structure are immutable, when the state has to change a new structure is created. Does this mean a lot more memory usage?

That depends on the data structure, the exact changes you performed and, in some cases, the optimizer. As one example let's consider prepending to a list:

```<code>list2 = prepend(42, list1) // list2 is now a list that contains 42 followed
                           // by the elements of list1. list1 is unchanged
</code>```

Here the additional memory requirement is constant - so is the runtime cost of calling prepend. Why? Because prepend simply creates a new cell which has 42 as its head and list1 as its tail. It does not have to copy or otherwise iterate over list2 to achieve this. That is, except for the memory required to store 42, list2 reuses the same memory that is used by list1. Since both lists are immutable, this sharing is perfectly safe.

Similarly, when working with balanced tree structures, most operations require only a logarithmic amount of additional space because everything, but one path of the tree may be shared.

For arrays the situation is a bit different. That's why, in many FP languages, arrays are not that commonly used. However, if you do something like arr2 = map(f, arr1) and arr1 is never used again after this line, a smart optimizer can actually create code that mutates arr1 instead of creating a new array (without affecting the behavior of the program). In that case the performance will be as in an imperative language of course.

Title: In functional programming, does having most of the data structures immutable require more memory usage?

Body: In functional programming since almost all data structure are immutable, when the state has to change a new structure is created. Does this mean a lot more memory usage? I know the object oriented programming paradigm well, now I'm trying to learn about the functional programming paradigm. The concept of everything being immutable confuses me. It would seem like the a program using immutable structures would require much more memory than a program with mutable structures. Am I even looking at this in the right way?</p>

Body:
In functional programming since almost all data structure are immutable, when the state has to change a new structure is created. Does this mean a lot more memory usage?

That depends on the data structure, the exact changes you performed and, in some cases, the optimizer. As one example let's consider prepending to a list:

list2 = prepend(42, list1) // list2 is now a list that contains 42 followed
                           // by the elements of list1. list1 is unchanged

Here the additional memory requirement is constant - so is the runtime cost of calling prepend. Why? Because prepend simply creates a new cell which has 42 as its head and list1 as its tail. It does not have to copy or otherwise iterate over list2 to achieve this. That is, except for the memory required to store 42, list2 reuses the same memory that is used by list1. Since both lists are immutable, this sharing is perfectly safe.

Similarly, when working with balanced tree structures, most operations require only a logarithmic amount of additional space because everything, but one path of the tree may be shared.

For arrays the situation is a bit different. That's why, in many FP languages, arrays are not that commonly used. However, if you do something like arr2 = map(f, arr1) and arr1 is never used again after this line, a smart optimizer can actually create code that mutates arr1 instead of creating a new array (without affecting the behavior of the program). In that case the performance will be as in an imperative language of course.


答:
The original algorithm is basically:

```<code>for each position:
    calculate best range ending at this position
print best over all possible ending positions
</code>```

The best possible range ending at a position is the maximum of:

0 (starting from scratch here)

the best possible range of the previous position + new mark

Now, we need to calculate K endings, for different amount of dropped tests

```<code>for each position:
    for k = 0 to K:
        calculate best possible range ending at this position and dropping at most k tests
print best of all calculated ranges
</code>```

The best possible range ending is the maximum of:

0 (starting a new range at this position)

the best possible range of the previous position + new mark

the best possible range of the previous position and one less dropped test

Title: Training Camp Algorithm

Body:
Problem Statement -

The task is to find the most profitable contiguous segment of tests, given a sequence of test scores, with being allowed to drop any k tests from a chosen range.

The problem appears to be a DP problem at the outset, but complexity arises when the test drop condition comes into the picture.

What modifications can be made to the classic DP approach for this problem? Or is there a completely different approach to it?

Test Range - N <= 104

Source - INOI 2011 Q Paper

Body:
The original algorithm is basically:

for each position:
    calculate best range ending at this position
print best over all possible ending positions

The best possible range ending at a position is the maximum of:

0 (starting from scratch here)

the best possible range of the previous position + new mark

Now, we need to calculate K endings, for different amount of dropped tests

for each position:
    for k = 0 to K:
        calculate best possible range ending at this position and dropping at most k tests
print best of all calculated ranges

The best possible range ending is the maximum of:

0 (starting a new range at this position)

the best possible range of the previous position + new mark

the best possible range of the previous position and one less dropped test


问:
algorithm to extract "possibilities" from a tree
From a given tree, subsequent trees have to be generated. Nodes can be marked as "variant" in the given tree (the example uses an asterisk to mark the node). All possible combinations between the variants form the resulting trees.

From the following tree:

```<code>- Product
    - Packaging *
        - Small box
        - Heavy box *
            - Eco
            - Non-eco
    - Delivery *
        - Standard
        - Express
</code>```

The following 6 trees should be generated:

```<code>- Product
    - Packaging
        - Small box
    - Delivery
        - Standard

- Product
    - Packaging
        - Small box
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Express
</code>```

Is there an elegant algorithm for this (recursive solution)?

答:
I'd be tempted to think there are at least a couple of ways you could describe the solution here:

Sets of leaf nodes - As all the parents will be included in each result, it may be simpler to picture a list of lists where you are merely selecting each possible configuration of values.  Looking at the example of ((Small box, heavy box),(Standard, Express)) would generate the possibilities which could be done with brute force if nothing else: ((Small box, Standard), (Small box, Express), (Heavy box, Standard), (Heavy box, Express))

Looking ahead - If there are multiple layers to go, then all the nodes will be added but if there is only one more layer to go, then each possibility is to be added.  The idea here is to consider how Packaging and Delivery are in each tree yet the leaf nodes are rather uniquely chosen.  This could be done recursively looking further down the tree as there are a few special cases to handle like an empty tree and a single node to give a couple of examples.  If there are a couple of levels or more then the look ahead idea can be used.


问:
Why don't modern libraries use OOP
I'm a beginner-level C++ programmer, but I understand the concepts of the language fairly well. When I began to learn external C++ libraries, like SDL, OpenGL (maybe something else too), to my great surprise I found out that they don't use C++ concepts at all.

For example, neither SDL, nor OpenGL use classes or exceptions, preferring functions and error codes. In OpenGL I've seen functions like glVertex2f, which takes 2 float variables as an input and probably would be better as a template. Moreover, these libraries sometimes use marcos, while it seems to be a common agreement that using macroses is bad.

All in all, they seem to be written more in C style, than in C++ style. But they are completely different incompaitable languages, aren't they?

The question is: why modern libraries do not use the advantages of the language they are written in?

答:
Both OpenGL and SDL are C libraries and expose a C interface to the rest of the world (as pretty much every language out there can interface with C but not necessarily with C++). Thus, they're restricted to the procedural interface that C gives you and the C way of declaring and using data structures.

Over and above the "interfacing with other languages" aspect that a C interface offers you, C in general tends to be a bit more portable than C++, which in turn makes it easier to get the non-platform dependent part of the code of libraries like these working on another OS or hardware architecture. Pretty much every platform out there has a decent C compiler, but there are still some that have restricted C++ compilers or ones that are just not very good.

While C and C++ are very different languages, they are not "incompatible", in fact, to a large extent C++ is a superset of C. There are some incompatibilities but not many, so using a C interface from C++ is a very easy thing to do.

Title: Why don't modern libraries use OOP


答: Both OpenGL and SDL are C libraries, not C++ libraries. You can use them from C++, but they're written in C and have a C API (which is also accessible from other languages; C++ is a pain to access via a FFI). Have a look at Boost for a large array of general-purpose (and some specialized) C++ libraries and SFML for a C++ multimedia library.</p>

Title: Why don't modern libraries use OOP

Body:
I'm a beginner-level C++ programmer, but I understand the concepts of the language fairly well. When I began to learn external C++ libraries, like SDL, OpenGL (maybe something else too), to my great surprise I found out that they don't use C++ concepts at all.

For example, neither SDL, nor OpenGL use classes or exceptions, preferring functions and error codes. In OpenGL I've seen functions like glVertex2f, which takes 2 float variables as an input and probably would be better as a template. Moreover, these libraries sometimes use marcos, while it seems to be a common agreement that using macroses is bad.

All in all, they seem to be written more in C style, than in C++ style. But they are completely different incompaitable languages, aren't they?

The question is: why modern libraries do not use the advantages of the language they are written in?


答:
Speaking to OpenGL specifically, OpenGL was originally part of a stack of APIs -- OpenGL provided a low-level, performance-oriented API, accessible from C (or even Fortran), while OpenInventor provides a high-level object-oriented API, designed to be used from C++, and providing both a high-level scene-graph API, and abstractions for saving/reading scenes to/from files, and GUI integration. </p>

<p>OpenGL ended up going much farther than OpenInventor (it filled a more pressing need, giving video hardware makers something to optimize for, and providing a common low-level API people could target instead of dealing with 3D acceleration hardware directly).  But OpenInventor is still out there, and there's a good open source implementation -- Coin3D -- with support for Unix/X11, Windows, and MacOS X/Cocoa. </p>

Title: Why don't modern libraries use OOP

Body:
Speaking to OpenGL specifically, OpenGL was originally part of a stack of APIs -- OpenGL provided a low-level, performance-oriented API, accessible from C (or even Fortran), while OpenInventor provides a high-level object-oriented API, designed to be used from C++, and providing both a high-level scene-graph API, and abstractions for saving/reading scenes to/from files, and GUI integration.

OpenGL ended up going much farther than OpenInventor (it filled a more pressing need, giving video hardware makers something to optimize for, and providing a common low-level API people could target instead of dealing with 3D acceleration hardware directly).  But OpenInventor is still out there, and there's a good open source implementation -- Coin3D -- with support for Unix/X11, Windows, and MacOS X/Cocoa.


答:
I think you are confusing "writing a library" vs. "exposing API to outside".  I don't know much specifically about the libraries you've mentioned (they might be internally written in C), but I know many others, myself included, have written C++ libraries/frameworks which fully utilized all kinds of fancy OOP practices/patterns, but still exposed C-style API to the outside world.

C and C++ are not entirely different systems.  C++ was built on top of C and a) can easily consume C code and b) is fully capable of providing C-style apis.

Advantage of C interface is that it is very easily consumable by the rest of the world. There are interop layers that allow C API to be consumed from just about any language (python, java, c#, php...), where as C++ interface is consumable from..... well, maybe C++ and still not always (different compilers, different versions of the same compiler will cause issues)

In the past, as an experiment in one of the projects at work, i decided to expose "OO" interface from a C++ DLL. In order to hide internal details and avoid a bunch of other things, I almost ended up reinventing Windows COM (component object model). After that project, I realized COM is not as bad as people make it out to be because a) it exposes OOP interfaces, b) takes care of all the issues I ran into and c) is standard enough to be consumable from a number of other languages.

But COM is still not without its baggage. In many cases, regular, plan C-style API is still a much better alternative.

Title: Why don't modern libraries use OOP


答:
In addition to what has been said in other answers, I would like to mention the Clean programming language, which supports so-called unique types. I do not know this language but I suppose that unique types support some kind of "destructive update".

In other words, while the semantics of updating a state is that you create a new value from an old one by applying a function, the uniqueness constraint can allow the compiler to reuse data objects internally because it knows that the old value will not be referenced any more in the program after the new value has been produced.

For more details, see e.g. the Clean homepage and this wikipedia article


答:
Naive implementations would indeed expose this problem - when you create a new data structure instead of updating an existing one in-place, you have to have some overhead.

Different languages have different ways of dealing with this, and there are a few tricks most of them use.

One strategy is garbage collection. The moment the new structure has been created, or shortly after, references to the old structure go out of scope, and the garbage collector will pick it up instantly or soon enough, depending on the GC algorithm. This means that while there is still an overhead, it is only temporary, and won't grow linearly with the amount of data.

Another one is picking different kinds of data structures. Where arrays are the go-to list data structure in imperative languages (usually wrapped in some sort of dynamic-reallocation container such as std::vector in C++), functional languages often prefer linked lists. With a linked list, a prepend operation ('cons') can reuse the existing list as the new list's tail, so all that really gets allocated is the new list head. Similar strategies exist for other types of data structures - sets, trees, you name it.

And then there's lazy evaluation, à la Haskell. The idea is that data structures you create aren't fully created immediately; instead, they are stored as "thunks" (you can think of these as recipes for constructing the value when it's needed). Only when the value is needed does the thunk get expanded into an actual value. This means that memory allocation can be deferred until evaluation is necessary, and at that point, several thunks can be combined in one memory allocation.


答:
Represent your problem as a grammar:

```<code>product: packaging delivery
packaging: heavy-box | small-box
delivery: standard | express
</code>```

This is easy to extend to a third level:

```<code>product: packaging delivery
packaging: heavy-box | small-box
delivery: standard | express
heavy-box: small | large
</code>```

With your problem in BNF, all you need is a program that can generate all possible strings accepted by this grammar.

Title: algorithm to extract "possibilities" from a tree

Body:
From a given tree, subsequent trees have to be generated. Nodes can be marked as "variant" in the given tree (the example uses an asterisk to mark the node). All possible combinations between the variants form the resulting trees.

From the following tree:

```<code>- Product
    - Packaging *
        - Small box
        - Heavy box *
            - Eco
            - Non-eco
    - Delivery *
        - Standard
        - Express
</code>```

The following 6 trees should be generated:

```<code>- Product
    - Packaging
        - Small box
    - Delivery
        - Standard

- Product
    - Packaging
        - Small box
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Express
</code>```

Is there an elegant algorithm for this (recursive solution)?

Body:
Represent your problem as a grammar:

product: packaging delivery
packaging: heavy-box | small-box
delivery: standard | express

This is easy to extend to a third level:

product: packaging delivery
packaging: heavy-box | small-box
delivery: standard | express
heavy-box: small | large

With your problem in BNF, all you need is a program that can generate all possible strings accepted by this grammar.


答:
I prefer applications that have both. I think at their best, a software installer is basically a slightly glorified self extracting zip, but that can do stuff like add start menu items and whatnot.

When I have admin access, I much prefer to mindlessly double click the installer and let it do the grunt work for me, unzipping it, making a program files folder, etc.

But, sometimes I don't have admin access or I want to run something from a remote machine because again I am too lazy to cop it to myself, then having it self contained saves me that labor.

Distributing both the installer and a zip file of the files I think is the way to go.

Title: Installer or Portable

Body:
I feared programs that require installation a lot. They leave traces behind the registry even after un-installation, plus, some uninstallers are poorly-programmed (that means, some programs cannot be uninstalled).
That applies to Windows.

The good side of installers, they create shortcuts and file associations. However, the Komodo on Linux uses a shell script to setup and can be safely uninstalled by deleting the folder.

Do you think installers should be all abolished? Do you think the effect of installations should be replaced by shell scripts?
Do you think all computer games should be portable?

Should the "scan the /Applications/${AppName}/Information folder and list app icons" design should be used for future desktop environments?


问:
What is a closure and how is it implemented in Ruby?
In the context of the Ruby programming language, what is a closure and when do you use one?  What are the uses for it in Rails?</p>

答:
Try this link: Understanding Ruby Closures. Another one: Understanding Ruby Blocks, Procs, and Lambdas. In a nutshell, a closure is a function plus a context in which the function is called. The context contains state information that the function can access, but which isn't part of the function itself. Ruby has several different kinds of closures: blocks, procs, and lambdas.

Also (from Michael):
http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/


问:
How to translate Lisp to Javascript
I have some legacy code, which uses Lisp as it's scripting language. To broaden, ease and accelerate scripting I'd like to replace Lisp by Javascript.
In order to be able to built on all present scripting files, I first need to translate all lsp to js.

Now I found parenscript but am not yet sure what it is good for (seems to modify Javascript to be able to run lisp, which is not what I want).
Also there are some converters on the web, which seem to work quite well.
Has anyone already done this and can share some experiences, best pracises and tools?

答:
Common Lisp is huge, and writing a compatible compiler / runtime is out of question for a novice. Parenscript is probably your best bet for direct running of your Lisp code on a JS target.

For simpler versions, like Scheme, there's a ready-made interpreter.

If you understand basic Lisp, take also at look a Clojure, a Lisp variant. Chances are you might port significant chunks of Lisp code to Clojure without a major rewrite. Then apply their JS compiler and see if it works for you.

JavaScript has quite Lispy internals (despite the bolted-on OOP features), so efficient translation of moderate amounts of simple Lisp code (e.g. without macros) to JS is not impossible to do by hand.

The bottom line is: there's no silver bullet. You'd better learn some Lisp to handle your task. (Try it; it's well worth it, and also forever changes the way you see programming.)

Title: How to translate Lisp to Javascript