答:
When issuing an identifier for an external system, you should only give URIs, or alternatively a key or a set of keys that have the same properties as a URI, rather than exposing the database primary key directly (from here onwards I'll refer to both URI or a key or a set of keys that have the same properties as URI as just URI, in other word a URI below doesn't necessarily mean RFC 3986 URI).

A URI may or may not contain the primary key of the object and it may or may not actually be composed of alternate keys. It doesn't really matter. What matters is that only the system that generates the URI is allowed to split or combine the URI to form an understanding of what the referred object is. External systems should always use the URI as an opaque identifier. It doesn't matter if a human user can identify that one part of the URI is actually a database surrogate key or that it consists of several business keys bunched up together, or that it's actually a base64 of those values. These are irrelevant. What matters is that the external system shouldn't need to be required to understand what the identifier means to use the identifier. External systems should never be required to parse the components within the identifier or combine an identifier with other identifiers to refer to something in your system.

Using GUID fulfills some of this criteria, however identifier like GUID can be difficult to dereference back into the object even within your system, so keys that are opaque to even your system like a GUID should only be employed if client parsing the URI/identifier actually poses a security risk.

Back to your VoIP example, say that a VoIP provider can be uniquely determined either by (VoIPProviderID) or by (Name, URL) or by (GUID). When an external system needs to update the VoIP provider, it can just pass a PUT /provider/by-id/1234 or PUT /provider/foo-voip/bar-domain.com or PUT /3F2504E0-4F89-41D3-9A0C-0305E82C3301 and your system would understand that the external system wants to update the VoIPProvider. These URIs are generated by your system and only your system need to understand that all they means the same thing. The external system should just treat whatever is in the URI as basically a PUT <whatever>.

Suppose that you have the data for different VoIP providers stored in different tables with different schemas (thus completely different set of keys identifies each VoIP provider based on which table they are stored in). When you have a URI, they can be accessed uniformly by the external system, without regards of how your system identify the particular VoIP provider. To the external system it's all just opaque pointer.

When your system uses a URI to refer to objects in such a way, you're not leaking anything regarding how you implement your system. You generate the URI and the client simply passes it back to you.


问:
Making internal search engine return results that adhere to local permissions on an internal web application
I have an ElasticSearch search engine and an internal web application.  Prior to applying the security model, search results were very fast.  The security model restricts some users from accessing certain pages.  We have 7 "types" of pages.

Our process is currently this:

Search engine queries all records

For each type of result, I get all recordIds of that type from the database that the user is allowed to access. This ensures I only call the database a max of 7 times (once per type)

I do an intersect between the records the user can access and the records search is returning

The above approach isn't fast enough. I have an autosuggest search and each query takes up to 2 seconds now.

What is a typical way to make a search engine return results that adhere to security?  Another developer has recommended I store the security permissions directly in ElasticSearch itself(essentially mirroring what our sql server has).

Edit: Each record has a page. We can assume 200-500 users and 25000+ records.

答:
If I understand correctly, previously the search results from the engine was fast. Now you do that, but additionally filter the results afterwards with up to 7 DB queries and intersection filters.

Obviously, the problem lies with the DB queries, or the intersection sorting and filtering!

The next question is - which is slow? Is the DB a slow box, are you performing the filtering once for each DB query? There are usually many ways of optimizing this kind of task, execution plans are your friend in this case.

If the problem is the DB, then caching might be an answer - if the security policies are relatively static, you can fetch the filter restrictions once and  save them per user when the user logs in. If the filtering is slow on the DB, then try applying the filter on the web server, a hashmap lookup as each page from the original results can be very fast indeed.

ContentLicense: CC BY-SA 3.0


问:
Entity Component System Coupling
Lately I've been working on a small personal project which is basically an Entity Component System framework with autoupdated Systems.

While I have a pretty good idea on the way the framework should work, because of lack of experience I am having trouble with actually keeping everything decoupled.

Some details on the framework:

Each entity is defined by it's components.

Systems are responsible for the actually modifying the entities by changing their components.

In order to improve locality of reference, instead of keeping each component in the appropriate entity,
all components are stored in homogenous vectors and each entity keeps a list of indices to each vector.

Since each System modifies specific components, it should keep a list only of the entities with the corresponding components.

How I dealt with all of this until now was to have a ComponentManager, an EntityManager and a SystemManager. These classes however have very tight coupling with each other. The EntitManager needs to have access to the ComponentManager in order to handle the size of the the index lists and the mapping of each component type to them. It also needs access to actually add the components in the appropriate vector.
Another coupling is between the EntityManager and the SystemManager. Whenever an entity is created, it needs to be added to the list of the appropriate Systems.

A general event bus would appear to help but I am not sure how to implement it without making it global.

How do I improve this design by removing coupling while still maintaining the system's functionality?

答:
How do I improve this design by removing coupling while still maintaining the system's functionality?

You don't go much into your functionality, so I'm going to make some guesses and go over the general approaches:

System -> Component - you say that the System only works with specific components (say, a physics system changing velocities), then why does the system care about entities at all? The system should be free to work with the components in relative isolation.

Entity -> Component - you mention that there's some manner of index lists between the entity and its component. This strikes me as odd. Entities should have references to their components (or vice versa) - even if that's as thin as a foreign key. By using indexes, you're exposing an implementation detail from the ComponentManager that is harming your coupling.

Entity -> System - again, if you have systems work with components, then there should be no tie here. An entity is created, which knows which components to make (or vice versa, the components are built and then aggregated/dependency resolved by the entity) - regardless of the system manipulating them.

Personally, the design I've seen work well is having the entity be a very, very thin layer that aggregates the components, acting as a context so that the components can play nice with one another. The outside world can then query and act on the components' public interface.

ContentLicense: CC BY-SA 4.0

Title: Entity Component System Coupling


问:
Is there any danger in writing raw bytes to a file?
I'm working through a problem in Programming Pearls -- specifically, the implementation of a program which sorts a file containing, at most, 10,000,000 integers (Column 1, Problem 3). Since the book doesn't specify how the data should be stored in the file, I'm considering storing the integers as raw bytes (there are some other constraints that make raw bytes a good option). I've never worked at this low of a level before, so I want to know if there's anything dangerous I should watch out for. Do I need to worry about accidentally using some sort of end-of-file sequence when I'm writing raw bytes to a file, for example?

Edit:

I realize now how broad my question was. I really meant problems of the more catastrophic kind, like accidentally overwriting other files on the disk. Sorry I wasn't clearer originally.

答:
The only danger you will run into is little vs. big endianess (whether the most or least significant byte is written first). However if you remain in the same environment there will be no issue. besides the general ensuring of writing/parsing roundtrip.

The file system is designed to handle any sequence of bytes.


答:
Different architectures have different representations for integers. The main risk here is saving the byte representation of an integer in machine A and then attempting to read that back and interpret the contents as integers in machine B. If machines A and B have different sizes for integers and/or different endianness, you'll most likely cause undefined behavior (e.g. in C) or an exception.

Since this is just a programming example and not a "real" program, it's not really an issue. If this were a real program, rolling your own application-specific binary format is usually not a good idea; there are better solutions, like SQLite or string-based serialization formats like JSON, YAML, XML, etc. For single values turning it into a string would suffice; for simple lists you could save one string per line and simply split the input on newlines when you read it back in.

Title: Is there any danger in writing raw bytes to a file?

Body:
I'm working through a problem in Programming Pearls -- specifically, the implementation of a program which sorts a file containing, at most, 10,000,000 integers (Column 1, Problem 3). Since the book doesn't specify how the data should be stored in the file, I'm considering storing the integers as raw bytes (there are some other constraints that make raw bytes a good option). I've never worked at this low of a level before, so I want to know if there's anything dangerous I should watch out for. Do I need to worry about accidentally using some sort of end-of-file sequence when I'm writing raw bytes to a file, for example?

Edit:

I realize now how broad my question was. I really meant problems of the more catastrophic kind, like accidentally overwriting other files on the disk. Sorry I wasn't clearer originally.


答:
No, in fact this is how many file formats work. Common examples of binary files like this include images and music/audio files.

To maintain the integrity of the file and the data read from it, be sure to follow these guidelines:

Always open the file (reading or writing) using the same mode: text or binary. The primary difference is text mode cares about newlines, and may "chomp" off the newlines characters when reading a file (depending on the specific library being used). Text mode may also perform Unicode translations that will likely choke on non-Unicode data.

When reading non-string data, be sure to read using the same data type as you write. For example, if the first four bytes of the file are a descriptive integer, be sure to read and write using a method that takes/provides an integer to ensure it is treated consistently. The same data type may have a different size on different machines, and mixing data types on the same machine can also change the meaning of the data (e.g. interpreting a bit in the middle of a longer integer as a sign bit).

Endianness: if the library you are using does not handle this consistently, you may need to handle it yourself. For example, Java always uses network byte order (big endian) for multi-byte types. C and C++ use whatever the library implementer decided, typically the same as the processor (little endian on Intel, big endian on most others). If this is a quick exercise on one system it is not as important, but it is still a good habit to pay attention to this and code around it if necessary.

The specific details will vary based on the framework, platform, and language, but this should cover the basic "gotchas" with file I/O.


问:
Is it a good practice to declare instance variables as None in a class in Python?
Consider the following class:

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

My coworkers tend to define it like this:

