问:
Visiting points on a number line while minimizing a cost not related to distance
I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement.

Problem

There are N = 1000 nuclear waste containers located along a 1-D number line at distinct positions from -500,000 to 500,000, except x=0. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at x = 0 and can move 1 unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers.

Sample Input:

4 Containers located at [-12, -2, 3, 7].

The best order to collect these containers is [-2, 3, 7, -12], for a minimum emitting of 50 units. Explanation: the person goes to -2 in 2 seconds and during that time 2 units of radiation are emitted. He then goes to 3 (distance: 5) so that barrel has released 2 + 5 = 7 units of radiation. He takes 4 more seconds to get to x = 7 where that barrel has emitted 2 + 5 + 4 = 11 units. He takes 19 seconds to get to x = -12 where that barrel has emitted 2 + 5 + 4 + 19 = 30 units. 2 + 7 + 11 + 30 = 50, which is the answer.

Notes

There is an obvious O(N!) solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked.

I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:

We insert 0 in as a baseline position (This will be the initial state)

Then, we sort the positions from least to greatest.

We then do a BFS/PFS, where the state consists of

Two integers l and r that represent a contiguous range in the sorted position array that we have visited already

An integer loc that tells us whether we're on the left or right endpoint of the range

An integer time that tells us the elapsed time

An integer 'cost' that tells us the total cost so far (based on nodes we've visited)

From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly

Final state is [0, N], checking both ending positions.

However, it seems that [L, R, loc] does not uniquely define a state, and we have to store L, R, loc, and time, while minimizing cost at each of these. This leads to an exponential algorithm, which is still way too slow for any good.

Can anyone help me expand on my idea or push my into the right direction?

Edit: Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current cost is low doesn't mean it is the optimal answer for that sub problem, since the time also affects the answer greatly.

Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such).

Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.

答:
I think you can improve this by looking at the problem as a directed graph of pairs of positions.

For this example I will use the line with values -9, -6, -1, 3, and 5.

Because it's too hard to draw a graph with just text, I'm going to represent the pairs as a table.  We can think of the cells as representing the state where all containers between those two positions have been collected.  Each cell has two values, one representing the cost to go left, the other representing the cost to go right (to the next container).

The values can simply be calculated as the distance between the two points multiplied by the number of barrels outside of those two points + 1.  Cells where both numbers have the same sign represent cases when all barrels of the opposite sign have been collected.  These are calculated using only the number of barrels in the direction away from zero.

In the table values of X mean that you can't go in that direction (all the barrels in that direction have been taken).  The rows represent the current position of the collector and the columns represent the location of the next opposite barrel.

```<code>    +------+------+------+------+------+
    |  -9  |  -6  |  -1  |   3  |   5  |
+---+------+------+------+------+------+
|-9 |      |      |      | X, 24| X, 14|
+---+------+------+------+------+------+
|-6 | 3, X |      |      | 9, 27| 6, 22|
+---+------+------+------+------+------+
|-1 |      |10, X |      |20, 8 |15, 18|
+---+------+------+------+------+------+
| 3 |24, 4 |27, 6 |16, 8 |      | X, 2 |
+---+------+------+------+------+------+
| 5 |14, X |22, X |18, X |      |      |
+---+------+------+------+------+------+
</code>```

The rules for moving between squares can be somewhat confusing.

For negative numbered columns, the rules are as follows:

Going right moves down one cell.

Going left moves down one cell and then mirrors across the diagonal.

If the right value is X, going left moves up to the diagonal (where the column and row are equal) and left by one.

For positive numbered columns, the rules are as follows:

Going left moves up one cell.

Going right moves up one cell and then mirrors across the diagonal.

If the left value is X, going right moves down to the diagonal and right by one.

Now we can run Dijkstra's algorithm to calculate the best path, using these movement rules to traverse the graph.  Our starting positions are (-1, 3) and (3, -1) with initial costs of 5 and 15, respectively.  Once we've calculated values for the two end positions (left of (-9, -9) and right of (5, 5)) the smaller of the two is our answer.

The running time for each of the steps are:

O(N log N) for initially sorting the input values along the line

O(N^2) for calculating the table/graph

O(N^2 log N) for running Dijkstra's on the graph (Note: there are at most two edges for any given vertex).

The first two steps are dominated by the last, so your overall runtime is O(N^2 log N) which should be a good enough runtime for the challenge.

Body:
I think you can improve this by looking at the problem as a directed graph of pairs of positions.

For this example I will use the line with values -9, -6, -1, 3, and 5.

Because it's too hard to draw a graph with just text, I'm going to represent the pairs as a table.  We can think of the cells as representing the state where all containers between those two positions have been collected.  Each cell has two values, one representing the cost to go left, the other representing the cost to go right (to the next container).

The values can simply be calculated as the distance between the two points multiplied by the number of barrels outside of those two points + 1.  Cells where both numbers have the same sign represent cases when all barrels of the opposite sign have been collected.  These are calculated using only the number of barrels in the direction away from zero.

In the table values of X mean that you can't go in that direction (all the barrels in that direction have been taken).  The rows represent the current position of the collector and the columns represent the location of the next opposite barrel.

    +------+------+------+------+------+
    |  -9  |  -6  |  -1  |   3  |   5  |
+---+------+------+------+------+------+
|-9 |      |      |      | X, 24| X, 14|
+---+------+------+------+------+------+
|-6 | 3, X |      |      | 9, 27| 6, 22|
+---+------+------+------+------+------+
|-1 |      |10, X |      |20, 8 |15, 18|
+---+------+------+------+------+------+
| 3 |24, 4 |27, 6 |16, 8 |      | X, 2 |
+---+------+------+------+------+------+
| 5 |14, X |22, X |18, X |      |      |
+---+------+------+------+------+------+

The rules for moving between squares can be somewhat confusing.

For negative numbered columns, the rules are as follows:

Going right moves down one cell.

Going left moves down one cell and then mirrors across the diagonal.

If the right value is X, going left moves up to the diagonal (where the column and row are equal) and left by one.

For positive numbered columns, the rules are as follows:

Going left moves up one cell.

Going right moves up one cell and then mirrors across the diagonal.

If the left value is X, going right moves down to the diagonal and right by one.

Now we can run Dijkstra's algorithm to calculate the best path, using these movement rules to traverse the graph.  Our starting positions are (-1, 3) and (3, -1) with initial costs of 5 and 15, respectively.  Once we've calculated values for the two end positions (left of (-9, -9) and right of (5, 5)) the smaller of the two is our answer.

The running time for each of the steps are:

O(N log N) for initially sorting the input values along the line

O(N^2) for calculating the table/graph

O(N^2 log N) for running Dijkstra's on the graph (Note: there are at most two edges for any given vertex).

The first two steps are dominated by the last, so your overall runtime is O(N^2 log N) which should be a good enough runtime for the challenge.


问:
Origin of the name “OpenServer” for the SCO Unix operating system
I was looking over the evolutionary history of Unix and Unix-like systems on Wikipedia and one operating system name stood out to me: OpenServer.

Judging from the image, SCO's OpenServer is completely closed sourced; so why does SCO OpenServer have the word "open" in its name if the operating system is proprietary and contains no open source code?

I suspect this is because the original Unics operating system had a mixed/shared license, but that seems like a pretty distant ancestor when the proprietary Xenix came before OpenServer as well. Can anyone shed some light on the reason for this name?

答:
I think MichaelT is correct: it seems the word "open" here refers to the open standards compliance of the operating system.

I took at look at the SCO Open Desktop Release 2.0 - Product Overview Paper; in the section titled An Open System for Freedom of Choice, there are a number of references to "open
systems standards".

Because it is based on acknowledged open  systems standards, SCO Open
  Desktop protects and enhances the current hardware  and software
  resources of these organizations, while freeing them from dependence
  on any single hardware or software vendor.

Compliance to open standards allowed OpenServer to give the user freedom in choosing which hardware to use with operating system, rather than being confined to a specific vendor or set of components.

ContentLicense: CC BY-SA 3.0


答:
In the late 80's, the word "Open" was applied to many different parts of the computing world to mean different things.

The most familiar to us today is "Open Source."  The concept of open source existed quite a bit before the late '80's with the BSD license (one form of what is known as open source today).  This source of "open" though is late '90s:

The label "open source" was adopted by a group of people in the free software movement at a strategy session held at Palo Alto, California, in reaction to Netscape's January 1998 announcement of a source code release for Navigator.

...

In February 1998, Raymond made the first public call to the free software community to adopt the new term.

(from Wikipedia on Open Source)

Thus, this is not the source of the Open in Open Server as it predates it by a decade.  Which brings us to...

Lesser known and largely not important anymore (the Unix Wars are largely over) is The Open Group which was previously known as Open Software Foundation.

The OSF (and there's a name that might stick in some people's memory - OSF/1) was founded "to create  an open standard for an implementation of the UNIX operating system."

Prior to OSF, each major company had a very different flavor of Unix.  There was AIX, and AUX, and Ultrix, and IRIX, and Minix, and SunOS, and SCO, and Xenix, and BSD, and...

Each of these was tied to a specific hardware platform.  One couldn't run the OS of one on another hardware platform.  The definition of what was Unix and what standards one needed to compile code from Ultrix on an AIX machine were still very much in flux (Posix was set down in 1988).