```<code>class Person:
    name = None
    age = None

    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

The main reason for this is that their IDE of choice shows the properties for autocompletion.

Personally, I dislike the latter one, because it makes no sense that a class has those properties set to None.

Which one would be better practice and for what reasons?

答:
I will go with "a bit like docstrings, then" and declare this harmless, as long as it is always None, or a narrow range of other values, all immutable.

It reeks of atavism, and excessive attachment to statically typed languages.  And it does no good as code.  But it has a minor purpose that remains, in documentation.

It documents what the expected names are, so if I combine code with someone and one of us has 'username' and the other user_name, there is a clue to the humans that we have parted ways and are not using the same variables.

Forcing full initialization as a policy achieves the same thing in a more Pythonic way, but if there is actual code in the __init__, this provides a clearer place to document the variables in use.

Obviously the BIG problem here is that it tempts folks to initialize with values other than None, which can be bad:

```<code>class X:
    v = {}
x = X()
x.v[1] = 2
</code>```

leaves a global trace and does not create an instance for x.

But that is more of a quirk in Python as a whole than in this practice, and we should already be paranoid about it.

Body:
I will go with "a bit like docstrings, then" and declare this harmless, as long as it is always None, or a narrow range of other values, all immutable.

It reeks of atavism, and excessive attachment to statically typed languages.  And it does no good as code.  But it has a minor purpose that remains, in documentation.

It documents what the expected names are, so if I combine code with someone and one of us has 'username' and the other user_name, there is a clue to the humans that we have parted ways and are not using the same variables.

Forcing full initialization as a policy achieves the same thing in a more Pythonic way, but if there is actual code in the __init__, this provides a clearer place to document the variables in use.

Obviously the BIG problem here is that it tempts folks to initialize with values other than None, which can be bad:

class X:
    v = {}
x = X()
x.v[1] = 2

leaves a global trace and does not create an instance for x.

But that is more of a quirk in Python as a whole than in this practice, and we should already be paranoid about it.


问:
Best solution for a large database transaction
I have a COBOL CICS process running on a mainframe legacy system. The process does over 2K DMLs in a highly concurrent DB environment. After each CRUD operation, the result is used to make further computations followed by CRUD operations again. This entire process runs under a transaction block such that any failure before its successful completion results in the entire set of DB changes to be rolled back, only on success of each and every step in the process till the end, there is a commit. The COBOL program is written in a manner that it doesn't consume more than 20 odd seconds for its completion or failure lest the other process starve for DB resource(locks, stalls etc.) due to the enormity of this transaction.

Now we are commissioned to expose this legacy application as a Java SOAP web service. The three approaches I have are:

The Service layer of my Java code sends a message to the queue with input parameters, the already existing COBOL program picks the message from the queue and does the transaction. Java layer pings the queue asynchronously and when it has got a result from the COBOL process, it sends it back to the Controller.

Write a Stored Procedure which mimics the job done by the COBOL process including the DB transaction and call that SP from Java Service layer.

Write the Business logic inside Java Service/DAO layer and the transactions inside a Spring transaction block.

Business doesn't want the #1 approach as it means dependency on the legacy COBOL program. I have two doubts here :

I have an understanding that SPs are better from performance point of view. But will the SP be able to handle 2K or more odd DMLs within a transaction block and do the job in time at least equivalent to the time which COBOL process takes ? If yes, then will it be efficient enough in locking-releasing DB resources as the DB is highly concurrent and I don't want other processes to starve due to it.

I have never done a DB transaction of this magnitude from the Java code and I doubt whether Spring transaction block can hold 2K DMLs in a single block effectively. Even if it does I'm sure that it wouldn't match the speed of COBOL or SPs, hence it may acquire locks on records etc. and starve other processes which needs to access the same for long time.

The transactions are not on a particular DB table, it is distributed over 20 odd different tables containing critical financial data. I was thinking of breaking the large number of CRUD operations in chunks of Spring transaction blocks, but then it would have been a humongous task to code the entire roll back logic in Java, but it's alright, my main concern is locking other processes from DB access in the meanwhile.

I am a Java developer with meager knowledge of RDBMS and practically no knowledge of COBOL. I would be grateful if someone can help me point to the right direction so that I can come out with a solution myself.

答:
One of the promises of SOA is leveraging legacy systems through an abstraction layer, and a service bus.

You first say business is asking you to expose the legacy application as a web server, but then you say business doesn't want option #1 because it's dependant on the legacy COBOL program. So what they are really asking you then is to re-write it.

In that case the best approach is #2, rewrite the thing in stored procedures.

That has the following advantages over the Java/DAO approach:

Store-procedure-oriented languages like PL/SQL, PL/PgSQL or Transact SQL ( you don't tell which RDBMS you are using ), being purpose-specific (as opossed to general purpose) are more COBOL-like than Java. They have a smaller set of instructions, a simpler grammar and, in general, it would be easier to write a line-by-line translation of a COBOL program in PL/SQL than, say, in Java.

Stored procedures run in the database server, thus running faster than a client code in Java in an application server or client.

You will also do better whithout the overhead of DAO/JDBC, since speed is so critical.

What better to optimally handle blocks and transactions that the very language specifically built into the RDBMS for that very purpose.

I believe the first one of those four advantages is the one that is most important. And you will have an aditional advantage in that a non-programming, business expert will most probably understand the code and could help you validate formulas and business rules.

I've done a fair ammount of Oracle's PL/SQL programming myself for critical applications and I can tell you it's capable of handling very well huge transactions. I think, yes, SP are a tool fit for that purpose.


答:
I'd say 99 times out of 100 the answer is to grit your teeth and re-use the existing COBOL code.  It sounds like it might have some fairly complex logic behind the scenes; unless you actually have an up-to-date and accurate spec you might have trouble re-producing the logic in all its nuances.  This is bad mojo on a financial application as the bean counters will want bug-for-bug compatibility with the legacy code.

So, as a first stop, I would suggest that you seriously investigate what is needed to wrap your legacy process or integrate it with the front-end.  You might take a look at the COBOL-Java integration options available from Micro Focus.

If you really can't re-cycle the existing code then you have a significant problem.  While a sproc might well do what you want, you have the problem of making something mimic the exact behaviour of an apparently complex and probably poorly documented COBOL application.

Unless your replacement process is radically slower, wrapping 2000 DMLs in a transaction isn't going to be a major issue.  It's possible to wrap entire ETL processes in a transaction and have them roll back on a failure.  I have seen an application where it was necessary to do this, although it is unusual.  Splitting a financial transaction is a no-no, especially on a double entry system.  In almost all cases it should commit or roll back atomically.  Stick with the single transaction.

The fact that the COBOL application does computations one DML at a time and uses the results in the next step of the computation does not bode well for conversion to set operations.  Be prepared to have to do this row-by-row and find a way to make it run fast.  A stored procedure may well be the way to do this.  You don't say what DBMS you're using (DB/2 for Z/OS?).

Also, you might have to drop down to XA transactions (java.transactions API) and JDBC, especially if you need to work in the client layer.  If you want good performance on 2000 row based operations you might have to go below the framework.

Title: Best solution for a large database transaction

Body:
I have a COBOL CICS process running on a mainframe legacy system. The process does over 2K DMLs in a highly concurrent DB environment. After each CRUD operation, the result is used to make further computations followed by CRUD operations again. This entire process runs under a transaction block such that any failure before its successful completion results in the entire set of DB changes to be rolled back, only on success of each and every step in the process till the end, there is a commit. The COBOL program is written in a manner that it doesn't consume more than 20 odd seconds for its completion or failure lest the other process starve for DB resource(locks, stalls etc.) due to the enormity of this transaction.

Now we are commissioned to expose this legacy application as a Java SOAP web service. The three approaches I have are:

The Service layer of my Java code sends a message to the queue with input parameters, the already existing COBOL program picks the message from the queue and does the transaction. Java layer pings the queue asynchronously and when it has got a result from the COBOL process, it sends it back to the Controller.

Write a Stored Procedure which mimics the job done by the COBOL process including the DB transaction and call that SP from Java Service layer.

Write the Business logic inside Java Service/DAO layer and the transactions inside a Spring transaction block.

Business doesn't want the #1 approach as it means dependency on the legacy COBOL program. I have two doubts here :

I have an understanding that SPs are better from performance point of view. But will the SP be able to handle 2K or more odd DMLs within a transaction block and do the job in time at least equivalent to the time which COBOL process takes ? If yes, then will it be efficient enough in locking-releasing DB resources as the DB is highly concurrent and I don't want other processes to starve due to it.

I have never done a DB transaction of this magnitude from the Java code and I doubt whether Spring transaction block can hold 2K DMLs in a single block effectively. Even if it does I'm sure that it wouldn't match the speed of COBOL or SPs, hence it may acquire locks on records etc. and starve other processes which needs to access the same for long time.

The transactions are not on a particular DB table, it is distributed over 20 odd different tables containing critical financial data. I was thinking of breaking the large number of CRUD operations in chunks of Spring transaction blocks, but then it would have been a humongous task to code the entire roll back logic in Java, but it's alright, my main concern is locking other processes from DB access in the meanwhile.

I am a Java developer with meager knowledge of RDBMS and practically no knowledge of COBOL. I would be grateful if someone can help me point to the right direction so that I can come out with a solution myself.


问:
Java: how can I make the return type, of an inherited method in a subclass, the same as the subclass?
I am rather inexperience in Java, and I'm having a problem in forming a subclass of a class I have created. The class I have made, called Vector2D, contains methods, such as add(Vector2D addend), that takes a Vector2D object as an argument, and returns a Vector2D object. This method in particular is designed to add two vectors, and return the sum.

Then, I started coding a subclass, called Position2D, which I intend to have all of the functionality of the Vector2D class, except have additional functions, and have any usage of Vector2D inside the preexisting classes, be it as an argument, return type, etc., replaced with Position2D, so that the add(Position2D addend) function adds two Position2D vectors together, and returns the sum as a Position2D.

The issue arises that, when Position2D inherits from Vector2D, such functions continue to work in terms of Vector2D objects, spitting out an error as soon as a Position2D object is passed through it.

The relevant code for the Vector2D class is as follows:

```<code>public class Vector2D{

    //Field Variables
    private double x; //The vector's x-coordinate
    private double y; //The vector's y-coordinate

    //Constructors
    public Vector2D(){
        //Constructs empty vector.
        setX(0);
        setY(0);
    }

    //Methods
    public void setX(double newX){
        //This method is not problematic when inherited for the subclass.
        x = newX;
    }

    public void setY(double newY){
        //This method is not problematic too.
        y = newY;
    }

    public Vector2D add(Vector2D addend){
        //Adds two vectors and returns the sum.
        //This method, however, does pose a problem.
        Vector2D sum = new Vector2D();
        sum.x = x + addend.x;
        sum.y = y + addend.y;
        return sum;
    }

}
</code>```

The only work-around I can currently think of as to what the code in add(Position2D addend) in Position2D could be is:

```<code>public Position2D add(Position2D addend){
    //Adds two position vectors and returns the sum.
    Position2D sum = new Position2D();
    sum.x = x + addend.x;
    sum.y = y + addend.y;
    return sum;
}
</code>```

i.e., repeat the method from Vector2D, and manually modify it. This, of course, is not efficient and wastes time, especially so whenever the same has to be done for similar methods, and more so whenever I intend to make more subclass, e.g. Velocity2D. Therefore, I am looking for a much cleaner and efficient means of doing this.

答:
Remember inheritance defines a "is a" kind of relationship. The code

class Position2D extends Vector2D

tells the compiler that every Position2D is a Vector2D, but not vice versa.

Check out the following examples assuming that you already made the above declaration:

```<code>// obviously okay, type of instance matches reference type
Vector2D vecVecRef = new Vector2D();
Position2D posPosRef = new Position2D();
// this is okay because a Position2D is a Vector2D
Vector2D posVecRef = new Position2D();
// The compiler will not automatically convert a Vector2D to a Position2D
Position2D vecPosRef = new Vector2D(); //Compiler error!
</code>```

A Position2D variable can never refer to a Vector2D object. If you try typecasting it, the compiler will say "fine...I trust you" but then the JVM will get angry when it actually finds out that you are trying to assign a Vector2D to a Position2D. It will raise a ClassCastException at runtime.

```<code>// compiles fine but raises ClassCastException in runtime
Position2D vecPosRef = (Position2D) new Vector2D();
</code>```

This is because you can only Class cast a subclass into a superclass and not vice versa. So basically, you cannot cast Vector2D to Position2D and you cannot assign it without casting either.

The simplest solution to this problem is to have a constructor defined in your subclass that makes a Position2D object out of a given Vector2D object.

```<code>class Position2D extends Vector2D {
    Position2D() {
        // default stuff
    }

    Position2D(Vector2D v) {
        // you currently don't have the getX and getY methods
        // so define them in your superclass
        setX(v.getX());
        setY(v.getY());
    }
}
</code>```

With that one simple and convenient constructor, you can use code like this:

```<code>public class Inheritance {
    public static void main(String[] args) {
        Position2D pos1 = new Position2D();
        Position2D pos2 = new Position2D();
        pos1.setX(3);
        pos1.setY(4);
        pos2.setX(5);
        pos2.setY(6);
        Position2D pos3 = new Position2D(pos1.add(pos2)); // using constructor
        System.out.println(pos3.getX()); // this prints 8.0
    }
}
</code>```

As you can see, this way is much more extensible than rewriting all of the subclass methods.

Body:
Remember inheritance defines a "is a" kind of relationship. The code

class Position2D extends Vector2D

tells the compiler that every Position2D is a Vector2D, but not vice versa.

Check out the following examples assuming that you already made the above declaration:

// obviously okay, type of instance matches reference type
Vector2D vecVecRef = new Vector2D();
Position2D posPosRef = new Position2D();
// this is okay because a Position2D is a Vector2D
Vector2D posVecRef = new Position2D();
// The compiler will not automatically convert a Vector2D to a Position2D
Position2D vecPosRef = new Vector2D(); //Compiler error!

A Position2D variable can never refer to a Vector2D object. If you try typecasting it, the compiler will say "fine...I trust you" but then the JVM will get angry when it actually finds out that you are trying to assign a Vector2D to a Position2D. It will raise a ClassCastException at runtime.

// compiles fine but raises ClassCastException in runtime
Position2D vecPosRef = (Position2D) new Vector2D();

This is because you can only Class cast a subclass into a superclass and not vice versa. So basically, you cannot cast Vector2D to Position2D and you cannot assign it without casting either.

The simplest solution to this problem is to have a constructor defined in your subclass that makes a Position2D object out of a given Vector2D object.

class Position2D extends Vector2D {
    Position2D() {
        // default stuff
    }

    Position2D(Vector2D v) {
        // you currently don't have the getX and getY methods
        // so define them in your superclass
        setX(v.getX());
        setY(v.getY());
    }
}

With that one simple and convenient constructor, you can use code like this:

public class Inheritance {
    public static void main(String[] args) {
        Position2D pos1 = new Position2D();
        Position2D pos2 = new Position2D();
        pos1.setX(3);
        pos1.setY(4);
        pos2.setX(5);
        pos2.setY(6);
        Position2D pos3 = new Position2D(pos1.add(pos2)); // using constructor
        System.out.println(pos3.getX()); // this prints 8.0
    }
}

As you can see, this way is much more extensible than rewriting all of the subclass methods.


问:
What's the best way to create a static utility class in python? Is using metaclasses code smell?
Ok so I need to create a bunch of utility classes in python. Normally I would just use a simple module for this but I need to be able to inherit in order to share common code between them. The common code needs to reference the state of the module using it so simple imports wouldn't work well. I don't like singletons, and classes that use the classmethod decorator do not have proper support for python properties.

One pattern I see used a lot is creating an internal python class prefixed with an underscore and creating a single instance which is then explicitly imported or set as the  module itself. This is also used by fabric to create a common environment object (fabric.api.env).

I've realized another way to accomplish this would be with metaclasses. For example:

```<code>#util.py
class MetaFooBase(type):
    @property
    def file_path(cls):
        raise NotImplementedError

    def inherited_method(cls):
        print cls.file_path