With the late 80's, this lock in raised in prominence and some companies renamed their software to indicate that they were not locked in to particular hardware.  This is about open standards and open systems - not open software.

OpenVMS (from Wikipedia) is one such naming:

In 1991 it was renamed again to OpenVMS to indicate its support for industry standards such as POSIX and Unix compatibility, and to drop the hardware connection as the port to DIGITAL's 64-bit Alpha RISC processor was in process.

This naming would mirror the naming of OpenServer by SCO, being released in 1989.

Title: Origin of the name “OpenServer” for the SCO Unix operating system

Body:
I was looking over the evolutionary history of Unix and Unix-like systems on Wikipedia and one operating system name stood out to me: OpenServer.

Judging from the image, SCO's OpenServer is completely closed sourced; so why does SCO OpenServer have the word "open" in its name if the operating system is proprietary and contains no open source code?

I suspect this is because the original Unics operating system had a mixed/shared license, but that seems like a pretty distant ancestor when the proprietary Xenix came before OpenServer as well. Can anyone shed some light on the reason for this name?


问:
Can I use Visual Studio 2010 Architectural features to enforce design on code, without feature packs?
I am studying Visual Studio 2010's architectural tools for application lifecycle management.

After we have sketched some modeling diagrams, we wonder now how should be the natural workflow to convert that to architecture-compliant code.

We noticed that UML Explorer tab keeps track of entities created in class diagrams, sequence diagrams and component diagrams, but not so with layer diagrams and activity diagrams.

The main problem is: when the modeling is ready, how would be the expected way to convert it to a compliant code? Possible paths could be:

"you have to manually keep track of everything";

"you can use feature X and/or technique Y";

"There's no way to do that without the Modeling Feature Pack";

As far as I have researched until now, everything suggests that the Feature Pack is needed, but I wonder what would be the point to have those standard modeling projects if the greatest advantages of modeling (tracking and validating development code) cannot be performed...