#foo.py
from util import *
import env

class MetaFoo(MetaFooBase):
    @property
    def file_path(cls):
        return env.base_path + "relative/path"

    def another_class_method(cls):
        pass

class Foo(object): __metaclass__ = MetaFoo

#client.py
from foo import Foo

file_path = Foo.file_path
</code>```

I like this approach better than the first pattern for a few reasons:

First, instantiating Foo would be meaningless as it has no attributes or methods, which insures this class acts like a true single interface utility, unlike the first pattern which relies on the underscore convention to dissuade client code from creating more instances of the internal class.

Second, sub-classing MetaFoo in a different module wouldn't be as awkward because I wouldn't be importing a class with an underscore which is inherently going against its private naming convention.

Third, this seems to be the closest approximation to a static class that exists in python, as all the meta code applies only to the class and not to its instances. This is shown by the common convention of using cls instead of self in the class methods. As well, the base class inherits from type instead of object which would prevent users from trying to use it as a base for other non-static classes. It's implementation as a static class is also apparent when using it by the naming convention Foo, as opposed to foo, which denotes a static class method is being used.

As much as I think this is a good fit, I feel that others might feel its not pythonic because its not a sanctioned use for metaclasses which should be avoided 99% of the time. I also find most python devs tend to shy away from metaclasses which might affect code reuse/maintainability. Is this code considered code smell in the python community? I ask because I'm creating a pypi package, and would like to do everything I can to increase adoption.

答:
If I really needed this level of configurability, I would build factory classes that paste the utility classes together and return them as objects.

The mechanism you first mention is quite good, apart from the assigning up to the module.  You can just return them and store them in a normal namespace like a normal human.  No need to bypass logical boundaries and make everyone search everywhere for your code.

So you can make code that looks like stereotypes of different aspects of your classes, and rely upon straightforward mix-in inheritance to compose your factory classes.  This is more straightforward than metaclassing, which involves editing dictionaries of methods, etc, in ways that do not look like what they are -- code writing code inheriting from other code.

Metaclasses also get out of hand fast, in my experience.

And only one mechanism really gets to use them at a time in a whole code-base, unless everyone using them has been amazingly punctilious.  So by using them here, you may be foreclosing a better, future use for them.


问:
What is the best way to INSERT a large dataset into a MySQL database (or any database in general)
As part of a PHP project, I have to insert a row into a MySQL database. I'm obviously used to doing this, but this required inserting into 90 columns in one query. The resulting query looks horrible and monolithic (especially inserting my PHP variables as the values):

```<code>INSERT INTO mytable (column1, colum2, ..., column90)
VALUES
('value1', 'value2', ..., 'value90')
</code>```

and I'm concerned that I'm not going about this in the right way. It also took me a long (boring) time just to type everything in and testing writing the test code will be equally tedious I fear.

How do professionals go about quickly writing and testing these queries? Is there a way I can speed up the process?

答:
Try the following. Worked for me.

Form names must equal to database column names

Get the values as below:

```<code>foreach ($_GET as $formName => $value) {
    $sql = mysql_query("UPDATE table_name SET $formName = '$value' WHERE ID= $id");
}
</code>```

You will first need to insert an ID before the foreach loop.
you can get next id by doing:

```<code>SELECT MAX(id) FROM .....
</code>```

add 1 to id and insert it.

Body:
Try the following. Worked for me.

Form names must equal to database column names

Get the values as below:

foreach ($_GET as $formName => $value) {
    $sql = mysql_query("UPDATE table_name SET $formName = '$value' WHERE ID= $id");
}

You will first need to insert an ID before the foreach loop.
you can get next id by doing:

SELECT MAX(id) FROM .....

add 1 to id and insert it.


答:
You can by using the dependency inversion principle and the factory method pattern.

The return type should be a supertype of both Vector2D and Position2D.

Let's call that IVector2D ( an interface ).

The solution would be:

```<code>public interface IVector2D {

    public void setX(double newX);
    public void setY(double newY);
    public double getX();
    public double getY();
    public IVector2D add(IVector2D addend);
    public IVector2D getInstance(); // this helps decouple the instantiation

}
</code>```

An then

```<code>public class Vector2D implements IVector2D {

    private double x; //The vector's x-coordinate
    private double y; //The vector's y-coordinate

    public Vector2D(){ setX(0); setY(0); }

    public IVector2D getInstance(){ return new Vector2D(); }

    @Override
    public void setX(double newX) { x = newX; }

    @Override
    public void setY(double newY) { y = newY; }

    @Override
    public double getX() { return this.x; }

    @Override
    public double getY() { return this.y; }

    @Override
    public IVector2D add(IVector2D addend) {
        IVector2D sum = getInstance();
        sum.setX(this.getX()+addend.getX());
        sum.setY(this.getX()+addend.getY());
        return sum;
    }
}
</code>```

When extending, override getInstance() and implement a constructor:

```<code>public class Position2D extends Vector2D {
    public Position2D(){ super(); }
    @Override
    public IVector2D getInstance(){ return new Position2D(); }
}
</code>```

Note that you are actually returning an object of type Position2D, as you wanted, inside a reference of type Ivector2D, because you are overriding getInstance() and add() will call the getInstance() of Position2D. That abstraction allowed for the add() method to work seamlessly.

The test program would be:

```<code>public static void main(String[] args) {
    IVector2D a = new Position2D();
    IVector2D b = new Position2D();
    a.setX(1.2d);
    a.setY(2.3d);
    b.setX(0.33d);
    b.setY(9.0d);
    IVector2D c = a.add(b);
    System.out.println(c.getX());
}
</code>```

Ouput:

```<code>1.53
</code>```

Title: Java: how can I make the return type, of an inherited method in a subclass, the same as the subclass?

Body:
I am rather inexperience in Java, and I'm having a problem in forming a subclass of a class I have created. The class I have made, called Vector2D, contains methods, such as add(Vector2D addend), that takes a Vector2D object as an argument, and returns a Vector2D object. This method in particular is designed to add two vectors, and return the sum.

Then, I started coding a subclass, called Position2D, which I intend to have all of the functionality of the Vector2D class, except have additional functions, and have any usage of Vector2D inside the preexisting classes, be it as an argument, return type, etc., replaced with Position2D, so that the add(Position2D addend) function adds two Position2D vectors together, and returns the sum as a Position2D.

The issue arises that, when Position2D inherits from Vector2D, such functions continue to work in terms of Vector2D objects, spitting out an error as soon as a Position2D object is passed through it.

The relevant code for the Vector2D class is as follows:

```<code>public class Vector2D{

    //Field Variables
    private double x; //The vector's x-coordinate
    private double y; //The vector's y-coordinate

    //Constructors
    public Vector2D(){
        //Constructs empty vector.
        setX(0);
        setY(0);
    }

    //Methods
    public void setX(double newX){
        //This method is not problematic when inherited for the subclass.
        x = newX;
    }

    public void setY(double newY){
        //This method is not problematic too.
        y = newY;
    }

    public Vector2D add(Vector2D addend){
        //Adds two vectors and returns the sum.
        //This method, however, does pose a problem.
        Vector2D sum = new Vector2D();
        sum.x = x + addend.x;
        sum.y = y + addend.y;
        return sum;
    }

}
</code>```

The only work-around I can currently think of as to what the code in add(Position2D addend) in Position2D could be is:

```<code>public Position2D add(Position2D addend){
    //Adds two position vectors and returns the sum.
    Position2D sum = new Position2D();
    sum.x = x + addend.x;
    sum.y = y + addend.y;
    return sum;
}
</code>```

i.e., repeat the method from Vector2D, and manually modify it. This, of course, is not efficient and wastes time, especially so whenever the same has to be done for similar methods, and more so whenever I intend to make more subclass, e.g. Velocity2D. Therefore, I am looking for a much cleaner and efficient means of doing this.

Body:
You can by using the dependency inversion principle and the factory method pattern.

The return type should be a supertype of both Vector2D and Position2D.

Let's call that IVector2D ( an interface ).

The solution would be:

public interface IVector2D {

    public void setX(double newX);
    public void setY(double newY);
    public double getX();
    public double getY();
    public IVector2D add(IVector2D addend);
    public IVector2D getInstance(); // this helps decouple the instantiation

}

An then

public class Vector2D implements IVector2D {

    private double x; //The vector's x-coordinate
    private double y; //The vector's y-coordinate

    public Vector2D(){ setX(0); setY(0); }

    public IVector2D getInstance(){ return new Vector2D(); }

    @Override
    public void setX(double newX) { x = newX; }

    @Override
    public void setY(double newY) { y = newY; }

    @Override
    public double getX() { return this.x; }

    @Override
    public double getY() { return this.y; }

    @Override
    public IVector2D add(IVector2D addend) {
        IVector2D sum = getInstance();
        sum.setX(this.getX()+addend.getX());
        sum.setY(this.getX()+addend.getY());
        return sum;
    }
}

When extending, override getInstance() and implement a constructor:

public class Position2D extends Vector2D {
    public Position2D(){ super(); }
    @Override
    public IVector2D getInstance(){ return new Position2D(); }
}

Note that you are actually returning an object of type Position2D, as you wanted, inside a reference of type Ivector2D, because you are overriding getInstance() and add() will call the getInstance() of Position2D. That abstraction allowed for the add() method to work seamlessly.

The test program would be:

public static void main(String[] args) {
    IVector2D a = new Position2D();
    IVector2D b = new Position2D();
    a.setX(1.2d);
    a.setY(2.3d);
    b.setX(0.33d);
    b.setY(9.0d);
    IVector2D c = a.add(b);
    System.out.println(c.getX());
}

Ouput:

1.53


答:
I'm not entirely sure I've understood correctly, but I think you can reduce your 7 database accesses to 1.

Encode each security level as a bit in an integer. Store the security level with each record.

Establish which security levels a user is allowed to see - encode this as a similar integer.

When searching for records, include a requirement that the bitwise AND of these two values is non-zero.

If the security levels are strictly hierarchical, (e.g. TOP SECRET, SECRET, CONFIDENTIAL, RESTRICTED, UNCLASSIFIED) then this can be simplified further by assigning TOP SECRET = 4, SECRET = 3, CONFIDENTIAL = 2, RESTRICTED = 1, UNCLASSIFIED = 0. Store this with the record as a fieldsecurity_level

Then a user with CONFIDENTIAL clearance can request results with security_level <= 2, etc.

Title: Making internal search engine return results that adhere to local permissions on an internal web application

Body:
I have an ElasticSearch search engine and an internal web application.  Prior to applying the security model, search results were very fast.  The security model restricts some users from accessing certain pages.  We have 7 "types" of pages.

Our process is currently this:

Search engine queries all records

For each type of result, I get all recordIds of that type from the database that the user is allowed to access. This ensures I only call the database a max of 7 times (once per type)

I do an intersect between the records the user can access and the records search is returning

The above approach isn't fast enough. I have an autosuggest search and each query takes up to 2 seconds now.

What is a typical way to make a search engine return results that adhere to security?  Another developer has recommended I store the security permissions directly in ElasticSearch itself(essentially mirroring what our sql server has).

Edit: Each record has a page. We can assume 200-500 users and 25000+ records.


问:
What to learn to become freelancer?
I have around 8 years experience in software development. I have worked on application development all these years using C++ /win32.

I few years from now I want to become a freelancer . I tried to look into some freelance sites and I am not able to find any projects on C++/win32. I feel C++/Win32 wont help me much and I need to learn new skills . But my job require me to still work on C++ , so I cann't learn any new skills. I can still learn some new skills but without good project , it won't make any sense.

I have shortlisted few skills

php

jquery

perl

python

android

I am still confused which one to start and how to get expertise in them.Any suggestions?

答:
Yes!

PHP - Yes, learning this language will make you suitable for a large number of freelance projects. May niche (and higher paying) services like WordPress customization, Drupal customization, Joomla customization will all become a possibility to you if you know PHP.

Python - This is yet another language that is popular and has a LOT of freelance jobs. It is also fun to work with. I have not taken projects that require python but I have seen many jobs on job boards, odesk.com, guru.com that require you to know python. These projects always involve developing web applications with Python using the Django web application framework.

Android - It is the hottest mobile development framework available today. I would tread with caution if I were you in relying solely on this for a steady source of income . A few years ago  Symbian was the hottest mobile phone OS to program for. Now you can find not a handful of companies that use the Symbian OS. Nokia ( who owns symbian now ) has moved on to the MeeGo OS.

On to how to get expertise on these: There are dozens of books published on these topics by Packt, Apress, Wiley, O'Reilly. Investing in these books will save you much time.

Nope, Not really

perl - Not a lot of websites today use perl. You will cannot find many projects that require you to work on perl.

jQuery - This is just a javascript library. Knowing how to use this by itself will not help you go full-time (assuming of course you plan on going full time). What is more important is that you know how to work with Javascript and the document object model.

My suggestion for you is to focus on web development. Learn PHP, HTML, CSS and Javascript. Learn to use jQuery.

Also Consider..

Ruby On Rails - Ruby is a programming language and Rails is a web application framework written in ruby. You will find many jobs on this as well as full time positions on the same.

Most Importantly

It is important that you NOT base your opinion solely on what answers you will get here. Go to many job boards. Here is a directory of the job boards:

http://freelanceswitch.com/resources-directory/freelance-jobs/job-boards/

Get an idea of what are the niche skills that are in demand today. You need not necessarily prepare to provide the skills that is most in demand. Determine what you can realistically do well and acquire that skill.

Title: What to learn to become freelancer?

ContentLicense: CC BY-SA 2.5


问:
Binary Tree/Knowledge Base design C++
Currently I have a binary tree template setup where my main is using it with strings to make a question/answer game. I'm using a knowledge base that works as an interface to the binary tree that main uses (main has no access to node or binary tree classes). My code seems to work fine inserting/rearranging nodes as necessary but I think my design is pretty bad.

Is it usually best to just put the Node and BinaryTree classes in the same file since neither is independently useful? Or is it even standard when using binary trees to just make node a nested class inside the tree class?

Not sure how to not use class friending (assuming this is bad design) unless I just do away with the knowledge base. Without knowledge base being able to see private node members it wouldn't be able to move it's "current" node pointer around the tree through questions/guesses unless it passed its current pointer by reference to a binary tree function that moved it each time.

Also with this setup binary tree doesn't really do anything except provide a root node as k base is handling the inserting/rearranging/differentiating between questions and guesses, so I'm not sure how to move some traversal, etc. functionality from kbase to btree without just making a bunch of kbase functions that call their btree counterparts.

Is there a way to use std::swap in each file (node/tree/base) also without polluting with the utility header? This design looks to be bad OO-wise, any help is appreciated.

答:
Questions:

Is it usually best to just put the Node and BinaryTree classes in the same file since neither is independently useful? Or is it even standard when using binary trees to just make node a nested class inside the tree class?

Answer:

I think of Node as an implementation detail of BinaryTree. I would recommend making Node a nested class of BinaryTre. If it is possible for BinraryTree to be a regular class and not a class template, I would recommend using the pimpl idiom for Node. After all, it is an implementation detail of BinaryTree.

You said:

Not sure how to not use class friending (assuming this is bad design) unless I just do away with the knowledge base. Without knowledge base being able to see private node members it wouldn't be able to move it's "current" node pointer around the tree through questions/guesses unless it passed its current pointer by reference to a binary tree function that moved it each time.

My response:

It appears as though you are not providing an adequate public interface to BinaryTree. The knowledge base should be able to pass all its queries to BinaryTree through the public interface.

You said:

Also with this setup binary tree doesn't really do anything except provide a root node as k base is handling the inserting/rearranging/differentiating between questions and guesses, so I'm not sure how to move some traversal, etc. functionality from kbase to btree without just making a bunch of kbase functions that call their btree counterparts.

My response:

That reinforces my thinking that you are not providing an adequate public interface to BinaryTree. I would work on enhancing the public interface of BinaryTree instead making the knowledge base implement functionality that belongs in BinaryTree.

Title: Binary Tree/Knowledge Base design C++


问:
Python mutable default argument: Why?
I know that default arguments are created at the function initialisation time and not every time the function is called.  See the following code:

```<code>def ook (item, lst=[]):
    lst.append(item)
    print 'ook', lst

def eek (item, lst=None):
    if lst is None: lst = []
    lst.append(item)
    print 'eek', lst

max = 3
for x in xrange(max):
    ook(x)

for x in xrange(max):
    eek(x)
</code>```

What I do not get is why this was implemented this way.  What benefits does this behaviour offers over an initialisation at each call time?

答:
It happens because compilation in Python is performed by executing the descriptive code.

If one said

```<code>def f(x = {}):
    ....
</code>```

it would be pretty clear that you wanted a new array each time.

But what if I say:

```<code>list_of_all = {}
def create(stuff, x = list_of_all):
    ...
</code>```

Here I would guess I want to create stuff into various lists, and have a single global catch-all when I do not specify a list.

But how would the compiler guess this?  So why try?  We could rely on whether this was named or not, and it might help sometimes, but really it would just be guessing.  At the same time, there is a good reason not to try -- consistency.

As it is, Python just executes the code.  The variable list_of_all is assigned an object already, so that object is passed by reference into the code that defaults x in the same way that a call to any function would get a reference to a local object named here.

If we wanted to distinguish the unnamed from the named case, that would involve the code at compilation executing assignment in a significantly different way than it is executed at run-time.  So we do not make the special case.

Title: Python mutable default argument: Why?

Body:
It happens because compilation in Python is performed by executing the descriptive code.

If one said

def f(x = {}):
    ....

it would be pretty clear that you wanted a new array each time.

But what if I say:

list_of_all = {}
def create(stuff, x = list_of_all):
    ...

Here I would guess I want to create stuff into various lists, and have a single global catch-all when I do not specify a list.

But how would the compiler guess this?  So why try?  We could rely on whether this was named or not, and it might help sometimes, but really it would just be guessing.  At the same time, there is a good reason not to try -- consistency.

As it is, Python just executes the code.  The variable list_of_all is assigned an object already, so that object is passed by reference into the code that defaults x in the same way that a call to any function would get a reference to a local object named here.

If we wanted to distinguish the unnamed from the named case, that would involve the code at compilation executing assignment in a significantly different way than it is executed at run-time.  So we do not make the special case.


问:
Applying the principles of Clean Code to functional languages
I'm currently reading Robert Martin's Clean Code. I think it's great, and when writing OO code I'm taking his lessons to heart. In particular, I think his advice to use small functions with meaningful names makes my code flow much more smoothly. It's best summed up by this quote:

[W]e want to be able to read the program as though it were a set
  of TO paragraphs, each of which is describing the current level of abstraction and referencing subsequent TO paragraphs at the next level down.

(Clean Code, page 37: a "TO paragraph" is a paragraph that begins with a sentence voiced in the infinitive. "To do X, we perform steps Y and Z." "To do Y, we..." etc.) For example:

TO RenderPageWithSetupsAndTeardowns, we check to see whether the page is a test page and if so, we include the setups and teardowns. In either case we render the page in HTML

I also write functional code for my job. Martin's examples in the book definitely do read as if they were a set of paragraphs, and they're very clear -- but I'm not so sure that "reads like a set of paragraphs" is a desirable quality for functional code to have.

Taking an example out of the Haskell standard library:

```<code>maximumBy               :: (a -> a -> Ordering) -> [a] -> a
maximumBy _ []          =  error "List.maximumBy: empty list"
maximumBy cmp xs        =  foldl1 maxBy xs
                        where
                           maxBy x y = case cmp x y of
                                       GT -> x
                                       _  -> y