UPDATE: This blog post shows how to use Layers Diagram of a modeling project (via Validation flag on modeling project's properties tab) to RAISE BUILD ERRORS in case a layer dependency (which can be manually created) is violated. That seems promising, and I wonder which more of these hidden features the "non-feature-packed" Visual Studio 2010 might have.

Thanks for any help

答:
As you have discovered, the layer validation, for C# at least, was present out of the box with Visual Studio Premium and Ultimate.

You also get the ability to generate Dependency Graphs, and Sequence Diagrams from your code, as well as the old-school class diagram view that has been around since VS2005 (possibly 2008, I'm not sure). I don't believe there is any code generation from models, though.

Whilst you can draw UML static structure diagrams, you can't generate them from code without the feature pack.

With the feature pack you can do Code-to-UML, and UML-to-Code (for C#, at least). The feature pack also extends the visualisation features that were out-of-the-box for C# so that they can handle C/C++, and also extends the layer diagram features to C++.

In answer to your question about what the point would be:
Microsoft often ship to fairly hard (as in, must not be missed) deadlines, and so sometimes features don't make the cut for quality reasons. These are often shipped as feature packs, service packs, etc. I believe they always intended the functionality to work the way it does with the feature pack, it just wasn't ready for the target ship-date.

The links to the documentation for the out-of the box features is:
http://msdn.microsoft.com/en-us/library/57b85fsc(v=vs.100).aspx

I presume you have the link to the feature pack docs, but for future readers:
http://msdn.microsoft.com/en-us/library/dd460723(v=vs.100).aspx


问:
Why don't I see many unit test projects that bring up and tear down a DB? (ASP.NET MVC)
I see all the examples that demonstrate unit testing code and mocking the calls to the DB since you are not suppose to touch the DB. But it seems to me having a set up tasks that uses the actually schema, loads the lookup tables and then populates it with data using the methods to be tested... This way it is more real world testing and all the stored procedures are tested as well.. But I never have seen any examples like this...  Is there some reason I do not understand why using this technique is not as useful as it seems ? </p>

<p>EDIT1: Sorry.. I shouldn't have called it unit test.. yes. I will have unit tests as well that are for testing code.. But beyond that it seems like a good idea to bring up and tear down and DB and have code that modifies that DB and does assertions.. But I don't want this to be UI testing.. I just want to perform a lot of CRUD functions and a lot of assertions .. :My question is #1 does this make sense.. #2 how do I automate this all within visual studio ? How do I tell VS 2012 to run a SQL script before running the tests? is there some special API for this ? </p>

答:
It's because a unit test shouldn't have any dependencies. It must be self contained. Unit tests exists to test a "unit" of logic in your code by treating it as a black box. The specific source of data (database or other) should have no impact on the logic.

Anything else, even if called via a unit testing framework isn't classed as a unit test. It would be a different type of test such as a functional test.

It's worth looking up some of Kent Beck 's material on TDD.


答:
The definition of unit test is a test that tests single unit of behavior in isolation. A test that tests integration with the database is testing neither a single unit nor in isolation, therefore it is by definition not a unit test.

Asking why there are no unit tests that integrate with the database is like asking why there are no odd numbers divisible by two: it's simply because of the definition of the word "odd number".

Title: Why don't I see many unit test projects that bring up and tear down a DB? (ASP.NET MVC)

Body:
I see all the examples that demonstrate unit testing code and mocking the calls to the DB since you are not suppose to touch the DB. But it seems to me having a set up tasks that uses the actually schema, loads the lookup tables and then populates it with data using the methods to be tested... This way it is more real world testing and all the stored procedures are tested as well.. But I never have seen any examples like this...  Is there some reason I do not understand why using this technique is not as useful as it seems ? </p>

<p>EDIT1: Sorry.. I shouldn't have called it unit test.. yes. I will have unit tests as well that are for testing code.. But beyond that it seems like a good idea to bring up and tear down and DB and have code that modifies that DB and does assertions.. But I don't want this to be UI testing.. I just want to perform a lot of CRUD functions and a lot of assertions .. :My question is #1 does this make sense.. #2 how do I automate this all within visual studio ? How do I tell VS 2012 to run a SQL script before running the tests? is there some special API for this ? </p>


问:
What are the disadvantages of using stored procedures, SSIS, and SSRS to implement business applications?
Recently, it was suggested that many projects (where I work) should be implemented using some combination of stored procedures (on SQL Sever / T-SQL), SSIS, and SSRS.

In one specific project, SSIS would get a file from a SFTP server. The file contains the daily price of ten stocks. A data warehouse will store the daily price of each stock since inception. As of now, the prices go back twenty-five years. Stored procedures will have the business logic to calculate various performance numbers (i.e. return %) during arbitrary time periods such as the 5 year return at 31 December 2012.

These stored procedures would be used by SSRS to create reports for the end users.

What are the problems/issues using this approach? I feel that vendor (Microsoft) lock is an issue but I don't see that (unfortunately) being enough to change direction. Also, I have a concern about all the business logic being stored procedures. What are the arguments against/for putting this business logic (i.e. calculation of performance numbers) in stored procedures versus using Java (or some other OO programming language) with ORM (such as myBatis)?

答:
The biggest advantage of stored procedures is that they are limited to T/SQL statements.  That usually keeps complexity down.

A solution in a more general language has to solve many problems that a T/SQL procedure does not: how to map objects to database tables (ORM), how to schedule imports, how to log exceptions, how to connect to the database.  That can get very complex, especially if the author tries to solve the problem in a general way.

A side advantage is that T/SQL does not change very often.  A stored procedure from 1995 runs fine on SQL Sever 2012.  By contrast, a general purpose language from 2008 feels antique and dated today.


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Buying expensive off-the-shelve products when the open source alternatives are better and free.

How many companies use git? How many companies use some crappy enterprisey version control?

ContentLicense: CC BY-SA 2.5


答:
I wouldn't worry much about vendor lock-in. Changing databases is always a complex challenge; Microsoft isn't getting rid of SQL Server any time soon, so I would feel comfortable building against it specifically.

I've got no experience with SSIS and SSRS, but I do use stored procedures exclusively for database access. I like them because they separate data from consumption--as a programmer, I shouldn't care how I know what the value of a stock portfolio, just what it is. Stored procedures give me the power to do all that work in one place (and in the database, so there is never the urge to try to roll your own set-based logic in procedural code). Performance is also better, especially when you have massive result sets and aggregations.

Title: What are the disadvantages of using stored procedures, SSIS, and SSRS to implement business applications?

Body:
Recently, it was suggested that many projects (where I work) should be implemented using some combination of stored procedures (on SQL Sever / T-SQL), SSIS, and SSRS.

In one specific project, SSIS would get a file from a SFTP server. The file contains the daily price of ten stocks. A data warehouse will store the daily price of each stock since inception. As of now, the prices go back twenty-five years. Stored procedures will have the business logic to calculate various performance numbers (i.e. return %) during arbitrary time periods such as the 5 year return at 31 December 2012.

These stored procedures would be used by SSRS to create reports for the end users.

What are the problems/issues using this approach? I feel that vendor (Microsoft) lock is an issue but I don't see that (unfortunately) being enough to change direction. Also, I have a concern about all the business logic being stored procedures. What are the arguments against/for putting this business logic (i.e. calculation of performance numbers) in stored procedures versus using Java (or some other OO programming language) with ORM (such as myBatis)?


答:
One problem with this solution is that it pre-supposes that the solution be database driven, that the database be a relational database, and that it is acceptable to put the logic in the database. There are several challenges here.

Have you tried spikes using non-relational technologies like MongoDB? MongoDB itself is free (though they offer commercial support), insanely easy to get started with, and far less complex than a SQL based approach.  Depending on your data structure you might want to consider a column store (like Cassandra), a key value store (like Riak), or a graph database (like Neo4J).  If you want to know more about these kinds of databases try checking out the book NoSQL Distilled http://martinfowler.com/books/nosql.html

It is sometimes considered advantageous to centralize business logic in as few places as possible. It can make your application far easier to manage when source code is expressive and laid out in a way that is easy for programmers to understand, and it's quite difficult to do this in SQL. Also it's hard to maintain SQL code - there's no decent re-factoring support, code analysis support, decent IDEs are hard to come by.

While its getting easier and easier to do Continuous Integration, Test Driven Development and Continuous Delivery with modern software programming environments, it't not getting much easier to automate the database portion of your app. Many teams struggle with automating migrations, coordinating database versions with software versions and other struggles. It doesn't help that often to automate the deployment of your application to several environments, you'll have licensing issues to work through, which will make Continuous Integration and Continuous Delivery harder. This is compounded by the fact that there is not a rich ecosystem of testing frameworks for SQL, which is going to make it harder to develop a test suite that gives you confidence that you haven't broken your app.

More and more, many teams are considering the database an option for persistence; not for logic or functionality. This is leading to better architecture and applications that are easier to manage, test, and deploy.


答:
TLDR

Storing your queries separate from the reports they drive will create a mess in your database; if you are going for plain SQL queries, embed them in the report.

Consider using SSAS (SQL Server Analysis Services), or SSRS Report Models (sometimes called a semantic model), rather than plain old SQL queries. Not always possible, but generally performs better.

Don't put things like calculation of performance figures in procedural code like Java, or C#, it is better to make them part of a view on top of your database (such as the SSRS, or SSAS features mentioned above), they perform better, and logically sit inside your reporting stack.

Full Answer

The biggest disadvantage of backing your reports with stored procedures is that the report, and the query to fill it are stored separately, and whilst the report tells you what query it depends on, the stored procedures do not tell you which assets depend on them. Now, you might start off with the intention of having a strict 1-to-1 mapping of stored procedures to reports, but in my experience, somebody will try to be clever later on and layer on stored procedure on top of another, and you end up with a web of dependencies (I've spent the last 6 months on a project to slightly improve the situation at my workplace). If you maintain rigorous documentation you can deal with this, but let's face it, documentation is hard, and annoying, and almost always out of date.

A better solution to using stored procedures would be to embed the query straight in the report, this way the report and the query are coupled to each other, they reside together and you don't get other dependent assets latching on without your knowledge. I know that this flies in the face of the "conventional wisdom" about code reuse, but SQL is not code, and the dependency chains can not be determined anywhere near as easily is in compiled code.

Another disadvantage of stored procedures is that they aren't actually the best way to drive reports, especially when you are talking about calculating aggregates over a period of 25 years. SSAS (Sql Server Analysis Services) is specifically designed for this kind of querying, and it facilitates a much more user-friendly method of building queries and reports (empowering users to build reports is brilliant). Furthermore, it allows the same data to be queried through excel as pivot tables etc (which people love). Microsoft's whole direction with reporting is to move the querying out of the database, and into the SSRS/SSAS layer. You won't always be able to produce all your reports this way, and will have to fall back to a hand-written SQL query at some point, but keep it in the report.

Now, as for the question around whether the "business logic" should be in Java. If you're talking about calculations for various statisics, or KPIs, essentially static functions over the data, rather than anything that deals with user interaction, then no, you shouldn't stick those things in code. They should be a part of your reporting stack. In Microsoft-land the best place to put these is in a SSRS Model, or an Analysis Cube (in fact the 2012 products have a replacement for the cube which gives you the same concept without needing to have batch-processing step, so it works off live data).


问:
Object Orientation done right with PHP
I've started to work with web development using PHP as server side programming language. In that time I didn't know the benefits of object orientation and had a hard time trying to write more maintainable code (for instance, spliting presentation from logic, and etc).

After some years I knew about ASP.NET MVC and I gave it a try. I've learned how to work with the .NET plataform using C# programming language and I really found awesome how better structured my applications could be using good object orientation (dependency injection for instance was something that when I saw it for the first time I thought: "that's everything I always needed").

The point is that although I'm happy working with ASP.NET MVC, I still need in some projects to work with PHP, however I was wondering if it's possible to bring all the benefits from object orientation to PHP. I didn't find a way to do so on my own because for instance, PHP is not strongly typed so that it becomes a little complicated to make use of dependency injection as I've learned when working with ASP.NET MVC. Also, many of the things I've learned when working with MVC in ASP.NET although very cool and useful I didn't find a way to do the same in PHP.

Now here comes the question: does anybody know about resources to learn how to take benefits of all that cool things from OOP to PHP? I'm interested in any resources: books, tutorials, videos, etc.

Thanks very much in advance, and sorry if this question is silly.

答:
To develop websites with PHP using an OOP approach you'll need the following.

phpStorm will allow you to apply type details to your objects, methods and variables via PHPDocs. While other IDEs support this, phpStorm has been the only one that seems to work correctly in my experience (NetBeans has just doesn't work). Type details are required to really take advantage of OOP programming, because without it you simply don't know what $obj->doThing() really does.

PHP OOP works best with namespaces and well thought out class loaders. A popular approach is to structure your classes and files in a similar pattern as to Java packages.

What is OOP? This is a very wide open question. There are design patterns, language specific syntaxes and frameworks. It's difficult to say code in PHP is OOP. At what point does it become OOP? C# forces an OOP approach because the web services require it. You can still develop a very badly designed OOP solution in C#, but a very well designed non-OOP approach in PHP. OOP on it's own isn't the solution to anything.

I haven't used it, but I think CodeIgniter uses an OOP approach in it's design. The declarations of controllers, models and views is based upon abstraction. CakePHP is also an OOP approach, but it uses many PHP tricks to shorten the developers work. As a result, it often doesn't follow what I feel is a true OOP design, but it's a very good framework.

PHP lack of typed variables and parameters for methods is one of it's weak points in OOP. It's a problem of scale. OOP is a tool that allows you to scale your problems by building pieces that fit together. What happens when you need to refactor the method of a base class in PHP? The risks of introducing a new bug is very high, where is in C# you'll break the interface contract at compile time. The risk is very low. So designing classes and methods in PHP is a practice in careful forethought, rather than coding time experimenting. If you follow the guidelines for writing PHPDoc comments, declare your parameter types and use phpStorm. You'll be able to handle a larger OOP design then using other tools (in my mind).

Title: Object Orientation done right with PHP


问:
How does Go improve productivity with "implicit" interfaces, and how does that compare with C#'s notion of Extension Methods?
In the Go Language Tutorial, they explain how interfaces work:

Go does not have classes. However, you can define methods on struct types.  The method receiver appears in its own argument list between the func keyword and the method name.

```<code>type Vertex struct {
    X, Y float64
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
</code>```

An interface type is defined by a set of methods.  A value of interface type can hold any value that implements those methods.

This is the only way to create an interface in Go.  Google further explains that:

A type implements an interface by implementing the methods. There is no explicit declaration of intent [i.e. interface declarations].

Implicit interfaces decouple implementation packages from the packages that define the interfaces: neither depends on the other.

It also encourages the definition of precise interfaces, because you don't have to find every implementation and tag it with the new interface name.

This all sounds suspiciously like Extension Methods in C#, except that methods in Go are ruthlessly polymorphic; they will operate on any type that implements them.

Google claims that this encourages rapid development, but why?  Do you give up something by moving away from explicit interfaces in C#?  Could Extension Methods in C# allow one to derive some of the benefits that Go interfaces have in C#?

答:
I don't see extension methods and implicit interfaces as the same at all.

First let's speak to purpose.

Extension methods exist as a syntactic sugar specifically to give you the ability to use a method as if it's a member of an object, without having access to the internals of that object. Without extension methods you can do exactly the same thing, you just don't get the pleasant syntax of someObjectYouCantChange.YourMethod() and rather have to call YourMethod(someObjectYouCantChange).

The purpose of implicit interfaces however is so that you can implement an interface on an object you don't have access to change. This gives you the ability to create a polymorphic relationship between any object you write yourself and any object you don't have access to the internals of.

Now let's speak to consequences.

Extension methods really have none, this is perfectly in line with the ruthless security constraints .NET tries to use to aid in distinct perspectives on a model (the perspective from inside, outside, inheritor, and neighbor). The consequence is just some syntactic pleasantness.

The consequences of implicit interfaces are a few things.

Accidental interface implementation, this can be a happy accident, or an accidental LSP violation by meeting someone else's interface which you didn't intend to while not honoring the intent of it's contract.

The ability to easily make any method accept a mock of any given object at all by simply mirroring that objects interface (or even just creating an interface that meets that methods requirements and no more).

The ability to create adapters or other various similar patterns with more ease in regards to objects you can't meddle at the innards of.

Delay interface implementation, and implement it later without having to touch the actual implementation, only implementing it when you actually want to create another implementor.


答:
I wouldn't be too worried about vendor lock-in. Moving to a different database would be a very large project for anyone and would be rare.

Arguments for putting all business logic into stored procs:

For very heavy duty data processing, you need very well optimized code. This is what databases excel at - it makes a lot of sense to write very finely tuned SQL and pay a lot of attention to indexes and query plans etc. This will undoubtedly become in issue if you don't use the correct tool/technology for this heavy lifting.

Databases (eg sql server) will performance tune themselves based on your query using statistics. This is a large benefit.

All of the logic will be in one place and (if well written) should be relatively easy to maintain, edit and deploy and script into source code control.

Lots of people know how to write and maintain procs, it's a very mature science.

Cons:

Stored procs can grow into an unmaintainable mess if not written carefully. While this is true of any language, it's especially true of SQL server stored procs.

Doing any logic that isn't directly database work (eg copying files around) isn't what a database is designed for. Maybe it has that functionality, but in my opinion you definitely want an application that will do this - when it comes to FTP'ing files around, unzipping etc you really want the full control of application code. Maybe a database can do this kind of thing, but I have very strong doubts whether it can do it well, provide good error handling etc. What if you need to unzip a file that's password protected? What if the file is empty? Network connection dropout? File is locked? What if... etc I'm sure there are lots of use-cases that the DB can't handle.

Debugging large stored procs can be very, very difficult. If things start going very wrong then you're in for a world of pain.

It can be very easy for stored procs to get out of sync between systems (Dev DB, UAT DB, production DB). This needs to be done very carefully. (Personally I script all of my procs and as part of my builds/releases I run in the procs into their respective databases, great once it's all setup).

(Here's an opinion for you) - SSRS is a pain in a butt. I hate it and so do most of the devs that I know, no-one wants to work when them. Try to hire someone to maintain SSRS stuff will be much harder than hiring a Java developer.

If it was me, I'd write a Java application to do the file handling, and for the heavy duty data processing use stored procs, if necessary. Best of both worlds and no SSRS :)


问:
Card deck and sparse matrix interview questions
I just had a technical phone screen w/ a start-up.  Here's the technical questions I was asked ... and my answers.  What do think of these answers?  Feel free to post better answers :-)

Question 1:  how would you represent a standard 52 card deck in (basically any language)?  How would you shuffle the deck?

Answer:  use an array containing a "Card" struct or class.  Each instance of card has some unique identifier... either it's position in the array or a unique integer member variable in the range [0, 51].  Shuffle the cards by traversing the array once from index zero to index 51.  Randomly swap ith card with "another card" (I didn't remember how this shuffle algorithm works exactly).  Watch out for using the same probability for each card... that's a gotcha in this algorithm.  I mentioned the algorithm is from Programming Pearls.

Question 2:  how to represent a large sparse matrix?  the matrix can be very large... like 1000x1000... but only a relatively small number (~20) of the entries are non-zero.

Answer:  condense the array into a list of the non-zero entries.  for a given entry (i,j) in the array... "map" (i,j) to a single integer k... then use k as a key into a dictionary or hashtable.  For the 1000x1000 sparse array map (i,j) to k using something like f(i, j) = i + j * 1001.  1001 is just one plus the maximum of all i and j.  I didn't recall exactly how this mapping worked... but the interviewer got the idea (I think).

Are these good answers?  I'm wondering because after I finished the second question the interviewer said the dreaded "well that's all the questions I have for now."

Cheers!

答:
Wouldn't this ensure that you do not touch an already placed element again? </p>

```<code>for (i = 51; i >= 2; i--) {
  swap(arr[i], arr[rand() % i]);
}

swap(arr[0], arr[1]); //just to be safe.
</code>```

<p>(referring to Watch out for using the same probability for each card... that's a gotcha in this algorithm.)</p>

Body:
Wouldn't this ensure that you do not touch an already placed element again?

for (i = 51; i >= 2; i--) {
  swap(arr[i], arr[rand() % i]);
}

swap(arr[0], arr[1]); //just to be safe.

(referring to Watch out for using the same probability for each card... that's a gotcha in this algorithm.)


答:
Instead of just saying "Because it's a unit test", lets talk about why we might want to have a test that doesn't depend on a database.

Isolated Failures

We want a failing unit test to quickly identify where an issue is. The narrowest unit test failure already has two possible sources, both the unit under test and the test itself. Every dependency is another possible error source.

Assuming you do not have custom database data for every test, you run the risk that someone modifies the data for another test, but breaks yours. If you do have data for every test, then managing it all just became a pain. Schema change? Go modify every unit test.

Fast Failures

Unit tests should be fast. How fast? Fast enough that developers do not resist running them regularly, and do not waste time when doing so. Unit tests quickly lose a lot of value if people never run them because they spend 45 minutes setting up and tearing down the database 1000+ times.

Testing with the Database

That being said, our app does use a database. If we never test with the database, we don't really know if the app works. Many projects do this testing when testing the integrated whole, and usually get run less often than unit tests. For example, one of my projects involved several applications with unit tests that could be run in less than 30 seconds a piece, but the integrated system tests lasted 4+ hours on a compute grid.


问:
Reasoning to wait until third time in the Rule of Three?
I just came across the article "Rule of Three" in wikipedia

Rule of three is a code refactoring rule of thumb to decide when a
  replicated piece of code should be replaced by a new procedure. It
  states that the code can be copied once, but that when the same code
  is used three times, it should be extracted into a new procedure. The
  rule was introduced by Martin Fowler in Refactoring and attributed
  to Don Roberts.

I know that this is just a rule of thumb, but why is it recommended to refactor only after the second duplication? Is there any downside to refactoring when we write the first duplication?

答:
I think this rule of thumb exists because it is easy to get caught into playing "What if..." when designing the code for the first time or after the first duplication.  I've encountered severe analysis paralysis in some cases because people started designing functionality that might be needed later.  But not needed for the immediate problem at hand.

There is an art for designing/writing only what you need, while keeping the code amenable to future re-factoring.


答:
Yes, it's quite possible, and it's the way things are going.  The PHP community seems to be moving more towards a Java style (heavily object oriented, verbose, etc.).

PHP the Right Way

Some notable things...

Namespaced code (after 5.3)

Standardized naming / file management as per php standards group (PSR-0)

Dependency management with Composer (like Ruby Gems, Node npm modules, etc.)

Dependency Injection Container (Symfony's is like Java's Spring), or Pimple, etc.

ORM (Doctrine2 is like Java's Hibernate)

Automated testing with PHPUnit, Behat, etc.

It's actually quite a nice ecosystem if you are using the newer set of tools.

Title: Object Orientation done right with PHP

Body:
I've started to work with web development using PHP as server side programming language. In that time I didn't know the benefits of object orientation and had a hard time trying to write more maintainable code (for instance, spliting presentation from logic, and etc).

After some years I knew about ASP.NET MVC and I gave it a try. I've learned how to work with the .NET plataform using C# programming language and I really found awesome how better structured my applications could be using good object orientation (dependency injection for instance was something that when I saw it for the first time I thought: "that's everything I always needed").

The point is that although I'm happy working with ASP.NET MVC, I still need in some projects to work with PHP, however I was wondering if it's possible to bring all the benefits from object orientation to PHP. I didn't find a way to do so on my own because for instance, PHP is not strongly typed so that it becomes a little complicated to make use of dependency injection as I've learned when working with ASP.NET MVC. Also, many of the things I've learned when working with MVC in ASP.NET although very cool and useful I didn't find a way to do the same in PHP.

Now here comes the question: does anybody know about resources to learn how to take benefits of all that cool things from OOP to PHP? I'm interested in any resources: books, tutorials, videos, etc.

Thanks very much in advance, and sorry if this question is silly.


问:
What is the time complexity of the algorithm to check if a number is prime?
What is the time complexity of the algorithm to check if a number is  prime?

This is the algorithm :

bool isPrime (int number) {
    if (number < 2) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;
    for (int i=3; (i*i) <= number; i+=2) {
        if (number % i == 0 ) return false;
    }
    return true;
}
```

答:
O(sqrt(n)) in the magnitude of the number, but only as long as you use int

Note that complexities for prime number related algorithms are often discussed with n as the length (in bits) of the number - and that you cannot assume things like comparing, adding, modulor or multiplying to be O(1), because with arbitrariy-precision numbers these operations become more expensive with the size of the number.

The best currently known algorithm runs in O((log n)^6)


问:
What is the difference between WCF service and a simple Web service in developing using .NET Framework?
My questions are:

What is the difference between WCF service and a simple Web service in .NET Framework?

What a WCF Service can do which a .NET Web service cant? In other words, what are the limitation of .NET Web services which were overcome in WCF services?

I understand that WCF are REST based and .NET web services are SOAP based. But I need to know more than that. How a developer will make a design decision whether to developer a Web service or a WCF service?

答:
both webservices and wcf services serve the same purpose: they allow you to call a service-function on an other remote machine in a similar way you would call a local function.

A soap-webservice does this using http(s)-internettransportprotocol and formatting the message to the remote machine and the answer from the remote machine in the xml-soap-format.

this is not the only way to do remote-procedure-calls.

In the java world there is rmi (remote method invocation), in dotnet there is "dot net remoting"

wcf is an abstraction that alow remote-procedure-calls with several different formats among these are:

soap-webservice

rest-webservice

dot net remoting

you write the wcf-service or client code once and by configurationfile you decide which remoting mechanism will be used.

A simple dotnet soap-webservice is much easier to write and it requires a microsoft internet information server as a host.

A WCF-Service (or WCF-Client) is more complicated to understand/learn but much more flexible if you want to change the remote-provider. A WCF can become a selfhosted SOAP-Webservice so you do not need a msie.


问:
Naming the project containing only interfaces
I've extracted interfaces from my repository classes, like ICustomerRepository, IProductRepository and so on. The project which contains the repositories is named X.DataAccessLayer. Should I call the project with the interfaces X.DataAccessLayerInterfaces, or what is better?

And I definitely have to keep the interfaces in a separate project (I have 2 projects with implementations of these interfaces).

答: I would go with x.DataAccess.Interface and have your implementations as x.DataAccess.Oracle, x.DataAccess.EF or whatever.</p>


问:
Why are the version / build numbers different for Mylyn?
At projects.eclipse.org Mylyn Build 1.1.0 is slated for June 2013.
At www.eclipse.org/mylyn The "news" says Mylyn 3.8.3 was released on March 1st.

Why is there little or no correlation between the two?

答:
Mylyn Builds is just one of the components of Mylyn, it's description reads:

Integration of continuous integration and build systems and seamless
  access to software build and assembly technologies. Mylyn users will
  be able to access continuous integration processes, control build
  execution and associate build results with tasks and context.

Version 3.8.3 refers to Mylyn in general, while version 1.1.0 refers to Builds component.


问:
How to be robust against webservice downtime caused by third parties
I'm using iPage as my cloud based server provider.  I haven't had any problems with them yet.  They hold the scripts for my RESTful services for the mobile app I'm developing.  My problem however is that tonight the service went down.  I got a "This is a 500" error.

I'm wondering how do I build redundancy into my RESTful services to prevent this stuff from happening.  They say it'll be 2 hours at least until they can solve this problem.  If my app is live I can't wait 2 hours.  My users will get annoyed.  I know this happens anyway but how can I build redundancies to prevent it.

答:
A traditional trade-off in outsourcing any part of the business to a supplier, not just cloud computing: you get to give up working on the bits that are "plumbing" in what you offer, and focus on the parts where you think you can add most value. On the other hand, you give up control of the plumbing to another company, which introduces its own risks.

Your options are:

accept that outages like this might happen.

to have some Service Level Agreement with your supplier so that if they can't satisfy your availability requirements you can penalise them. This doesn't stop your customers getting angry, but provides some financial restitution should your service become unavailable.

use a different supplier with a better ability to suit your needs.

handle the server provision yourself. That has some costs in terms of hardware, bandwidth, power, cooling, administration time and so on, but puts you in control of what you say is a key part of your work.

outsource the backend to multiple suppliers. You could host a load-balancer, so that requests go to servers from different companies. Should one backend go down, you can configure the load-balancer not to point to it. However, notice that this just moves the problem up the chain: your load-balancer is now a single point of failure. How do you ensure that box doesn't go offline for two hours? Also, this solution introduces new problems: do the backends need to be in sync? How is that managed? How does that synchronisation recover from an outage? Can you afford to pay multiple providers? And so on.


答:
I can think of to types of redundance:

Have a second fallback provider that hosts a copy of your REST service and a mirror of your data and let your app call the fallback if the main system is down.

have a local file copy of your last rest-service-calls-results in case that the server is offline.

both solutions can be costly. The alternative is to accept the downtime and tell your appusers

```<code>"Sorry, the Servers is down for maintanance reasons. Please try again later"
</code>```

Title: How to be robust against webservice downtime caused by third parties

Body:
I'm using iPage as my cloud based server provider.  I haven't had any problems with them yet.  They hold the scripts for my RESTful services for the mobile app I'm developing.  My problem however is that tonight the service went down.  I got a "This is a 500" error.

I'm wondering how do I build redundancy into my RESTful services to prevent this stuff from happening.  They say it'll be 2 hours at least until they can solve this problem.  If my app is live I can't wait 2 hours.  My users will get annoyed.  I know this happens anyway but how can I build redundancies to prevent it.

Body:
I can think of to types of redundance:

Have a second fallback provider that hosts a copy of your REST service and a mirror of your data and let your app call the fallback if the main system is down.

have a local file copy of your last rest-service-calls-results in case that the server is offline.

both solutions can be costly. The alternative is to accept the downtime and tell your appusers

"Sorry, the Servers is down for maintanance reasons. Please try again later"


答:
Despite that many developers prefer the term "integrationtests" instead of "unittests" when external systems like databases are involved
automated tests with databases are often painfull and fragile:

From Unit Testing with an In-Memory Database for a Spring/Hibernate Project

```<code>Testing DB code is often painful with any significant number of people. Often you
either need every developer to have their own database, with it's own uniquely
inconsistent data and ways of failing, or to use a shared database in which case
people often manage to produce tests that don't work if more than one person runs
the tests concurrently. Also testing on a "real" DB is slow and subject to failure
for reasons not related to your code.
</code>```

With fragile i mean "does the test fail because there is a logical error in the code or is it because someone deleted a datarow that is required by the test".

In order for database related tests to work you need to have a predefined set of databasecontent wich must be maintained. We have projects where there is a automated-testing-ony database where the developpers are not allowed to modify any data.

The other alternative is that the automated test generates the required test-data itself and works with an in-memory database.

Body:
Despite that many developers prefer the term "integrationtests" instead of "unittests" when external systems like databases are involved
automated tests with databases are often painfull and fragile:

From Unit Testing with an In-Memory Database for a Spring/Hibernate Project

Testing DB code is often painful with any significant number of people. Often you
either need every developer to have their own database, with it's own uniquely
inconsistent data and ways of failing, or to use a shared database in which case
people often manage to produce tests that don't work if more than one person runs
the tests concurrently. Also testing on a "real" DB is slow and subject to failure
for reasons not related to your code.

With fragile i mean "does the test fail because there is a logical error in the code or is it because someone deleted a datarow that is required by the test".

In order for database related tests to work you need to have a predefined set of databasecontent wich must be maintained. We have projects where there is a automated-testing-ony database where the developpers are not allowed to modify any data.

The other alternative is that the automated test generates the required test-data itself and works with an in-memory database.


问:
How To Become More Comfortable with the Technical Terms
I have been working freelance for a few years, and before that I worked as an entry-level coder for a non-technical company. I "understand" how delegates, and MVC, and how to make an app and make it work, but I have done a few interviews recently and they are throwing questions at me that I don't know the answers to. These are questions that I think I should know the answers to, but I basically haven't ever had to use the technical language. Needless to say I feel very stupid when this happens but I don't know how to prepare / remedy this problem without going back to Comp Sci 101. It's like I can do the work, but I don't know what they're talking about.

Any suggestions would be much appreciated.

答:
Read more Stack Overflow.

This site is jam packed with tech jargon. You may be able to get some meanings just from the context; if you're not sure, use the tag wiki, Google, and Wikipedia to help. There are lots of ways to expose yourself to new terminology on SO, including:

basic participation: just reading questions and answers

tags: the tags section is a rich source of terms and definitions

review: reviewing questions and answers can help you get outside your comfort zone


问:
Find the peak of each islands in sparse matrix
I have a sparse matrix that contains several islands of unknown size. I would like to find the highest peak of each islands. Consider this matrix as an example:

```<code>0 0 1 0 0 0 0
0 0 1 2 1 0 0
0 0 0 3 2 1 0
0 1 0 0 0 0 0
0 2 3 4 0 1 0
0 0 1 1 0 1 0
0 0 0 0 0 1 0
</code>```

In this case I would like to get the position of 3 at (3, 2), the position of 4 at  (3, 4) and the position of 1 at (5, 4), (5, 5) or (5, 6). Note: I consider 4-connected neighbours.

Until now I came up with the solution that scans each pixel and if it is not zero it starts a flood fill from that pixel. The flood fill paints the pixels to zero keeping track the maximum value visited. This algorithm works well but I was wondering if there are any faster solution?

In my target platform (iOS) I have access to different vector processing frameworks like BLAS, LAPACK, vDSP that provide some functions for fast finding the maximum value in a vector (or matrix). Maybe one could implement a faster solution with the help of these functions?

答:
If I understand correctly, it would seem that you're doing it in the most efficient way.  Let me try to summarize your algorithm:

```<code>Main:
For each pixel in image:
  If pixel is non-zero:
    Call flood subroutine with pixel.
  End
End

Flood subroutine:
Acquire all neighboring pixels of passed pixel of the same height.
Peak = true
For each pixel
  If pixel has neighboring pixel with higher height
    Peak = false
    Call flood subroutine with pixel with higher height
  End
End
If Not Peak
  For each pixel
    Set pixel height to 0
  End
Else
  Add peak to list
End
</code>```

This means that although technically you're passing every pixel in the image to perform this flooding subroutine, if a lot of the pixels share the same height, you will later hit a lot of 0 height pixels that were set by the subroutine.

You could probably even optimize this a bit to both select all pixels of the same height as well as determine if there are neighboring pixels with higher height in the same algorithm to avoid having to perform that check afterwards.

The only problem with this algorithm is that it may be rather memory heavy, since it uses recursion to hold the pixels with the same color.  You could probably improve on this a bit by selecting the neighboring pixels with higher height, setting currently selected pixels to 0 if found, then freeing the resources prior to calling the flood subroutine for each pixel with higher height.

I hope that helps.

Body:
If I understand correctly, it would seem that you're doing it in the most efficient way.  Let me try to summarize your algorithm:

Main:
For each pixel in image:
  If pixel is non-zero:
    Call flood subroutine with pixel.
  End
End

Flood subroutine:
Acquire all neighboring pixels of passed pixel of the same height.
Peak = true
For each pixel
  If pixel has neighboring pixel with higher height
    Peak = false
    Call flood subroutine with pixel with higher height
  End
End
If Not Peak
  For each pixel
    Set pixel height to 0
  End
Else
  Add peak to list
End

This means that although technically you're passing every pixel in the image to perform this flooding subroutine, if a lot of the pixels share the same height, you will later hit a lot of 0 height pixels that were set by the subroutine.

You could probably even optimize this a bit to both select all pixels of the same height as well as determine if there are neighboring pixels with higher height in the same algorithm to avoid having to perform that check afterwards.

The only problem with this algorithm is that it may be rather memory heavy, since it uses recursion to hold the pixels with the same color.  You could probably improve on this a bit by selecting the neighboring pixels with higher height, setting currently selected pixels to 0 if found, then freeing the resources prior to calling the flood subroutine for each pixel with higher height.

I hope that helps.


问:
The best approach to building a mobile service that's also available when the connection drops?
Hopefully this question will be a good suit for P.SE since it is a whiteboard-level 'how can this be done' conceptual question.

I'm trying to build a product that needs to be available to someone on the move with a mobile device when their connection may be quite poor (due to travelling between cities where 3G coverage is stronger).

For simplicity, let's say the application is an address book.

The user must be able to add/remove/edit all contacts in the address regardless of connection state, then those changes iterated to a central server DB whenever the connection next becomes available (and any changes made on the server since the connection dropped also downloaded).

I was originally building the application with PHP/Symfony working with static pages but this new 'mobile' requirement has made me re-think my front-end technology.

I'm now looking at using EmberJS for my frontend (download all the necessary frontend templates with the initial request, then only update the dynamic parts seems like it would suit my application better than serving an entire static page (and resources) for every request).

I've been implementing Ember-Data with the standard REST Adapter which is working great with my already-existent Symfony2 API, so I've greatly reduced the amount of data being sent/received and the responsive 'feel' of the app but still need to tackle my 'no-connection-available' scenario.

Instinctively, I'm drawn to HTML5's LocalStorage functionality but can see synchronizing data between the localstorage and central DB server being a gigantic headache.

Let's say I add "Bob Smith" to the address book from my mobile when the connection is up. The connection drops. I change the name to "Bob Jones" and then change the name to "Fred Smith" using a desktop with a stable connection. When the mobile re-connects, which update takes precedence?

I saw this question regarding using multiple data adapters (REST and LocalStorage) with Ember and it looks like I'm in for a world of hurt. Should I just build a nice-responsive version of the app/service with Ember/REST Adapter, then roll native mobile apps for the on-the-move version? Will handling data persistence be easier to handle as a native app?

答:
The "no connection" requirement makes me think that a web-based solution is not the best fit here. You might get it to work if the connection was lost after the initial page is shown, but what if the user turned the device on in an area with no coverage.

The best solution, in my opinion, would be a native app that stores the data locally and tries to synchronize periodically with the central database. If during such a synchronization a conflict is detected, the app should ask the user to resolve the conflict.

It might also be worthwhile to investigate existing native apps that are similar to what you are building and see in how far they already support synchronization with an external server. If you are lucky, you would only need to implement the server side of a standard synchronization protocol and have a perfectly working solution.


问:
Heap overflow vs stack overflow
So as a general rule to avoid a stack overflow, big objects should be allocated to the heap (correct me if I am wrong). But, since the heap and the stack expand towards each other, wouldn't this cause heap overflow or alternatively limit the space for the stack and higher the chances of stack overflow?  </p>

答:
Obviously, storing X byte of data is going to reduce the amount of free memory by at least X bytes, no matter where you put it.

big objects should be allocated to the heap

I don't think that this is the main distinction to draw.

If you need data to be accessible outside of the current stack frame (for example as a global variable, or to pass it to another thread), you cannot put it into the stack.

The stack shrinks when a subroutine returns, so all data stored in its stack frame is lost.

Data on the heap stays "alive" until you de-allocate it.

Beyond that, because stack memory is generally much more limited than heap memory in "real life" (not just two unlimited sections growing towards each other like you alluded to in your question), you may want to put anything large on the heap, even if you could put it on the stack. For example, Java places everything in the heap. The downside is more complex memory management.

OwnerDisplayName: Rayhunter

Title: Heap overflow vs stack overflow

OwnerDisplayName: Thilo


问:
Scrum: Short VS long sprint
We were trying to figure out the optimal sprint length for our project. After working on a 3-weeks basis we thought that cutting the sprint to 2-weeks would provide better velocity.

The advantages were clear - shorter feedback loop, small stories (with user value) and so on.
On the other hand, there are a lot of disadvantages such as ceremonies (planning, retrospective) and so on in which we don't produce and now happen more often.

I was wondering how, for a new team, can we decide on optimal sprint length?

答:
Up to you. Try both, see what works. Use that.

The best agile 'sprint' I ever used was 6 weeks. We got so much done - but we only needed to deliver to the client on that schedule. We didn't use tasks, preferring working to the user-story style of working.

Title: Scrum: Short VS long sprint


问:
Why don't I see many unit test projects that bring up and tear down a DB? (ASP.NET MVC)
I see all the examples that demonstrate unit testing code and mocking the calls to the DB since you are not suppose to touch the DB. But it seems to me having a set up tasks that uses the actually schema, loads the lookup tables and then populates it with data using the methods to be tested... This way it is more real world testing and all the stored procedures are tested as well.. But I never have seen any examples like this...  Is there some reason I do not understand why using this technique is not as useful as it seems ? </p>

<p>EDIT1: Sorry.. I shouldn't have called it unit test.. yes. I will have unit tests as well that are for testing code.. But beyond that it seems like a good idea to bring up and tear down and DB and have code that modifies that DB and does assertions.. But I don't want this to be UI testing.. I just want to perform a lot of CRUD functions and a lot of assertions .. :My question is #1 does this make sense.. #2 how do I automate this all within visual studio ? How do I tell VS 2012 to run a SQL script before running the tests? is there some special API for this ? </p>

答:
MSTest?

The other answers say why you need to test in isolation, but you then test the DB stored procedures as well - call them with a certain input to a table filled with pre-defined data, and see what result is returned. Each test sets up data, calls the test code, then rollsback so the DB is back to its original state.

This is easy, use it in conjunction with your client-side tests. (its just a shame few people know enough to realise that unit testing applies to SQL as well as C# code, if only they would split the sql code into stored procedures they'd find DB testing was as easy. Few people write proper DB unit tests, which is surprising given how important the DB aspect is to most programs).

Now there is a separate issue with integration testing, and for that you'll need to set up a DB with sample data and then call your client (using Selenium or similar) so that you exercise the whole thing end-to-end. This isn't unit testing per-se. It is still very useful, and you really should be doing this as well - unit tests only verify the tiny detail of little bits of code and ignore the 'bigger picture' of how they work together. Integration tests will verify that your entire app works when all those little units are plugged together.


问:
How much redundancy/robustness should complex software implement?
The focus of this question: Some software performs "extra work" in order to increase the chance of a "eventually successful/satisfactory" outcome, despite one or more internal errors in the software, which requires a longer execution time when those errors happen. All these happen without the user's knowledge if the outcome was successful.

Definition of complex software:

Contains code written by (contributed from) more than 10 developers over its lifetime, and not written in the same time frame

Depends on more than 10 external libraries, each with caveats

A typical software task (for generating a result wanted by the user) requires 10 or more input parameters, where most of them have default values but are configurable if the user needs control.

Most importantly, software that has the appropriate complexity relative to the task being performed, i.e. not unnecessarily complicated.

Edited: What is complex? Please see There is a big difference between Complex and Complicated. (direct link)

Definition of Redundancy/Robustness within this question:
(Added Robustness based on comments)

If a software task failed when the current set of parameters was used, try different parameters.

Obviously, there must be inside knowledge that those "different" parameters use a different code path, possibly resulting in a different (hopefully better) outcome.

Sometimes these different code path are chosen based on observations of the external libraries.

At the end, if the actual task performed is slightly different from the user's specification, the user will receive a report detailing the discrepancy.

Finally, like the 10-plus configurable parameters, the redundancy and reporting are also configurable.

Example of such software:

Database Migration

Business database

Source control database, etc.

Batch converting between a Word document and an OpenOffice document, PowerPoint and OpenOffice Draw, etc.

Automatic translation of an entire website

Automatic analysis of software package, such as Doxygen, but where the analysis needs to be more dependable (i.e. not just a documentation tool)

Network communication, where packets may be lost and a number of retries are expected

This question was originally inspired from How do you deal with intentionally bad code?
 but is now focused on just one of the causes of software bloat. This question does not address any other causes of software bloat, such as addition of new features.

Possibly related:

How to deal with complex codes in (huge) projects

How do people manage to write and maintain extremely complex and hard to read code?

答:
It's a requirements thing.

Is there a requirement for robustness ?

"When the communications link fails, erroneous packets are discarded"
"When the link resumes operation, no transaction is processed twice"

there should be use cases for error recovery ( otherwise how do you know how it will happen ?)

Leaving it to the programmers to invent robustness as they go ( if required) results in "magical" systems.

All magical systems become crappy magic over time.
Error correction in the background hides the occurrence of faults, so that faults will not be corrected, so the system will eventually degrade to a state of greater entropy; and run like crap, as it corrects for errors all the time. You must have a limit to stop the system entering a permanently degraded state.


答:
It depends on what you describe a "new team".

Indeed, a teams velocity depends on a lot of parameters among many (ie: juniors?, seniors?, newcomers?, tensions between team members?, etc.).

Therefore the "ideal" sprint length is also bound to these parameters.

Anyway, there's no out of the box solution for that, the only way is to test it with the team itself, and also take in account the best average fit for all the team members.

Title: Scrum: Short VS long sprint

Body:
We were trying to figure out the optimal sprint length for our project. After working on a 3-weeks basis we thought that cutting the sprint to 2-weeks would provide better velocity.

The advantages were clear - shorter feedback loop, small stories (with user value) and so on.
On the other hand, there are a lot of disadvantages such as ceremonies (planning, retrospective) and so on in which we don't produce and now happen more often.

I was wondering how, for a new team, can we decide on optimal sprint length?


问:
Is Entity Framework only for Asp .NET / Asp. NET MVC?
I never coded on VS and I'm a junior programmer in C# and I would like to know if the entity framework is available only for ASP .NET applications ?</p>

答:
Not only. Entity Framework is an ORM for .NET applications.

Any time you want to bridge between an application and a database, you can use an ORM, including EF.

It is useful for WebForms, WinForms, WPF and other types of applications (using any .NET language).


答: No. It is suitable for any .NET application. ASP.NET WebForms and MVC websites, WinForms and WPF desktop applications, Windows services, console apps - anything. If you need to connect to a database, Entity Framework is the main Microsoft-endorsed way to do it.</p>

Title: Is Entity Framework only for Asp .NET / Asp. NET MVC?

Body: I never coded on VS and I'm a junior programmer in C# and I would like to know if the entity framework is available only for ASP .NET applications ?</p>


问:
Models structure in PHP/MVC
I have some classes that are composed with ORM generated Models.

example1:
For example the Report.php (Model) is using a Document.php Model generated with ORM. Based on the document object a report is created.

I would like to know some name suggestions for the Report.php folder path.
It clearly belongs to the /Model folder but in what subfolder?

example2:
The CustomTagFilter.php will remove some html tags from a html string.

I wish to find a clear path name for this kind of Models. Any suggestions ?

```<code>/Models/[SUGGESTION]
</code>```

答:
There are no rules on how you should organise your model code. Mostly not because it all depends on your application. At best, we can give you some food for thought.

In a small application (up to a few dozen model classes), I might not even bother with organising them in separate folders.

If a more structured organisation of the model classes is deemed beneficial, I would first group the classes according to functionality, so all the ORM related classes together, the classes dealing with functionality A together, etc. If still more organisation is needed, add another layer using whatever division seems right at that point.

For the posted examples, the division would probably come to

Models/

ORM/

Document.php

Filters/

CustomTagFilter.php

Report.php

The only thing to avoid is to use catch-all categories. If you can't think of a good category name, don't put it in a sub-category at all (like I did with Report.php).

Title: Models structure in PHP/MVC


答:
Entity Framework (EF) is an Object Relational Mapper (ORM) for .NET Framework. You can use it in any application type. It has no dependency on your application User Interface (UI) type. It actually populates objects with data from your database and if you make any changes in your object then it saves that object data to database. </p>

<p>After getting the data in object form you can use that object in any type of application in .NET Framework like ASP.NET (WebForm and MVC), Windows Forms Application, WPF, Class library, Console Application etc.  </p>

Body:
Entity Framework (EF) is an Object Relational Mapper (ORM) for .NET Framework. You can use it in any application type. It has no dependency on your application User Interface (UI) type. It actually populates objects with data from your database and if you make any changes in your object then it saves that object data to database.

After getting the data in object form you can use that object in any type of application in .NET Framework like ASP.NET (WebForm and MVC), Windows Forms Application, WPF, Class library, Console Application etc.


答: Database testing is not done in Unit test but in Integrated test.</p>


答:
I think you're looking at it a bit backwards.  Velocity is an after-effect of the work your team is doing.  It is not a causal factor - ie. it's something you measure and it's not something you can directly tweak.

This explanation of velocity has a relevant tidbit to your question.

The simplest way to define velocity is: the number or user stories a team/project can do in one sprint

And by that definition, a longer sprint means more time for development per sprint and therefore a greater velocity number.

Relative velocity between a 2 week or a 3 week sprint is a slightly different question.  Overhead from project ceremonies can impact how much you can get done because there is less overall time available.  Consider this calculation as a way to identify available development hours in a sprint.

DevHoursAvailable = ((HoursInDay * DaysInSprint) - CeremonyOverhead) * AvailabilityFactor * NumberOfDevs

CeremonyOverhead is generally fixed.  Decrease your DaysInSprint and you can see how you'll have less available time for development during that sprint.  Using a simple example of 1 dev, here are the numbers for a few sprint lengths.

1 week:

  ((8 * 5) - 4) *.8 = 28.8 hours or 5.76 hours per day.

  2 weeks:

  ((8 * 10) - 4) *.8 = 60.8 hours or 6.08 hours per day.

  3 weeks:

  ((8 * 15) - 4) *.8 = 92.8 hours or 6.18 hours per day.

The "obvious" answer is that longer sprints are better.  The problem with the obvious answer is that it ignores the beneficial impact of feedback loops.  Temper thoughts regarding that calculation with an overall perspective on what Agile is supposed to bring to the development process.

I suspect your core issue is that your user stories are not as defined as they could be.  That lack of understanding what's required is the real impediment to getting work accomplished.

Title: Scrum: Short VS long sprint


问:
Accepted best practices for setup.py of a forked project

Context:

I was looking to see if there was a tool to do something (in my case I was looking for a proxy that would allow for http log inspection from a python test framework).

There turned out to be a tool that would require only minor adjustment, and it seemed to be reasonably stable/mature, with no updates in the past 5 months (pymiproxy), so I forked the project (to here) and have got it working as I need. The goal behind the original project is simplicity, so I doubt a pull request would be accepted, especially since one of the files involved is only useful to my current employer.

Finally I thought I should update the setup.py file, but I'm not sure - I have done a 'useful' amount of work on my fork, and while I have left the original files in tact, subclassing in my own modules, there is now significant additional functionality.

I don't know that I feel comfortable claiming to be the 'author' of this module as it would be installed by python, but as the fork project author, I also don't feel comfortable leaving support emails directed to the original project's author.

Question:

What is the general accepted best practice for forked projects? Should the project be renamed to indicate that it is of a different purpose? The original project is not available through pip or else the structure of my project would allow that instead of forking, I only wrap the original as a dependancy. Should I in fact roll back my changes, put these in a new project, and get the two both listed in pypl, or is doing this on behalf of the original author going too far?

Notes:

Headings added to aid speed-reading. I'm looking for accepted best practices, so please no opinions without sources to back them up, be it an authoritative blog post, or examples of other projects which have done the same.

答:
Well, in practice when I fork a project and can't get – or don't want – my changes to be integrated in upstream, I rename the fork, in the README, I cite the original author  but claim to be maintainer of that code source and link the source to my repository and in setup.py update the authors string to add my name after a comma:

```<code>name='renamedproject'
author='origauthor, me',
url='http://myfavoriterepository.com/me/renamedproject'
</code>```

I have no sources to back me up, but that's the result of long discussions I had with other pythonista friends a while ago while drinking dark beers…

OwnerDisplayName: BiggAl

Body:
Well, in practice when I fork a project and can't get – or don't want – my changes to be integrated in upstream, I rename the fork, in the README, I cite the original author  but claim to be maintainer of that code source and link the source to my repository and in setup.py update the authors string to add my name after a comma:

name='renamedproject'
author='origauthor, me',
url='http://myfavoriterepository.com/me/renamedproject'

I have no sources to back me up, but that's the result of long discussions I had with other pythonista friends a while ago while drinking dark beers…

OwnerDisplayName: zmo


问:
Time consuming Unit test for support for 100,000 records: Am I doing it right?
I am working on adding test coverage for an application that previously didn't have any. One additional requirement that emerged is that one of the background processes should be able to process 100,000 rows at a time.

I've written a unit test that ensures that the background process is able to work with the 100,000 entities without crashing the interpretter (PHP) on a 4.0MB memory limit. But each test run takes close to 4 minutes to finish. All other tests take just 10 seconds to run.

Can this be approached differently than a unit test?

答:
I'm not sure how you have your test cases structured, but that sounds more like a system test or acceptance test than a unit test to me.

In my opinion, unit tests should be concerned with testing that functionality works and exercising various code branches. An example of a unit test would be processing a single record, and you might have a few variations of this record to force your testing to go down certain paths and confirm your results are what is expected. Your unit tests can be used for regression and smoke testing as well - things that you run on a regular basis (nightly, after a build, locally in a development environment before a code review, and so on).

Your system level and acceptance tests aren't run as frequently - running automated system tests nightly would be as frequent as I'd expect. These would be more intensive tests that would focus on system performance, memory consumption, timing, and behavior with other systems. Having it automated, much like your unit tests, are a good thing, but I wouldn't want to bog down your unit test suite or regression test suite with such long-running activities.


问:
What aspects of "maintainability" can influence choice of IS implementation technology?
Background: I'm an apprentice and am handling the project of developing a particular IS-System. Currently I'm only managing the requirements analysis and the information-processes design, but as a Software Developer, I would also like to implement the concept as an actual Web-Portal.
When it comes to choice of technology, I personally would like to build my front-end based on JavaScript Frameworks(jQuery, Bootstrap, DataTables.Net, ...) which offer high front-end implementation flexibility and nice out-of-box modern design, and wire these to .NET MVC in the code-behind. The people around me, who haven't written a line of code in what seems like decades, all fret about difficulty to maintain such a system, in comparison to using .NET Controls and sticking to the MS Web-Site development Package. So whenever I try to bring up, that I could build a nice-looking, user-friendly, modern portal, once we're done with the first concept-phase, I just get concerned looks and a mumble about "maintainability" and "we'd prefer trying to use Sharepoint Analysis Services connected to our DB".

Question: what aspects of "maintainability" can influence choice of System implementation technology?

Goal: I would like to sit down and "prove" that my approach is just as maintainable as what they are suggesting, and if it isn't I would like to identify ways to improve it.

Questions I found interesting:

JavaScript codes complexity and maintainability

How does one meaningfully measure maintainability?

How to have a maintainable and manageable Javascript code base

What characteristics or features make code maintainable? (!)

What hurts maintainability? (!)

Some abstract aspects of maintainability:

readability

coupling

consistency

the reasoning behind code is documented

答:
In general, maintainability indicates how quickly a change can be made to the existing code and how easy it can be made without a risk of introducing bugs or breaking existing code.  The questions you've linked to (here and here) cover these general aspects of maintainability very well.

I'm making some assumptions here, but it sounds like your colleagues aren't interested in these general aspects of maintainability.  They're interested in the question of "How can we even find someone to make a change to the existing code?"  SharePoint can (I think) be customized by someone with no particular programming experience; ASP.NET WebForms starts out with a pretty easy learning curve (since it does its best to abstract away all of the details that web development introduces), and there are lots of people who are at least minimally proficient in it.

ASP.NET MVC and jQuery have more of a learning curve.  You need to be familiar with two different programming languages (for example, C# and JavaScript).  You need to know HTML and CSS.  You're using a collection of several libraries that you assemble yourself (jQuery and DataTables.Net in your example) instead of having the vendor give you a nice consistent framework.

An MVC + JavaScript web site has a lot of advantages and can be more maintainable for a skilled developer.  But for an organization that doesn't specialize in software development and doesn't want to have to develop and retain that talent, it starts to look a lot less maintainable, since it becomes much less certain that they'll even have someone who can make changes.


答:
Stack overflow is what happens when an architecture with a bounded stack tries to increment its stack pointer beyond its maximum possible value.  Sometimes this is a hard limit, such as on the 6502, which had a 256-byte stack at a fixed location in memory and a one-byte stack pointer.  Pushing a 257th byte onto the stack would cause the stack pointer to wrap around and clobber the bottom of the stack.  In modern systems, it's usually a soft limit that can be reset before starting the program or while the program is running.  Step over that line with a POSIX-y system and you get a segmentation fault.  It's also theoretically possible to have a stack that continues to grow downward as long as memory is available to hold it.

The phenomenon you're referring to is called a stack-heap collision, where one grows so much that it overlaps the other.  You saw these a lot more frequently when address spaces (and memory) were smaller; now it's a lot less common because we don't run out of either nearly as often.

My advice would be to base your decisions on how you're going to dispose of the memory.  If it's something that can disappear when you go out of scope, put it on the stack, because it will save you the headache of managing it.  If it needs to stay around past the life of the current scope put it on the heap.  Don't take this as a hard-and-fast rule, either, because there are situations where it doesn't apply.  Use your judgement: if you're going to allocate something you know will run you out of stack, use the heap and make sure you clean up after yourself.  Large allocations tend to be re-used, which is why they get put on the heap more often.

The bottom line is that if you're so short on memory that stack and heap will collide, you have bigger problems than where to put what you allocate.

Title: Heap overflow vs stack overflow

Body: So as a general rule to avoid a stack overflow, big objects should be allocated to the heap (correct me if I am wrong). But, since the heap and the stack expand towards each other, wouldn't this cause heap overflow or alternatively limit the space for the stack and higher the chances of stack overflow?  </p>


问:
Data structure for accessing units of measure
TL;DR - I'm trying to design an optimal data structure to define units within a unit of measure.

A Unit of measure is essentially a value (or quantity) associated with a unit.  SI Units have seven bases or dimensions.  Namely: length, mass, time, electric current, temperature, amount of substance (moles), and luminous intensity.

This would be straightforward enough, but there are a number of derived units as well as rates that we frequently use.  An example combined unit would be the Newton: kg * m / s^2 and an example rate would be tons / hr.

We have an application that relies heavily upon implied units.  We'll embed the units within the variable or column name.  But this creates problems when we need to specify a unit of measure with different units.  Yes, we can convert the values at input and display but this generates a lot of overhead code that we'd like to encapsulate within its own class.

There are a number of solutions out on codeplex and other collaborative environments.  The licensing for the projects is agreeable but the project itself usually ends up being too lightweight or too heavy.  We're chasing our own unicorn of "just right."

Ideally, I could define a new unit of measure using something like this:

UOM myUom1 = new UOM(10, volts);

  UOM myUom2 = new UOM(43.2, Newtons);

Of course, we use a mix of Imperial and SI units based upon our clients' needs.

We also need to keep this structure of units synchronized with a future database table so we can provide the same degree of consistency within our data too.

What's the best way of defining the units, derived units, and rates that we need to use to create our unit of measure class?  I could see using one or more enums, but that could be frustrating for other developers.  A single enum would be huge with 200+ entries whereas multiple enums could be confusing based upon SI vs Imperial units and additional breakdown based upon categorization of the unit itself.

Enum examples showing some of my concerns:

myUnits.Volt

  myUnits.Newton

  myUnits.meter

SIUnit.meter

  ImpUnit.foot
  DrvdUnit.Newton

  DrvdUnitSI.Newton

  DrvdUnitImp.FtLbs

Our set of units in use is pretty well defined and it's a finite space.  We do need the ability to expand and add new derived units or rates when we have client demand for them.  The project is in C# although I think the broader design aspects are applicable to multiple languages.

One of the libraries I looked at allows for free-form input of units via string.  Their UOM class then parsed the string and slotted things accordingly.  The challenge with this approach is that it forces the developer to think and remember what the correct string formats are.  And I run the risk of a runtime error / exception if we don't add additional checks within the code to validate the strings being passed in the constructor.

Another library essentially created too many classes that the developer would have to work with.  Along with an equivalent UOM it provided a DerivedUnit and RateUnit and so on.  Essentially, the code was overly complex for the problems we're solving.  That library would essentially allow any:any combinations (which is legitimate in the units world) but we're happy to scope our issue (simplify our code) by not allowing every possible combination.

Other libraries were ridiculously simple and hadn't even considered operator overloading for example.

In addition, I'm not as worried about attempts at incorrect conversions (for example: volts to meters).  Devs are the only ones who will access at this level at this point and we don't necessarily need to protect against those types of mistakes.

答:
Think about what your code is doing, and what it will allow. Having a simple enumeration with all the possible units in it allows me to do something like convert Volts to meters. That's obviously not valid to a human, but the software will gladly try.

I did something vaguely similar to this once, and my implementation had abstract base classes (length, weight, etc.) that all implemented IUnitOfMeasure. Each abstract bases class defined  a default type (class Length had a default implementation of class Meter) that it would use for all conversion work. Hence IUnitOfMeasure implemented two different methods, ToDefault(decimal) and FromDefault(decimal).

The actual number I wanted to wrap was a generic type accepting IUnitOfMeasure as its generic argument. Saying something like Measurement<Meter>(2.0) gives you automatic type safety. Implementing the proper implicit conversions and math methods on these classes allows you to do things like Measurement<Meter>(2.0) * Measurement<Inch>(12) and return a result in the default type (Meter). I never worked out derived units like Newtons; I simply left them as Kilogram * Meter / Second / Second.