</code>```

That is about as far away as you can possibly get from Martin's advice, but that's concise, idiomatic Haskell. Unlike the Java examples in his book, I can't imagine any way to refactor that in to something that has the sort of cadence he asks for. I suspect that Haskell written to the standard of Clean Code would come off as long-winded and unnatural.

Am I wrong to consider (at least some of) Clean Code at odds with functional programming best practices? Is there a sensible way to reinterpret what he says in a different paradigm?

答:
Clean Code is first and foremost a style manual. Strunk and White does not apply when you are writing in Klingon. The idea is that you want to be clear to the programmers that will likely read your code. You want to have code that is modularized and easy to restructure. There are ways to do this in Haskell just as there are ways to do this in any other language but the precise particulars will vary.

That being said, there are a number of style guidelines out there for Haskell. Stack Overflow has a fairly comprehensive guide as well. Keeping coding logic straightforward and brief seem to be fairly constant. Generalization of functions is also stressed as it leads to modularity. DRY code is also stressed, same as with Clean Code.

In the end, Clean Code and Haskell's coding guidelines strive for the same thing but wind up taking their own paths to get there.


问:
Does FFMpeg support gpu acceleration of media encoding/decoding?
I was wondering if ffmpeg supported gpu acceleration. I was reading on their websites and came across contradicting information.

http://www.ffmpeg.org/general.html#Video-Codecs
-H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)

http://ffmpeg.org/trac/ffmpeg/wiki/x264EncodingGuide
-Will a graphics card make x264 encode faster?
No. libx264 doesn't use them (at least not yet). There are some proprietary encoders that utilize the GPU, but that does not mean they are well optimized, though encoding time may be faster; and they might be  worse than x264 anyway, and possibly slower. Regardless, FFmpeg today doesn't support any means of gpu encoding, outside of libx264.

If not, is there any way to add gpu acceleration to h.264 encoding/decoding?

答: You could try this: https://developer.nvidia.com/nvidia-video-codec-sdk for encoding the h264 streams then mux them with ffmpeg.</p>


答:
In addition to all of the gotchas already mentioned, if you are making up a new binary file format rather than reading and writing data in an existing format, it is absolutely vital that you include a file header: a block of data at the very beginning of the file that unambiguously identifies the file format and records any metadata that may be required.

Good file headers include at least three things:

A "magic number", of at least four bytes.  The magic number MUSTrfc2119 be the very first N bytes in the file, MUST never have been used for any other file format you can dig up, and MUST contain at least one byte that is not a printable ASCII character.  See the PNG specification for how to design a really thorough magic number.  See the source code of the file(1) command for a database of existing magic numbers that's as comprehensive as you're likely to find.

The point of a magic number is to unambiguously label the file, in-band, with its format.  If you don't include a magic number, or it's not the very first thing in the file, you run the risk of programs misidentifying your file as some other type of file, which leads to data loss, viruses escaping detection, and other such catastrophes.

An indication of the version of the file format.  Even if you think you're never going to have to revise your file format drastically, make the next two bytes after the magic number be 00 00 and document that this is a 16-bit version number in some definite endianness (whichever you like, but pick one and stick to it throughout the file) and will be incremented if the meaning of subsequent data changes radically.  Your future self will thank you.

(The PNG specification takes a different route here, specifying that chunk formats are frozen, and that all future changes to the format will take the form of new chunk types.  That's also valid, but I recommend the simple magic number+version number approach for beginners to binary data processing.  The people who designed PNG were drawing on collective decades of experience with image formats.)

Some kind of mechanism for embedding arbitrary metadata in the file.  This can be as simple as having the next two bytes be a 16-bit offset from the end of the header to the beginning of the actual data, with everything in between to be interpreted as UTF-8 key-value pairs a la RFC 822 (that is, "Tag: value\n" — if you go this route I recommend not allowing folding of long lines).  Again, PNG is considerably cleverer.


答:
I'm not sure I follow what you mean by your example.  Paragraphs, as he describes them, do not require long-windedness.  He doesn't mean the code should read like English.  The important part is the grouping of functionality at the same level of abstraction, in a logical progression.  That's a theoretical structural concept that transcends programming paradigms.

Expressed in Bob Martin's "TO paragraph" format, I read your example as:

To compute the maximumBy, you need an ordering function and a list, and the result is an element of that list.

To compute the maximumBy of an empty list and any ordering function is an error.

To compute the maximumBy of a list xs, you fold over that list using the maxBy function.

To compute the maxBy of two list elements, you compare them using the given ordering function.  If the first element is greater, choose it.  Otherwise choose the second.

You're starting with the most general concepts and progressing to more detail, just as in the imperative examples.  The idea of the "TO paragraphs" is that you can stop reading at a certain point when you've gotten enough detail, without having to jump up and down the page.  That's certainly the case here.

A couple of the names could perhaps be better, but they are common conventions of the language, especially when writing generic higher-order functions.  Higher-order function names also don't translate well into imperative verb phrases like the examples in the book, because they more describe relationships between verbs.

There are ways to implement this that don't follow the "TO paragraph" guidelines.  Leaving off the explicit type signature would omit the higher-level "overview" sentence.  You could use an if expression for the error handling instead of pattern matching, which would muddle that inappropriately with another abstraction level.  You could inline maxBy as an anonymous function instead of giving it a name that can be described later in more detail.

In fact, I think constructs like where actually are a better fit for the paragraph format, because you can use them to give a name to a deeper detail in a way that's close to how we express it in English, and similarly limit its scope in a clear way to the context of the "paragraph."

Title: Applying the principles of Clean Code to functional languages

Body:
I'm currently reading Robert Martin's Clean Code. I think it's great, and when writing OO code I'm taking his lessons to heart. In particular, I think his advice to use small functions with meaningful names makes my code flow much more smoothly. It's best summed up by this quote:

[W]e want to be able to read the program as though it were a set
  of TO paragraphs, each of which is describing the current level of abstraction and referencing subsequent TO paragraphs at the next level down.

(Clean Code, page 37: a "TO paragraph" is a paragraph that begins with a sentence voiced in the infinitive. "To do X, we perform steps Y and Z." "To do Y, we..." etc.) For example:

TO RenderPageWithSetupsAndTeardowns, we check to see whether the page is a test page and if so, we include the setups and teardowns. In either case we render the page in HTML

I also write functional code for my job. Martin's examples in the book definitely do read as if they were a set of paragraphs, and they're very clear -- but I'm not so sure that "reads like a set of paragraphs" is a desirable quality for functional code to have.

Taking an example out of the Haskell standard library:

```<code>maximumBy               :: (a -> a -> Ordering) -> [a] -> a
maximumBy _ []          =  error "List.maximumBy: empty list"
maximumBy cmp xs        =  foldl1 maxBy xs
                        where
                           maxBy x y = case cmp x y of
                                       GT -> x
                                       _  -> y
</code>```

That is about as far away as you can possibly get from Martin's advice, but that's concise, idiomatic Haskell. Unlike the Java examples in his book, I can't imagine any way to refactor that in to something that has the sort of cadence he asks for. I suspect that Haskell written to the standard of Clean Code would come off as long-winded and unnatural.

Am I wrong to consider (at least some of) Clean Code at odds with functional programming best practices? Is there a sensible way to reinterpret what he says in a different paradigm?


问:
Addressing the fact that primary keys are not part of your business domain
In almost all circumstances, primary keys are not a part of your business domain. Sure, you may have some important user-facing objects with unique indices (UserName for users or OrderNumber for orders) but in most cases, there is no business need to overtly identify domain objects by a single value or set of values, to anyone  but perhaps an administrative user. Even in those exceptional cases, especially if you are using global unique identifiers (GUID), you will like or want to employ an alternate key rather than expose the primary key itself.

So, if my understanding of domain-driven design is accurate, primary keys need not and thus should not be exposed, and good riddance. They're ugly and cramp my style. But if we choose not to include primary keys in the domain model, there are consequences:

Naively, data transfer objects (DTO) that derive exclusively from combinations of domain models will not have primary keys

Incoming DTO's will not have a primary key

So, is it safe to say that if you are really going to stay pure and eliminate primary keys in your domain model, you should be prepared to be able to handle every request in terms of unique indices on that primary key?

Put in another way, which of the following solutions is the correct approach to dealing with identifying particular objects after removing PK in domain models?

Being able to identify the objects you need to deal with by other attributes

Getting the primary key back in the DTO; ie, eliminating the PK when mapping from persistence to domain, then recombining the PK when mapping from domain to DTO?

EDIT: Let's make this concrete.

Say my domain model is VoIPProvider which includes fields like Name, Description, URL, as well as references like ProviderType, PhysicalAddress, and Transactions.

Now let's say I want to build a web service that will allow privileged users to manage VoIPProviders.

Perhaps a user-friendly ID is useless in this case; after all, VoIP providers are companies whose names tend to be distinct in the computer sense and even distinct enough in the human sense for business reasons. So it may be enough to say that a unique VoIPProvider is completely determined by (Name, URL). So now let's say I need a method PUT api/providers/voip so that privileged users can update VoIP providers. They send up a VoIPProviderDTO, which includes many but not all of the fields from the VoIPProvider, including some flattening potentially. However, I can't read their minds, and they still need to tell me which provider we are talking about.

It seems I have 2 (maybe 3) options:

Include a primary key or alternate key in my domain model and send it to the DTO, and vice versa

Identify the provider we care about via the unique index, like (Name, Url)

Introduce some sort of intermediate object that can always map between persistence layer, domain, and DTO in a way that does not expose implementation details about the persistence layer - say by introducing an in-memory temporary identifier when going from domain to DTO and back,

答:
I am going to have to target this wildly inaccurate and naive statement:

Perhaps a user-friendly ID is useless in this case; after all, VoIP providers are companies whose names tend to be distinct in the computer sense and even distinct enough in the human sense for business reasons.

Names are terrible as keys, as they are frequently changing. A company may have many names during its lifetime, the company may merge, split, merge again, create a distinct subsidiary for specific tax purposes that has 0 employees but all customers which then hires employees from a completely different subsidiary.

Then we get into the fact that company names are not even remotely unique, as shown by the landmark Apple vs. Apple.

A good object relational mapper or framework should abstract the primary keys away and make these invisible, but they are there, and they will usually be the only way to uniquely identify an object in your database.

For reference, I prefer how django handles this:

```<code>class VoipProvider(models.Model):
    name=fields.TextField()
    address=fields.TextField()

class Customer(models.Model):
    name=fields.TextField()
    address=fields.TextField()
    voipProvider=fields.ForeignKeyField(VoipProvider)
</code>```

In this way, the details of a provider of a customer can be access in code by using:

```<code>myCustomer.voipProvider.name #returns the name of the customers VOIP Provider.
</code>```

While the Primary/Foreign keys aren't visible, they are there, and can be used to access items, but are abstracted away.

Body:
I am going to have to target this wildly inaccurate and naive statement:

Perhaps a user-friendly ID is useless in this case; after all, VoIP providers are companies whose names tend to be distinct in the computer sense and even distinct enough in the human sense for business reasons.

Names are terrible as keys, as they are frequently changing. A company may have many names during its lifetime, the company may merge, split, merge again, create a distinct subsidiary for specific tax purposes that has 0 employees but all customers which then hires employees from a completely different subsidiary.

Then we get into the fact that company names are not even remotely unique, as shown by the landmark Apple vs. Apple.

A good object relational mapper or framework should abstract the primary keys away and make these invisible, but they are there, and they will usually be the only way to uniquely identify an object in your database.

For reference, I prefer how django handles this:

class VoipProvider(models.Model):
    name=fields.TextField()
    address=fields.TextField()

class Customer(models.Model):
    name=fields.TextField()
    address=fields.TextField()
    voipProvider=fields.ForeignKeyField(VoipProvider)

In this way, the details of a provider of a customer can be access in code by using:

myCustomer.voipProvider.name #returns the name of the customers VOIP Provider.

While the Primary/Foreign keys aren't visible, they are there, and can be used to access items, but are abstracted away.


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答:
Absolutely not.  It's not my responsibility to manage the relationship between my co-workers and management.  What goes on between them, is between them.  What I happen to know, or not know, as a result of happenstance, is my business.

And it's rare - if ever - that anything good comes from getting yourself involved in other people's business.  Even the person you think you're "helping" will probably think less of you for it, since you paint yourself as non-trustworthy and a meddling busy-body.

In short, just don't do it.


问:
Error Handling Strategies in Multithreaded Environments
TL;DR What error generating and handling strategies do you use in Multithreaded code intended for use by others and why do you use them? If applicable, state what programming paradigm it's useful for. I'm more interested in imperative, concurrent environments but any in general will be useful.

I'm writing a little concurrency library that's currently a pet/C++11 learning project but may be used internally by my work later. In terms of the domain it's more in the realm of DSP and media streaming but since this will be used in a game engine I need fairly strong error handling.

My big block at the moment is not getting my head around the parallel code and data structures but how to do error handling and reporting. My main experience in large systems is games but I'm usually using libraries, not designing them. I'm just looking for different strategies and how they might be used in different situations as this is a rather big gap in my knowledge.

My biggest area of concern is employing a strategy so that if the program can recover, it should. If it does recover, there should be a way to notify a user as to what's happened through some kind of mechanism. Already I have some some data structures that although they can recover, memory may be leaked if a destructor fails for example.

Some Approaches:

Handle exceptions for which you can safely recover from inside the library, but let fatal exceptions propagate to users of the library to indicate that object is now in an undefined state. It's my preferred approach in single threaded environments but this approach won't communicate bad state to other threads.

When an exception occurs that would put a data structure in an unrecoverable state, tear down the data structure and set a flag to block any more operations over that data structure then raise a general exception to the end user. This is hard for lock-free algorithms.

Forward an error state through parallel computations. Works well for Kahn process networks and other high level concurrency models. No so helpful if a primitive supporting the high level model has failed.

Terminate the thread/task that caused the exception. Works well for thread local data/computation but not much of a solution for shared data.

Just as a note, I know that a good library will probably use a mix of more than just what's listed above. I just don't have the experience to know what strategy is good where for any sufficiently large system.

答:
My two cents.

First, most async models I've seen in libraries tend to make me frustrated. Everybody seems to have their own slightly different brand of async, and many of those interfaces are not good. As such, I tend to like libraries that keep everything synchronous. Note that callbacks can still be good. But keep all the logic on one thread; the application programmer often wants to think about threading apart from the task the library is trying to perform.

Second, a small library devoted to asynchronous code can be a very good thing - as long as that is its sole focus. A pattern that I've seen and liked in C# is to chain together actions on different threads, but write it in almost a single threaded manner with a fluent interface. (The new keyword await is somewhat along the same lines.) One common place where this comes up is in dispatches onto the UI thread. Then provide a way to handle exceptions at the end, almost like a catch block. So for example maybe something like this:

```<code>...
int expensiveResult=-1;
YourThreadLibrary
  .Background(()=>expensiveResult=DoLongRunningTaskToCreate())
  .UI(()=>UpdateUI(expensiveResult))
  .Exception(ex=>LogIt(ex));
</code>```

Exceptions are the way to go in C# and you have GC, so your situation may be different. But the pattern may still make some sense.

I know this might seem too simplistic but these are the tools that I've seen be general enough to work across many problems. The nice thing is that a fluent interface like this is definitely open to extension if written properly so you can add your .ParallelFailOnAny(params Action[]) etc.

Body:
My two cents.

First, most async models I've seen in libraries tend to make me frustrated. Everybody seems to have their own slightly different brand of async, and many of those interfaces are not good. As such, I tend to like libraries that keep everything synchronous. Note that callbacks can still be good. But keep all the logic on one thread; the application programmer often wants to think about threading apart from the task the library is trying to perform.

Second, a small library devoted to asynchronous code can be a very good thing - as long as that is its sole focus. A pattern that I've seen and liked in C# is to chain together actions on different threads, but write it in almost a single threaded manner with a fluent interface. (The new keyword await is somewhat along the same lines.) One common place where this comes up is in dispatches onto the UI thread. Then provide a way to handle exceptions at the end, almost like a catch block. So for example maybe something like this:

...
int expensiveResult=-1;
YourThreadLibrary
  .Background(()=>expensiveResult=DoLongRunningTaskToCreate())
  .UI(()=>UpdateUI(expensiveResult))
  .Exception(ex=>LogIt(ex));

Exceptions are the way to go in C# and you have GC, so your situation may be different. But the pattern may still make some sense.

I know this might seem too simplistic but these are the tools that I've seen be general enough to work across many problems. The nice thing is that a fluent interface like this is definitely open to extension if written properly so you can add your .ParallelFailOnAny(params Action[]) etc.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
To my notion, the biggest asset a green programmer can bring to the table, beyond his existing technical skills, is initiative and passion.  If you show your boss that you are aggressive about learning new things, aggressive about learning your way around the company, the code-base, the tools, and your co-workers, and you show that you have a passion for what you are doing, that will impress.  Unless you're working for a horrible manager, in which case you want out anyway.

I would also suggest putting some focus on "soft skills" stuff.  Demonstrate that you aren't just a geek who is useless in any sort of inter-personal interaction.  Make friends with the people in sales, marketing, support, business development, project management, etc.  Show that you are a good communicator and somebody who can work with people to get things done.


问:
Drawing a custom rendered control in Windows - resizing
Some background: in order to learn GUI programming and drawing in Windows I'm starting to create my own GUI toolkit in Windows (so this is a didactic exercise, please don't suggest "use Qt" or "use MFC").

I would like to draw the entire window area from memory DCs in double buffering (thus also handling mouse and keyboard events myself) but I'm now wondering how should I handle resize events from the window: suppose I have a text control and a sidebar and my window gets a resize command

the sidebar should grow larger and the text control should show more text (it is also larger).

The first thing that comes to my mind is to redraw all the widgets on the memory DC and then BitBlt it to the screen. Anyway some widgets might not have changed at all or might be changed just a bit (the portion "Text here, text here, te" hasn't changed at all during the resize).

What can be done to exploit this fact and avoid redrawing (even in memory DC, not device DC) the parts which haven't changed?

答: You'll want to redraw the whole thing. Keeping track of which parts are still the same as the unsized image is going to be computationally more difficult as simply redrawing the whole lot, especially considering that in general usage you're going to have a dialog full of controls, not full of whitespace. Even in the case of text, the text displayed will be wrapped at different points, and thus require redrawing.</p>


问:
Calculate which quantity packages to use based on quantity of bookings
In my app, many appointments can be booked for activities.  Each activity has many price packages with a price and a quantity.

On showing the cart, I need to work out what combination of packages to use to get the user the best prices and allow all the appointments to be accounted for.

There is not always a quantity 1 package.

Is there a common pattern to apply to this?

Here is where I got to before I realised how hard this was going to be:

```<code>cost = 0
i = appointments.count
activity.packages.order(:quantity => :asc).each do |package|
   if i >= package.quantity &&  i.modulo(package.quantity) == 0
     cost = cost + (package.price * i/package.quantity )
     i = i - i/package.quantity
   end
end
if i > 0
  raise "error: packages do not cover number of children."
end
</code>```

That's in ruby(rails).

So the problem I didn't see until I wrote the above is, what if there are 8 appointments, and packages for 4 & 5  - it will use the 5 package, then the last 3 won't fit in a 4 package and it will fail.

EDIT: More detail

So the structure is

```<code>activities has_many packages
packages:
 quantity: integer
 price: float
</code>```

So a package defines a price for a bundle of appointments for an activity.

So for example, sailing lessons are $500 for 5 or $430 for 4.

If the user orders 8 sailing lessons, the app needs to work out that it should use two of the quantity 4 packages = $860

If the user order 9 sailing lessons, the app should work out they need 1 Quantity 5 package, and one quantity 4 package.  etc

答:
This is not solvable if the required number of appointments cannot be written as a sum of the available Package.Quantity numbers.

But maybe that requirement is too strict. Why not say that you want to offer the client the cheapest available sum of packages? E.g. if he wants 8 appointments but you can't match 8, you give him e.g. 5+4 packages.

Let your package definitions follow these rules:

if Quantity for Package1 is larger than Quantity for Package2, then

1) The price for Package1 is higher than the price for Package2, and

2) The average Price/Quantity for Package1 is <= Price/Quantity for Package2
3) You always have a Package with quantity 1

Then you can do the following (best illustrated with a numeric example):

Assume you have these packages:

```<code>12 for 600 = avg 50
10 for 550 = avg 55
5 for 500 = avg 100
4 for 400 = avg 100
3 for 360 = avg 120
2 for 260 = avg 130
</code>```

The client wants 8 appointments

Alternatives that match exactly are e.g.

5+3 = price 860 avg 108

4+4 = price 800 avg 100

But '10 for 550' would be the best solution if you want to minimize the price: 550

So assuming the conditions earlier:

1) If exact quantity match -> take that (you don't want to go 'higher' because that reduces your sales unnecessarily)

2) If not, take package with quantity 'next up' (the 10)

3) If that does not exist, you have to 'walk down'

3a) Try to find an exact sum from the highest quantities possible,

i.e. the lowest number of packages combined

That is because you know that these have the lowest average costs

All possible combinations are:

```<code>5+3       860   avg 108
4+4       800   avg 100
4+2+2     920   avg 115
3+3+2     980   avg 123
2+2+2+2   1040  avg 130
</code>```

So you have 2 candidates with only two packages.

Take the one with the lowest price (4+4).

If you do not have a package with quantity 1 you need a step 3b (but then I cannot get my head around the algorithm), OR you can also predefine the packages so that all combinations can be made - with the sample quantities I gave (2,3,4,5,10,12) you can fulfill any number with this algorithm.

Body:
This is not solvable if the required number of appointments cannot be written as a sum of the available Package.Quantity numbers.

But maybe that requirement is too strict. Why not say that you want to offer the client the cheapest available sum of packages? E.g. if he wants 8 appointments but you can't match 8, you give him e.g. 5+4 packages.

Let your package definitions follow these rules:

if Quantity for Package1 is larger than Quantity for Package2, then

1) The price for Package1 is higher than the price for Package2, and

2) The average Price/Quantity for Package1 is <= Price/Quantity for Package2
3) You always have a Package with quantity 1

Then you can do the following (best illustrated with a numeric example):

Assume you have these packages:

12 for 600 = avg 50
10 for 550 = avg 55
5 for 500 = avg 100
4 for 400 = avg 100
3 for 360 = avg 120
2 for 260 = avg 130

The client wants 8 appointments

Alternatives that match exactly are e.g.

5+3 = price 860 avg 108

4+4 = price 800 avg 100

But '10 for 550' would be the best solution if you want to minimize the price: 550

So assuming the conditions earlier:

1) If exact quantity match -> take that (you don't want to go 'higher' because that reduces your sales unnecessarily)

2) If not, take package with quantity 'next up' (the 10)

3) If that does not exist, you have to 'walk down'

3a) Try to find an exact sum from the highest quantities possible,

i.e. the lowest number of packages combined

That is because you know that these have the lowest average costs

All possible combinations are:

5+3       860   avg 108
4+4       800   avg 100
4+2+2     920   avg 115
3+3+2     980   avg 123
2+2+2+2   1040  avg 130

So you have 2 candidates with only two packages.

Take the one with the lowest price (4+4).

If you do not have a package with quantity 1 you need a step 3b (but then I cannot get my head around the algorithm), OR you can also predefine the packages so that all combinations can be made - with the sample quantities I gave (2,3,4,5,10,12) you can fulfill any number with this algorithm.


问:
Would you still use Java in your next project, despite the whole mess in JCP
It seems that there is a whole mess around current JCP.

Quite of number of highly respected guys like Doug Lea, Tim Peierls had quit JCP.

Reference :

Is JCP dead? and Final results of the JSR Review Ballot for JSR #336

This put Java in an unfavorable future. As a Java developer, will you still consider using Java in your next project?

答:
I've been moving slowly away from "Java the language" anyway, but still relying on the JVM as a platform, by adopting Groovy, and starting to learn Scala and Clojure.  The recent events with Oracle and the JCP make me a little less certain about the future of "Java as a platform," but not to the point of dropping it (yet).  Regardless of what happens with the ASF and Harmony, OpenJDK is out there, under GPL+classpath exception license, and Harmony does still exist even if it never gets TCK certification.  And with IBM and Apple seemingly on the OpenJDK bandwagon, I'm moderately optimistic that the JVM will live on in a suitable form.

For me, the only real action I'd take right now, is to "future proof" myself by starting to evaluate and learn some other platforms / languages... Erlang, Haskell, Lisp, Ocaml, whatever.


问:
Good practice to pass this information through URL parameter
Basically, let's suppose an application that manage some user's meetings.

I have a filtering zone on a page that aims to specify the category of items I need to specifically return.

Supposing two kind of filters:

Retrieving my actual meetings (meetings currently occurring or planned in the near future)

Retrieving my past meetings (meetings that are already past)

I think of passing a kind of url parameter like this:

www.myapp.com?me=actual

or

www.app.com?me=past

Indeed, I can't have both actual and past in the same call since it would not be appropriate for the listing.

So in my server side, I would handle through a simple conditional the passed value to filter the query.

Is it right enough to pass a string like this (past or actual) or is there a better practice to handle this case?

Note that by default, meaning without filtering, all meetings are returned.

答:
Totally standard. Even if both options could be used in parallel you could use something like me=actual;past and split on the server. I think the URL should read something like www.myapp.com/meetings?me=actual (in case you would have more functionality than just meetings and maybe want to go for RESTful routing right away or later)

With how URLs work the other option would be to have something like www.myapp.com/actual_meetings and www.myapp.com/past_meetings which would become ugly rather soon and at least for frameworks like Rails that use RESTful routes would need some extra work where not necessary. Also this has not very much flexibility in case you need to add more options, not too mention other cases where you have options are dynamically generated from database entries.

Some things may depend on your background technology of course, but for most websites you will see params used for such small details where one controller action can handle such very similar requests (where the difference is mostly a detail in the SQL query and all the business logic and view rendering of html stay the same anyway)

From a REST perspective this would be rather obvious, since meetings are clearly a REST resource and what you do would just call the index action (therefore www.myapp.com/meetings in plural) and which meetings to show only a matter of those params.


问:
LAMP without PHP
My question is that is the P part of the LAMP really necessary?
I will have the database and I can connect to it via the appache http so why will I need php/python in the server side (if it is a really simple set up)

also from a seperation of concern it might be more robust at least thertically to leave the P out of the equation and to use LAM only.

What are you guys think? I need to build this as a linux server in order to backend mobile ios and android.

cheers

答: LAMP is just a convenient platform.  If part of it doesn't fit your needs -- like, for example, you need run a windows server for $REASONS -- then replace that part.</p>

Title: LAMP without PHP


问:
Why doesn't Python have a "flatten" function for lists?
Erlang and Ruby both come with functions for flattening arrays. It seems like such a simple and useful tool to add to a language. One could do this:

```<code>>>> mess = [[1, [2]], 3, [[[4, 5]], 6]]
>>> mess.flatten()
[1, 2, 3, 4, 5, 6]
</code>```

Or even:

```<code>>>> import itertools
>>> mess = [[1, [2]], 3, [[[4, 5]], 6]]
>>> list(itertools.flatten(mess))
[1, 2, 3, 4, 5, 6]
</code>```

Instead, in Python, one has to go through the trouble of writing a function for flattening arrays from scratch. This seems silly to me, flattening arrays is such a common thing to do. It's like having to write a custom function for concatenating two arrays.

I have Googled this fruitlessly, so I'm asking here; is there a particular reason why a mature language like Python 3, which comes with a hundred thousand various batteries included, doesn't provide a simple method of flattening arrays? Has the idea of including such a function been discussed and rejected at some point?

答:
Proposals for a flatten function to be added to the standard library appear from time to time on python-dev and python-ideas mailing lists. Python developers usually respond with the following points:

A one-level flatten (turning an iterable of iterables into a single iterable) is a trivial one-line expression (x for y in z for x in y) and in any case is already in the standard library under the name itertools.chain.from_iterable.

What are the use cases for a general-purpose multi-level flatten? Are these really compelling enough for the function to be added to the standard library?

How would a general-purpose multi-level flatten decide when to flatten and when to leave alone? You might think that a rule like "flatten anything that supports the iterable interface" would work, but that would lead to an infinite loop for flatten('a').

See for example Raymond Hettinger:

It has been discussed ad nauseam on comp.lang.python. People seem to
  enjoy writing their own versions of flatten more than finding legitimate
  use cases that don't already have trivial solutions.

A general purpose flattener needs some way to be told what is atomic and
  what can be further subdivided. Also, it is not obvious how the algorithm
  should be extended to cover inputs with tree-like data structures with
  data at nodes as well as the leaves (preorder, postorder, inorder
  traversal, etc.)


答:
The “P” part of a LAMP stack is a layer of CGI scripts. This layer can be provided by a number of languages. While PHP is the most common of these, other languages such as Perl or Python can be used as well.

While a LAMP architecture is common and robust, it may not actually match your needs. For example it might make sense to not use CGI scripts and leave out the “A” (Apache HTTP Server), and use a more integrated web framework of your language of choice instead. When using Perl, a common stack would be to utilize Linux running a Perl application built around the Mojolicious web framework, using Starman as a server and PostgreSQL as a DB, and running behind Nginx as a caching proxy. Which stack to choose depends directly on the project you are tackling, and on the technologies you (and your team) are familiar with.

Title: LAMP without PHP

Body:
My question is that is the P part of the LAMP really necessary?
I will have the database and I can connect to it via the appache http so why will I need php/python in the server side (if it is a really simple set up)

also from a seperation of concern it might be more robust at least thertically to leave the P out of the equation and to use LAM only.

What are you guys think? I need to build this as a linux server in order to backend mobile ios and android.

cheers


答:
Do unto others as you wish they would do unto you.  I would definitely not tell my boss in this case.

It's also your boss's job to deal with issues like this, and not yours.  Getting involved in this way in other people's business is usually a detriment to you.

Title: If your workmate is quitting his job, would you notify your boss?

Body: If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>


问:
Are functional languages better at recursion?
TL;DR : Do functional languages handle recursion better than non-functional ones?

I am currently reading Code Complete 2. At some point in the book, the author warns us about recursion. He says it should be avoided when possible and that functions using recursion are generally less effective than a solution using loops. As an example, the author wrote a Java function using recursion to compute the factorial of a number like so (it may not be exactly the same since I do not have the book with me at the moment):

```<code>public int factorial(int x) {
    if (x <= 0)
        return 1;
    else
        return x * factorial(x - 1);
}
</code>```

This is presented as a bad solution. However, in functional languages, using recursion is often the preferred way of doing things. For example, here is the factorial function in Haskell using recursion:

```<code>factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
</code>```

And is widely accepted as a good solution. As I have seen, Haskell uses recursion very often, and I did not see anywhere that it is frowned upon.

So my question basically is:

Do functional languages handle recursion better than non-functional ones?

EDIT : I am aware that the examples I used are not the best to illustrate my question. I just wanted to point out that Haskell (and functional languages in general) uses recursion much more often than non-functional languages.

答:
Functional languages are better at two very specific kinds of recursion:  tail recursion and infinite recursion.  They are just as bad as other languages at other kinds of recursion, like your factorial example.

That's not to say there aren't algorithms that work well with regular recursion in both paradigms.  For example, anything that requires a stack-like data structure anyway, like a depth-first tree search, is simplest to implement with recursion.

Recursion comes up more often with functional programming, but it is also way overused, especially by beginners or in tutorials for beginners, perhaps because most beginners to functional programming have used recursion before in imperative programming.  There are other functional programming constructs, like list comprehensions, higher-order functions, and other operations on collections, that are usually much better suited conceptually, for style, for conciseness, for efficiency, and for ability to optimize.

For example, delnan's suggestion of factorial n = product [1..n] is not only more concise and easier to read, it's also highly parallelizable.  Same for using a fold or reduce if your language doesn't happen to have a product already built in.  Recursion is the solution of last resort for this problem.  The main reason you see it solved recursively in tutorials is as a jumping off point before getting to better solutions, not as an example of a best practice.