答:
I would not worry too much about not using specific STL librarys like std::string or std::iostream or std::vector. The QT-equivalents come in a different flavour but they are not so far off to make any problem.

The more idiomatic difference in my opinion seems to be the programming style heavy on using new for allocation. While for a QT program this might be fine for the Gui part, the virtue of C++ and RAII is, that you can actually keep lots of data on the stack instead of the heap. When switching to writing non-GUI code you should recall that.

Title: QT-C++ vs Generic C++ and STL

Body:
Been brushing up on my C++ lately, on Ubuntu QQ. I love the Qt framework  for everything, especially building GUI's. I became quite familiar with it when using PyQt over the last few years.

When using PyQt, I had some issues that are now more pronounced when using C++ with Qt: Qt has many extensions to C++ that are Qt specific - QString being just one common example, not to mention automated garbage collection. It is possible to write Qt applications using C++ without knowing much at all about C++ and the STL.

I may have to hit the job market again soon and I'd like to be able to consider C++ positions - but I'm afraid binding myself too much to Qt will limit my abilities to work with generic C++, which were once quite formidable but are now long dormant and rusty.

Should I avoid Qt? Would I be better off using WxWidgets or GTK++ for building GUI's?

What's the best GUI framework to use that allows/requires the most use of generic C++ and the STL? How do I make myself most marketable as a C++ programmer when it comes to GUI frameworks, etc?


问:
Does any know of a Algorithm that allows for a figure like this image?
Does anyone know how to create an algorithm capable of making the figure just like in the picture, when given a set of specific points (3D array)

答:
Coming here after the battle, but since there are no accepted answer yet and seeing that @Luke refuses to get the rep he deserves, here is a quick summary of the link he provided.

So the full algorithm is available here:

http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html

The idea is to bootstrap your mesh with a simple method which gives you a sphere with 20 faces, and then refine it until you are satisfied.

Bootstrapping the shape

You start with an icosahedron. As the wikipedia article says, you can obtain the vertices by drawing three identical and orthogonal rectangle. You have 3 rectangles with 4 corner each --> 12 vertices.

Wikipedia illustration:

For example, the Z plan points are (a, b are the rectangle lengths):

(+a, +b, 0)

(-a, +b, 0)

(+a, -b, 0)

(-a, -b, 0)

Now you still have to find the 20 faces. This is left as an exercise to the reader :p

Refining the shape

Now that you have a basic sphere, you may want to add polygons. You do so with this simple algorithm:

```<code>for each iteration:
    # each iteration multiplies by 4 the number of faces
    for each edge at the current iteration:
        split the edge in two
        replace the middle point on the sphere
</code>```

To find the middle point, we suppose that we wish to create  the unit sphere (center (0, 0, 0), radius 1).

```<code>middlePoint(p1, p2):
    middle = Point((p1.X + p2.X / 2), # same for y, z)
    radius = sqrt(middle.X^2, middle.Y^2, middle.Z^2)
    return Point(middle.X / radius,  # same for y, z)
</code>```

At each iteration, we may have to reconstruct the faces, but it is fairly easy. Each face is divided into four:

ContentLicense: CC BY-SA 3.0

Body:
Coming here after the battle, but since there are no accepted answer yet and seeing that @Luke refuses to get the rep he deserves, here is a quick summary of the link he provided.

So the full algorithm is available here:

http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html

The idea is to bootstrap your mesh with a simple method which gives you a sphere with 20 faces, and then refine it until you are satisfied.

Bootstrapping the shape

You start with an icosahedron. As the wikipedia article says, you can obtain the vertices by drawing three identical and orthogonal rectangle. You have 3 rectangles with 4 corner each --> 12 vertices.

Wikipedia illustration:

For example, the Z plan points are (a, b are the rectangle lengths):

(+a, +b, 0)

(-a, +b, 0)

(+a, -b, 0)

(-a, -b, 0)

Now you still have to find the 20 faces. This is left as an exercise to the reader :p

Refining the shape

Now that you have a basic sphere, you may want to add polygons. You do so with this simple algorithm:

for each iteration:
    # each iteration multiplies by 4 the number of faces
    for each edge at the current iteration:
        split the edge in two
        replace the middle point on the sphere

To find the middle point, we suppose that we wish to create  the unit sphere (center (0, 0, 0), radius 1).

middlePoint(p1, p2):
    middle = Point((p1.X + p2.X / 2), # same for y, z)
    radius = sqrt(middle.X^2, middle.Y^2, middle.Z^2)
    return Point(middle.X / radius,  # same for y, z)

At each iteration, we may have to reconstruct the faces, but it is fairly easy. Each face is divided into four:


问:
QT-C++ vs Generic C++ and STL
Been brushing up on my C++ lately, on Ubuntu QQ. I love the Qt framework  for everything, especially building GUI's. I became quite familiar with it when using PyQt over the last few years.

When using PyQt, I had some issues that are now more pronounced when using C++ with Qt: Qt has many extensions to C++ that are Qt specific - QString being just one common example, not to mention automated garbage collection. It is possible to write Qt applications using C++ without knowing much at all about C++ and the STL.

I may have to hit the job market again soon and I'd like to be able to consider C++ positions - but I'm afraid binding myself too much to Qt will limit my abilities to work with generic C++, which were once quite formidable but are now long dormant and rusty.

Should I avoid Qt? Would I be better off using WxWidgets or GTK++ for building GUI's?

What's the best GUI framework to use that allows/requires the most use of generic C++ and the STL? How do I make myself most marketable as a C++ programmer when it comes to GUI frameworks, etc?

答:
I agree with most of high praise of Qt, but the question was What's the best GUI framework to use that allows/requires the most use of generic C++ and the STL? In this respect Qt is a little schizophrenic: it duplicates STL containers and algorithms with it's own twists. It also provides containers, which are different than STL. Interoperability between Qt and STL is not always smooth sailing. In some cases it takes a few function calls to get from std::string to QString and back.

wxWidgets has an option for STL build, which uses STL containers exclusively - there is no parallel universe with home grown replacements as in case of Qt. It also compiles with a standard C++ compiler without needing non-standard extensions. It is a quality GUI framework worth considering.

You can also have a look a gtkmm, which is a C++ wrapper around GTK+. It is closer to fulfilling your first requirement than Qt.

Title: QT-C++ vs Generic C++ and STL


问:
Exploratory Development vs Incremental Development
In Software Engineering Methodologies... The Evolutionary Development contains Exploratory & Prototyping...
Is Exploratory Development same as Incremental Development... What do you mean by exploratory Development?

The terms are taken from
Software Engineering - Ian Sommerville

答:
Exploratory Development == experimental. New to the world or new to you or your company. means trying something and then maybe having the guts to leave it and go some other way.

Incremental means doing in stages. So you can develop something similiar to what has been done before, but a smaller feature set at a time, test and ship quickly & often, with more involved QA & dev ops. Be agile and have more releases and hopefully happier customers.


问:
How to manage a Closed Source High-Risk Project?
I am currently planning to develop a J2EE website and wish to bring in 1 developer and 1 web designer to assist me. The project is a financial app within a niche market.

I plan to keep the source closed. However, I fear that my would-be employees could easily copy the codebase and use it or sell it to a third party. The app development will take 4-6 months, perhaps more, and I may bring in additional employees after the app goes live.

But how do I keep the source to myself. Are there techniques companies use to guard their source?

I foresee disabling USB drives and DVD writers on my development machines, but uploading data or attaching the code in email would still be possible.

My question is incomplete. But programmers who have been in my situation, please advice. How should I go about this? Building a team, maintaining code-secrecy,etc.

I am looking forward to sign a secrecy contract with the employees if needed too.
(Please add relevant tags)

Update

Thank you for all the answers. I certainly won't be disabling all USB ports and DVD writers now. But I think I should be logging activity(How exactly should I do that?) I am wary of scalpers who would join and then run off with the existing code. I haven't met any, but I have been advised to be wary of them. I would include a secrecy clause, but given this is a startup with almost no funding and in a highly competitive business niche with bigger players in the field, I doubt I would be able to detect or pursue any scalpers.

How do I hire people I trust, when I don't know them personally. Their resume will be helpful but otherwise trust will develop only with time.

But finally even if they do run away with the code, it is service that matters after the sale is made. So I am not really worried for the long term.

答:
The hard truth is that nobody wants your code.
You may think that you develop a solution everybody wants to know how it works. But more often than not you don't.

What would you do if you took over the source code of your competitors? You can't distribute it. You can't copy any parts of it into your project (even if it wasn't so hard to integrate thirdparty code into your codebase). What you can do? You can study it. But often it's harder to read the code than to write it in the first place.

Look at the open source software. It is a closest analogy to a stolen source code. There is a vast amount of unmaintainted code. A large portion has a license that doesn't suit your needs. Others has incompatible programming language or needs porting to your platform. The code which suits your needs will take plenty of time to read.

There are many open source projects with a closed source mentality. I.e. they don't accept patches. Soon enough your version of code will deviate so much that it would be impossible to merge new versions.

You should understand that what's the most valuable is your team who maintains your code, moves it forward. Not the code itself.


问:
Less code or less operation
Sometimes I hesitate between "More code to avoid unnecessary operations" and "less code but with redundant operations". Let me just take an example (Win32 API):

I try to paint some controls manually when the cursor is over it. If the cursor is over this control and it is painted, then it doesn't need to be painted again before the cursor goes out from it.

Of course, I can just paint this control whenever a WM_MOUSEMOVE appears. Or, I can use more variables to record the state of this control and paint it only when the state is changed.

Although it is not a question (in practice) in my example, I still want to have a feeling for which is the better choice, in general. And if this depends on cases, any way to develop a good sense to do the choice?

(I am not focus on "efficient". It is more or less like a question as: If you are an idealist of programming, which one is better in your opinion.)

答:
There is no better choice in general. Code readability and system performance are two valid goals, and if they are at odds, you must know about the strengths of those two forces in your particular situation before deciding. To say, "when readability and performance are at odds, always choose performance (or readibility)" would be a terrible oversimplification that leads to terrible decisions when followed blindly.

To make  good decision, you would consider these forces in the context of your actual requirements. For example:

UI behaviour, particularly something to do with painting the mouse pointer, is rather sensitive to speed. It may not affect the actual throughput of an application much or at all, but the impression of speed is vital for a good user experience: milliseconds of feedback delay can contribute to subconscious dislike of a system. (Consult user experience professionals for more precise figures, but they are shockingly small.) So in this case, performance may actually be comparatively important rather than a "nice to have".

At the same time, graphics rendering code is a rather fundamental part of a large system. You definitely want it to be correct and rock-solid - mis-drawing something in your user interface can leave an even worse impression than feedback lag. This puts a premium on maintainability, and that means readability is also important.

But rendering sprites, icons or whatever your low-level primitives are is (I hope) a relatively small, contained problem. Once you've implemented it, it may not require continuous improvement the way that business rules or interfaces do (how often does a new input modality come long that challenges the established keyboards and mice?), so maybe you can get away with optimizing the hell out off your code and then putting a lid on it. That would mean more opportunity to optimize and less danger of having to unravel your clever tricks again the next time you need to change low-level behavior.

This is not to say that you should optimize for speed, either in this case or in general, just because I named two pro-speed items and one pro-maintenance item. These are just examples of the kind of questions you need to ask to make the right decision depending on the circumstances. Also, you need to quantify the effects you are comparing, e.g. via usability testing and profiling metrics. One big minus can be enough to cancel out the advantages of a whole bunch of small plusses.

Title: Less code or less operation


问:
Entites in Invalid State
I'm looking into developing my entities so that they cannot be in an invalid state.

In particular I'm starting with my Customer entity.  This would have fields like:

Title (enum)

FirstName (string)

LastName (string)

Address (value object with another 6 fields)

MainTelephone (string)

AlternateTelephone (string)

EmailAddress (string)

I've added methods such as ChangeOfAddress() to facilitate the changing of address, which will ensure a valid address is entered as a replacement.

In the UI, I consider most fields (except for AlternateTelephone and EmailAddress) as 'required', encouraging users to complete fields such as Title to make addressing mail shots easier in the future.

For methods like ChangeOfAddress() the concept of 'invalid state' is an easy one, as I can apply validation on the new Address value object, but for the construction of a new Customer object I'm not as sure.

I guess my question is, should the bare minimum for the construction of a Customer entity include all the fields I feel are 'required' from the perspective of the UI?  I can't imagine how creating a Customer with only a FirstName and LastName (without any contact details), would be valid in the business sense I intend to use the Customer object in.  Although in a sense FirstName and LastName are good starting points for a minimum description of a Customer and I guess the Customer wouldn't be 'invalid' it'd just be lacking enough information to be useful to my business needs (which would be, to be able to contact them).

Hope this makes sense, I'd be interested to hear any opinions, as I'm still learning as I go.

答:
Sure, go ahead. Write your constructor so that it requires all fields that are required in the usual, "happy-path" rout to creating a customer. If it works, great! You've completed part of the requirements and enforced the integrity of a key data asset at the same time.

If it doesn't work, you will have learnt something about the system that you didn't know before, i.e. that your assumptions about the flow of data were wrong on an important point. This will almost certainly enable you to create a better model of the domain: revise your assumptions and revise the code to match them, and the system will profit from it.

Note that having had  wrong assumption is in no way shameful or a setback.
The ways that even the most basic assumptions can go wrong are manifold. Maybe a key lead must be entered because it is too valuable to pass up even without having completed the questionnaire. Maybe you need to interoperate with a legacy system that had different optionality rules. Maybe the state of California secedes, so that a previously valid contact becomes invalid even though the data are the same as they were before! My point is: you will have to revise assumptions. If you have cast them into the terms of your language, then the compiler will warn you when that happens. If you haven't, then you may go on for a quite a while following a rationale that no longer makes sense without noticing it. That's why making assumptions explicit is a good thing.

Title: Entites in Invalid State


问:
Structure vs. programming
Is it bad that I often find myself spending more time on program structure than actually writing code inside methods? Is this common?

I feel I spend more time laying the foundation than actually building the house (metaphorically). While I understand that without a good foundation the house will cave in, but does it legitimately need to take half of the project to finalize code structure?

I understand design patterns, and I know where to go if I need help on choosing one, but often I find myself doubting my own choices.

答:
No, it's not common, but yes, it should be common.

Having the correct organization of a large project is way more important than any single method in itself. If your project is organized well, it is comparatively easy to understand part of it. If a small change is necessary in one isolated part, it becomes easy to find the class or method concerned, to understand what it does, and to change it from one obvious behaviour to a different obvious behavior.

Having lots of self-contained methods and modules that seem almost to small to make sense is a good thing. Any individual method should be near-trivial to write and read. Many practitioners make the mistake of thinking "Oh, this is trivial to understand, it can't hurt to add a bit more functionality - it will still be pretty clear." Resist that urge with all your power of will; instead, exert this effort on a well-thought-out macro-structure, so that it remains trivial to find, read and change each part when necessary.

(The reasons that this isn't done more often are complex and probably intractable. Writing something that works well at first and slowly becomes unfit for modification seems to give quick return on investment, and many managers are unable to comprehend that a system which you can almost work with may be very expensive to transform into one that you can actually work with in the future. But that's no excuse for not doing the right thing in the first place when experience has taught you to do so.)

Title: Structure vs. programming


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答: Mandatory inclusion, expansion of $Log$ information when our SCC was antiquated version of PVCS. We had some files where the $Log$ information was much, much longer than the actual code in the file.</p>

ContentLicense: CC BY-SA 2.5


问:
How to use lists in equivalence partitioning?
I have read that equivalence partitioning can be used typically for intervals or lists, e.g. I assume it can be used for every set of inputs.
Anyway if the requirement says that allowed colors are (RED,BLUE,BLACK, GREEN), I cannot treat them like a list, right? I mean, testing one of them would not be enough because developers most likely used some switch-case and thus it is not real "set" where one could represent also the others.
So how it is meant with lists?

Also what is not that clear to me, I do not think it is always possible to do the initial partioning and then design the test cases.

   What about checking two lines intersection:   Y=MX+C. (two inputs)

1) The lines are paraller. M1=M1 but C1 must be different from C2.

2) Lines are intersecting. M1 must be different from M2.

3) Coincident. The are the same.

How can I use partitioning here? THis is actually taken from a book and it says that these sets are eq.classes.

答:
Equivalence partitioning is pretty much grouping the list elements so that chosen colour is grouped to one group:

RED,RED,RED,BLUE,BLUE,BLUE,BLUE,BLACK,GREEN

If you choose BLUE, then equivalence partitioning basically groups BLUE elements:

RED,RED,RED,(BLUE,BLUE,BLUE,BLUE),BLACK,GREEN

This can be represented as boolean sequence:

false,false,false, true,true,true,true, false, false

Now returning to the line intersection. If y=mx+c twice, then there is two pairs (x1,y1) and (x2,y2) so that they're the same element, i.e. x1=x2, y1=y2.

Each line has large number of (x,y) pairs which are not in the intersection, so you'll expect the following pattern:

false, false, false, false,..., false, true, false, false, false, ...

There is only one true value in the whole continuous sequence of (x,y) pairs.


问:
How can I ensure our SolidWorks files are covered by the GPLv3?
I am in charge of a project on github that has files that are and are not code based. Specifically, I am worried about our SolidWorks files. How do I ensure these files are covered by the GPLv3 license?</p>

答:
The GPL FAQ addresses this with:  GPL for other than software

You can apply the GPL to any kind of work, as long as it is clear what constitutes the “source code” for the work. The GPL defines this as the preferred form of the work for making changes in it.

Presuming you mean the 3D modeling software SolidWorks, then a design file would fall into this categorization that the FSF is intending with that FAQ.

As far as marking your design files as GPL'd, I would consider a couple of options:

clearly state they are released under the GPL on your website

if there are associated "info" files with the design files, you can add the GPL information there

add a note block within the design itself indicating that it's released under the GPL.  Essentially, wherever you would place copyright information for the design would be a good place to indicate the licensing terms.

OwnerDisplayName: Stedwell


问:
How common is it for a team to write everything in-house?
In a recent interview I asked the interviewers "how do you go about evaluating new technologies and libraries (such as SignalR) and bringing them in to use?". They said they don't, that instead they write everything themselves so they don't have to rely on anyone else.

The firm doesn't work for the government or defence contractors or on any safety-critical projects or anything like that. They were just your average, medium-size software development firm.

My question is: how common is it for teams to write everything themselves? Should I be concerned by teams that do?

Edit -- Most every response has said this is something to be concerned by. Would a second interview be an appropriate time to ask them to clarify/repeat their position on writing everything in house?

答:
If you are a technology based company of a certain size, than it would seem that you will be developing more and more of your own tech, for example: google develops alot if not most if not all of their software while open sourcing most of it in the pursuit to make it an industry standard.

For smaller companies, it would seem like an utter waste of time when they're trying to ship a specific product with it's own business logic, and in my experience I haven't seen that small-medium sized companies do so.

It becomes more intricate when you're talking about heavily-specialized code base, for example: encryption algorithms - some people have a basic understanding on how they work, but the intricate parts of actually implementing a solution would seem like shooting yourself in the foot unless you hire a cryptographer which specializes in such things.

Some companies do allow freedom to create your own open source projects, which seems more appropriate.

I would personally not go to a place with such culture.


问:
What is the best approach for overriding fields in a database?
I have a database that contains projects and each project contains many samples. I want a project level threshold value, to trigger highlighting when a field on the sample is above this threshold. I also want to be able to override the threshold at the individual sample level.

So I can see two ways to implement this:

keep the threshold field (only) on the sample, and trigger this to get filled in when the project is saved.

have both sample and project level threshold fields, and only use the sample field when it is relevant (there seems to be some redundancy with this model, though it more accurately represents the situation)?

Are there advantages / problems with either approach?

答:
I would go with your second option, only store the override value on the sample records when it is different to the project threshold (stored on the project record).

These seems like the cleaner solution to me (storing info about the project with the project record, and the sample specific data with the sample) but more importantly there's a problem with your first option.

For example, if you store the project threshold on the samples where there is no sample specific threshold and you have a project threshold of 5:

```<code>| Sample Name | Threshold |
| Sample A    | 5         |
| Sample B    | 5         |
| Sample C    | 5         |
</code>```

You update Sample C to have an over-ridden threshold of 6:

```<code>| Sample Name | Threshold |
| Sample A    | 5         |
| Sample B    | 5         |
| Sample C    | 6         |
</code>```

You then update the project threshold to 6:

```<code>| Sample Name | Threshold |
| Sample A    | 6         |
| Sample B    | 6         |
| Sample C    | 6         |
</code>```

If you should go on to change the project threshold back down, you can't distinguish C from A and B, meaning it will also be changed back to 5, which might not be what you want.

You could store a flag to indicate that the threshold is sample specific to avoid this situation, but this seems redundant when compared to storing the project threshold on the project and having nulls in the sample threshold unless it is set.

Body:
I would go with your second option, only store the override value on the sample records when it is different to the project threshold (stored on the project record).

These seems like the cleaner solution to me (storing info about the project with the project record, and the sample specific data with the sample) but more importantly there's a problem with your first option.

For example, if you store the project threshold on the samples where there is no sample specific threshold and you have a project threshold of 5:

| Sample Name | Threshold |
| Sample A    | 5         |
| Sample B    | 5         |
| Sample C    | 5         |

You update Sample C to have an over-ridden threshold of 6:

| Sample Name | Threshold |
| Sample A    | 5         |
| Sample B    | 5         |
| Sample C    | 6         |

You then update the project threshold to 6:

| Sample Name | Threshold |
| Sample A    | 6         |
| Sample B    | 6         |
| Sample C    | 6         |

If you should go on to change the project threshold back down, you can't distinguish C from A and B, meaning it will also be changed back to 5, which might not be what you want.

You could store a flag to indicate that the threshold is sample specific to avoid this situation, but this seems redundant when compared to storing the project threshold on the project and having nulls in the sample threshold unless it is set.


问:
Why NoSQL (Key-Value) storage become popular these days?
It seems that NoSQL concept not something very new and innovative, but these days become very popular. Why it become popular recently but not happen in the time when SQL is very popular?</p>

答:
NoSQL is not the absence of SQL necessarily. It can mean "Not Only SQL". It came about because of the web and the rise of massively distributed computing structures where SQL's overhead becomes a liability rather than an asset. It's the same with functional programming.

Lisp has been around since the 60s, ML since the 70s, and Erlang for a good while as well. It began to rise when people discovered that state mutability in a concurrent environment provides a wealth of problems.

Before that, Object Oriented Programming provided a tool for project organization and for separation of concerns that while perhaps a little slower than the procedural code still used in numerical computing, it was a good fit to the then new web programming architectures.

So it's a really a question of having the right tools for the job. Sometimes you need SQL, sometimes you don't.


问:
Are Python sockets suitable for file synchronization?
I'm working in an organisation with limited funds. They can't afford a business account on Dropbox. However, they would find it useful to have all their files synchronized on local machines.

I've recently looked at Python Sockets and it looks as though a custom script could achieve what they're looking for. I'm concerned that it may be too low-level  because a library may exist that provides a lot of functionality and it would be a waste of resources to start from scratch.

Is there a Python library/module that would provide what I'm looking for?

答: That sounds like you would be reimplementing rsync in Python. If you're mainly synchronizing NIX machines you should talk a look at using that. Specifically for Python, libraries like fabric can help you push files to remote machines.


问:
UML Class diagram confusion
I am learning how to draw a UML class diagram and after reading a few tutorials, I am still confused about the appropriate usages of Association type (The clear diamond and black diamond). I understand their usages but I haven't got a very concrete understanding on when to use them and when not to.

For example in the sample class diagram below, I would have thought that if Customer does not exist, the Order will be gone too but an association diamond was not being used.

Hope someone can provide me with more explaination/examples on the usages of association types.

Thanks.

答:
An association links one class to another to indicate a relation between them. For example, you have an association between Customer and Order which (with no further information) indicates that:

A customer can have an order or maybe several orders,

An order can belong to a customer or maybe shared by several customers.

The diagram in your question gives an additional info: there is one and only one customer by order, and zero or more orders by customer, so the rules become:

A customer have zero or more orders,

An order belongs to one and one only customer.

While aggregation is used in the association between Order and OrderDetail, it's not used in the association between Customer and Order. This is done to indicate the life cycle dependency. If an instance of the Order is destroyed, all instances of OrderDetail inside it would be destroyed too; on the other hand, the instances of Order are independent of the life cycle of the Customer instance, thus no aggregation here.

This doesn't mean that an order can exist without a customer: the 1 ↔ 0..* association explicitly forbids the orders which have no customers. The difference between a 1 ↔ 0..* association and the aggregation really happens on life cycle level.

Title: UML Class diagram confusion


问:
Best OOP design pattern for a sequence of operations
I am working on an application, a module of which does the following financial operations sequentially:

When a user requests for a certain amount to be transferred into her bank account:

check whether any transaction can happen now? (transaction can be carried out only during a certain time period)

check whether the user has requested for a minimum amount to be withdrawn

check whether the user has any default account

The result of all the above actions should be logged.

If all the above condition satisfies, the transaction is carried out. In future, there might be some additional checks.

Which object oriented design pattern should be best suitable for the above case?

答:
It sounds like what you are looking for is a Chain of Responsibility. In this case you could have the following classes:

TransactionValidatorBase abstract base class

TransactionTimeValidator

TransactionAmountValidator

TransactionAccountValidator

That are chained together to apply however many rules you specify.

Furter Reading

CoR on OODesign.com

Following the CoR on JavaWorld


答:
Technologies come and technologies go.  New technologies are frequently touted as better for being newer and having learned from the implied error of some key aspect of previous technologies.  In recent memory, Java was going to make everything easier, better, and more reliable than C, C++, and other languages of the 20th century.  Now other languages are going to make everything easier, better, and more reliable than Java.  Similarly, relational algebra and SQL were going to make everything simpler to work with than the "network" databases that preceded them, and now "no SQL" databases are going to make things better than SQL.

In practice, these new technologies never do what they claim, at least not on a broad basis, and not for long.  They do well in the narrow world they were originally defined for, and then they begin to accrete changes, and morph into the dragon they were intended to slay.  For the period during their rise, which has gotten shorter as the Internet has accelerated change in programming technologies, new technologies offer great promise.  NoSQL is already beginning to show their weaknesses ("eventual consistency"?  Sheesh!), leading to the revisionist re-definition of "NoSQL" as "Not [O]nly SQL".

Title: Why NoSQL (Key-Value) storage become popular these days?

Body: It seems that NoSQL concept not something very new and innovative, but these days become very popular. Why it become popular recently but not happen in the time when SQL is very popular?</p>


问:
Is it possible to reach absolute zero bug state for large scale software?
I am talking about 20-30+ millions lines of code, software at the scale and complexity of Autodesk Maya for example.

If you freeze the development as long as it needs to be, can you actually fix all the bugs until there is simply not a single bug, if such a thing could be verified by computers? What are the arguments for and against the existence of a bug-free system?

Because there is some notion that every fix you make creates more bugs, but I don't think that's true.

By bugs I meant from the simplest typos in the UI, to more serious preventative bugs that has no workaround. For example a particular scripting function calculates normals incorrectly. Also even when there are workarounds, the problem still has to be fixed. So you could say you can do this particular thing manually instead of using the provided function but that function still has to be fixed.

答:
No.

David Hilbert proposed his second problem of mathematics back in 1900 that essentially asked the world to prove that the arithmetic worked as intended.  He later propsed "the Entscheidungsproblem", which asked something similar in logical terms.  Kurt_Gödel's "first incompleteness theorem" proved in 1931 that no theory of elementary arithmetic could be both consistent and complete.  Alan Turing's representation of the Entscheidungsproblem as "the halting problem" moved the issue straight to the heart of this question, where he proved that it is impossible to prove whether a program will run to completion or not.  Given that undeciability, it is also impossible to prove whether a program has any bugs or not.

None of that frees the practicing programmers among us from striving for no bugs.  It merely means that we cannot succeed in general.


答:
Here's my theories:

It's new and it's shiny. Look at me!

Facebook/google/twitter/whoever use it, therefore it must be good.

Data modelling (properly) is hard. A lot of developers haven't learnt that skill.

On the surface it sounds great. Simple, free, scalable. Plus I don't have to learn SQL!

People don't have a good understanding of ACID.


答:
The question is, what are you using it for?

The vast majority of things using databases out there don't care significantly about ACID, and relational integrity.  It is good to know about these concepts so that when you do need them, you know where to (not) look.

When MySQL came onto the scene back in '95 it didn't have ACID.  It still isn't an ACID server by design (some of the table structures will let you do atomic transactions).  Claiming that ACID is a missing feature in NoSQL misses that it isn't a critical feature in not-NoSQL databases either.

Looking at MySQL and where it was used, and what it did one can see that it was used where speed of serving data is king.  This still has its role today that other systems don't provide.  Large, possibly distributed databases serving data.

This idea of the key-value storage isn't particularly new, its just that the hardware and software have caught up to the idea such that it can preform where it needs to to be competitive with other, heavier solutions.  Look at tuple space which has been around ince at least the '80s.

JavaSpaces (an implementation of tuple spaces) tried this, I recall looking at it long ago, but it didn't seem to take off.

This image shouldn't be too unfamiliar to those who use a NoSQL database.  Tuples and NoSQL databases are often mentioned in conjunction with each other.

Its not so much that it is popular today (and was unpopular in the past), but rather that the niche that a NoSQL database can fill allows ot to be filled with something that is quite different than what the mainstream database users are familiar with.  Its just that the technology has caught up to filling this niche more easily (JavaSpaces were a pain to use) than it has in the past, and the advantages that it offers to fill this niche beat the more mainstream approaches (without throign lots of hardware at it)

See also Polygot Persistence by Martin Fowler.


问:
How to compute barycentric coordinates in a systematic and efficient way?
As part of a ray tracer implementation, I need to compute the barycentric coordinates in a triangle in 3D in order to decide if a ray hits the triangle or not. In theory this could be done by simply solving a few linear equations. But due to the fact that the vertices of a triangle could have the same x, y or z coordinates, some of the coefficients in the equations would be 0, and this caused numerical error in my initial implementations. So, is there a systematic approach to find the barycentric coordinates in a more efficient way? Or I have no choice but to brutally check each possibility one by one?</p>

答: You might find that adding a little random noise to troublesome coordinates can be helpful.</p>


问:
Are programming books in other languages useful for Python?
I'm a self-taught intermediate Python programmer; I frequently come across popular books on software development and programming written in other languages (often Java).

Typical examples:

Refactoring: Improving the Design of Existing Code

Design Patterns, Gang of Four

Test Driven Development: By Example

The Art of Unit Testing: With Examples in .NET

Generally speaking, how useful is it to read a book written for another language? Specifically, what about Python? Should one stick to language specific books?

For example, a lot of people praise Design Patterns by the GOF, I've never read it because the model applies to other languages (after all Python is about anti-patterns, right?) yet I feel the urge to because of it's place in the CS literature cannon.

Likewise, would The Art of Unit Testing: With Examples in .NET help a Python programmer learn unit testing even though the examples are in .Net?

答:
Absolutely! It's actually very helpful to break away from your primary language occasionally because this lets you see programming concepts through a different lens which will allow you to gain new perspectives.

What makes any software good, or high quality is never about the syntax or language of choice.  It's how that language is applied. Steve McConnell calls this programming into a language instead of programming in a language.

McConnell wrote Code Complete, a book I highly recommend. He makes a specific note why the examples are in many different languages. One of the reasons is he wants the reader to focus on the concepts he is illustrating and not on the syntax.

The books in your list describes general concepts that would certainly be useful to any programmer, regardless of their language of choice.

Starting out you do want to focus on just being able to write code that compiles. It doesn't take very long to learn the syntax of a given language and with documentation and intellisense this takes even more away from how much you have to actually remember. Most languages can be learned within a few months. However, writing high quality software is a discipline and craftsmanship that takes years of practice and experience and even then there will always be room for improvement. Learning about design concepts such as how to make your software more testable, modular, loosely coupled etc. will open your eyes on how you look at code in general.

When you stop caring about syntax and can see code through a neutral lens then this will truly benefit you as a programmer.


问:
How can I compute maximal area including only given integer pairs of (x,y) coordinates?
The values of a function of two variables z = f (x, y), where x, y, z take integer values are stored in sql db. Calculate (appoint) the largest surface area of the flat. By 'flat area' we mean an area about which for each pair of x and y lying inside the area about the value of the function is constant (z = const).

I have already tried to use this flood fill algorithm, but I am not sure if this is the right way. e.g. if I have pairs(x,y) as follows: (0,0),(0,2),(2,0),(2,2) for which z equals to 5(z=const) and have point (1,1) where z=1 - how should I compute "flat area"?

答: Use flood fill to identify flat regions with no holes. For each one, solve the problem for that region, remember the answer, identify an adjacent flat region (if any), alter the current region to have the adjacent region's altitude, rinse, lather, repeat. Subtracting the area of the altitude 1 region from the area of the enclosing altitude 5 region is straightforward.</p>


问:
Is equivalence partitioning part of negative testing?
I assume that negative testing is an approach to design the test cases and so is equivalence partitioning. But I am not sure if NT is a part of ET.

An example:

A field can accept a numeric value from the range 0-10.

So I have three partitions: to 0, from 0-10 and more than 10.
Another invalid partitions would represent letters which is also negative testing, isn't it?

答:
I would not classify equivalence partitioning as a negative test. Equivalence partitioning is about reducing the cost of testing, while achieving the same coverage. In your example above, equivalence partitioning allows you to test just 1 number in the 0-10 range, and use that test to stand for the whole range.  Exhaustive testing, you would test the full range (11 tests), verses a single sample (1 test).  It's more about being more efficient. </p>

<p>Boundary testing could be considered negative testing. In your example, testing behavior at -1, 0, 10, 11 is an example of boundary testing. Also, other input types (floating point, characters, etc.) are considered negative tests.  </p>

Body:
I would not classify equivalence partitioning as a negative test. Equivalence partitioning is about reducing the cost of testing, while achieving the same coverage. In your example above, equivalence partitioning allows you to test just 1 number in the 0-10 range, and use that test to stand for the whole range.  Exhaustive testing, you would test the full range (11 tests), verses a single sample (1 test).  It's more about being more efficient.

Boundary testing could be considered negative testing. In your example, testing behavior at -1, 0, 10, 11 is an example of boundary testing. Also, other input types (floating point, characters, etc.) are considered negative tests.


问:
Creating alien symbols or signs that look natural
I was reading some Cthulhu Mythos stuff and started to think about those various signs and symbols that are used in the texts. Of course those are made by humans but point is that they look natural to human eyes.

So, what kind of algorithm would be needed to create natural looking symbols and signs? How this problem could be approached?

I guess Golden ratio and Fibonacci numbers are in key role.

答:
Reduce the problem first. Let's have an alien letter. Let's assume the letter is printed by an alien printer in small resolution, e.g. 20x30 points.

You can see we don't have a lot of possibilites in such scale, most of them are already used in some Earth language.

Solution 1:

Use symbols from unusual alphabets (e.g. greek, arabic, indian alphabet), rotate them, mirror them.

This is the simplest algorithm and will look very natural (have you ever seen a Matrix code generator?)

Solution 2:

Generating your own symbols. Note that symbols are always composed from relatively simple components - straight lines, circles, curves.

Using only straight lines, you can create something like runes. Note that many natural symbols have some kind of symmetry (see http://en.wikipedia.org/wiki/Runes).

Using only curves, you can create something like arabic alphabet

Word composition:

Take inspiration in different alphabets, look how they handle spaces between words or end of sentences. Probably having some smaller symbols for interpunction would be a good idea. Don't make all the words the same length. Don't make all the symbols appear with the same probability. Before creating long texts, you should first create syllables from your symbols and a word dictionary from the syllables. Some syllables should appear only in the beginning/end of words (grammar). The same words should be seen in different sentences (especially short words).


问:
Why are semicolons and commas interchanged in for loops?
In many languages (a wide list, from C to JavaScript):

commas , separate arguments (e.g. func(a, b, c)), while

semicolons ; separate sequential instructions (e.g. instruction1; instruction2; instruction3).

So why is this mapping reversed in the same languages for for loops:

```<code>for ( init1, init2; condition; inc1, inc2 )
{
    instruction1;
    instruction2;
}
</code>```

instead of (what seems more natural to me)

```<code>for ( init1; init2, condition, inc1; inc2 )
{
    instruction1;
    instruction2;
}
</code>```

?

Sure, for is (usually) not a function, but arguments (i.e. init, condition, increment) behave more like arguments of a function than a sequence of instructions.

Is it due to historical reasons / a convention, or is there a good rationale for the interchange of , and ; in loops?

答:
We write loops like:

```<code> for(x = 0; x < 10; x++)
</code>```

The language could have been defined so that loops looked like:

```<code> for(x = 0, x < 10, x++)
</code>```

However, think of the same loop implemented using a while loop:

```<code> x = 0;
 while(x < 10)
 {
     x++;
 }
</code>```

Notice that the x=0 and x++ are statements, ended by semicolons. They aren't expressions like you would have in a function call. Semicolons are used to separate statements, and since two of the three elements in a for loop are statements, that's what is used there. A for loop is just a shortcut for such a while loop.

Additionally, the arguments don't really act like arguments to a function. The second and third are repeatedly evaluated. It's true they aren't a sequence, but they also aren't function arguments.

Also, the fact that you can use commas to have multiple statements in the for loop is actually something you can do outside the for loop.

```<code>x = 0, y= 3;
</code>```

is a perfectly valid statement even outside of a for loop. I don't know of any practical use outside the for loop though. But the point is that commas always subdivide statements; it's not a special feature of the for loop.

Body:
We write loops like:

 for(x = 0; x < 10; x++)

The language could have been defined so that loops looked like:

 for(x = 0, x < 10, x++)

However, think of the same loop implemented using a while loop:

 x = 0;
 while(x < 10)
 {
     x++;
 }

Notice that the x=0 and x++ are statements, ended by semicolons. They aren't expressions like you would have in a function call. Semicolons are used to separate statements, and since two of the three elements in a for loop are statements, that's what is used there. A for loop is just a shortcut for such a while loop.

Additionally, the arguments don't really act like arguments to a function. The second and third are repeatedly evaluated. It's true they aren't a sequence, but they also aren't function arguments.

Also, the fact that you can use commas to have multiple statements in the for loop is actually something you can do outside the for loop.

x = 0, y= 3;

is a perfectly valid statement even outside of a for loop. I don't know of any practical use outside the for loop though. But the point is that commas always subdivide statements; it's not a special feature of the for loop.


问:
How to implement better security in Linux?
I'm just investigating the security and control of the Linux platform in comparison to Android.

In Android there seems to be a huge development around security - Applications are required to ask for system permissions, and if the user grants that permission, then the system allows that application to execute with those granted privileges.

It isn't like that on vanilla Linux. Applications can access anything they want, albeit not granting them to modify files, but nevertheless. Users simply don't know how applications work, and what information - sensitive information - they take and what they do with that information (upload it to a database and sell it to 3rd parties).

So what is this dealt with?

I'd imagine the Linux kernel has to be modified so it accepts access tokens per application basis or something similar.

Windows at least has some type of security system with it's built in firewall and local authority service. (I know little about Windows.)

答:
Android security is almost a joke. Consider the "read phone state and identity" permission - this is nearly always used by apps to send your phone details to advertisers so they can target ads at you (and earn a little revenue by the app maker). Does the app really need access to all your sensitive data on the phone just to get a unique id off you? Apparently so!

Then there's the way that the permissions are used, currently there's been a bit of malware on the App Store where an legitimate app requested some permission, and subsequently updated the app to add some malware that exploited that permission - and no-one noticed as the permission was already granted.

I think the Android security model, that means you have to give permission to various settings up-front, and in such coarse-grained ways, means that no-one really looks at what the apps requires, you have to accept all security permissions to use the app.

I'd say all users don't know how Android apps work either - once you've given an app network and file access, it can send all your files to a 3rd party without needing to trouble you for permission - you do have a file manager app on your phone what already has been given these permissions don't you?

You can't build security in in a way that stops all bad things without also stopping all the good things - security is more about run-time permissions and restricting apps from accessing parts of the system that it shouldn't have access to. Now Linux security is mainly based around filesystem security in that you prevent 1 user's running apps from accessing another user's files (as a multi-user system, this is important, and even for a single-user system, you don't want a rogue app from accessing sensitive 'root' system files).

BTW, Linux has iptables - a 'built in' firewall, and if the standard security system isn't good enough, you can set SELinux going, which was designed by the NSA.


答:
So why in the same languages such mapping is reversed for for loops.

Technically, the mapping is not "reversed".

The things separated by commas are not parameters.  In (at least) C++ and Java, they can be declarations, so they are not even expressions.

The things separated by semicolons are not (single) statements either.

In reality what we have here is a different syntactic context where the same symbols are being used differently.  We are not comparing like with like, so there is no mapping, and no strong argument for a consistent mapping based on semantic consistency.

So why not do it the other way around?

Well I think the reasons come from the "natural" meaning of , and ;.  In English written language, a semicolon is "stronger" break than a comma, and the glyph for semicolon is more visible than a comma.  Those two things combine to make current arrangement seem (to me!) to be more natural.

But the only way to know for sure why the syntax choice was made would be if the C designers could tell us what they were thinking back in ~1970.  I doubt that they have a clear memory of technical decisions made that far back in time.

Is it due to historical reasons / a convention

I'm not aware of any language before C that used a C-like syntax for "for" loops:

Donal Fellows notes that BCPL and B didn't have an equivalent construct.

The FORTRAN, COBOL and Algol-60 (and Pascal) equivalents were less expressive, and had syntaxes that did not resemble C "for" syntax.

But languages like C, C++ and Java that came after C all clearly borrow their "for" syntax from C.

Title: Why are semicolons and commas interchanged in for loops?

Body:
In many languages (a wide list, from C to JavaScript):

commas , separate arguments (e.g. func(a, b, c)), while

semicolons ; separate sequential instructions (e.g. instruction1; instruction2; instruction3).

So why is this mapping reversed in the same languages for for loops:

```<code>for ( init1, init2; condition; inc1, inc2 )
{
    instruction1;
    instruction2;
}
</code>```

instead of (what seems more natural to me)

```<code>for ( init1; init2, condition, inc1; inc2 )
{
    instruction1;
    instruction2;
}
</code>```

?

Sure, for is (usually) not a function, but arguments (i.e. init, condition, increment) behave more like arguments of a function than a sequence of instructions.

Is it due to historical reasons / a convention, or is there a good rationale for the interchange of , and ; in loops?


问:
Is GCC dying without threads support on Windows?
I need some opinion. GCC was always a very good compiler, but recently it is losing "appeal".
I have just found that on Windows GCC does not have std::thread support, forcing Windows users to use another compiler because the most exciting feature is still missing.

But why really doesn't GCC still have threads support under Windows? License problems? ABI incompatibilities? (Well there are already several cross-platform libraries using multithreading: boost, POCO, SDL, wxwidgets, etc. Wouldn't it be simple to use already existing, and MIT/libpng licensed, code to fit this hole instead of shipping GCC releases with no thread support?)

Recently, looking at compiler comparisons, GCC has the widest support for C++11 features with respect to other compilers, except for the fact that on Windows this is not true because we are still lacking atomics, mutexes and threads :/

I'd like to know more about this topic, but the only thing I can find is people asking for help because:

"thread" does not exist in std namespace

Looking at tickets tracking and mail discussions of GCC/TDM-GCC, there were requests for thread support since 2009. Possible that after 4 years still no solution? What's really happening?

答:
I understood that GCC is falling out of favour because the people maintaining it have become somewhat arrogant, and now that LLVM is here (and is very good) people are voting with the feet.

Slashdot had a discussion about LLVM's new support for C++11. _merlin says:

Oh I don't think anyone thinks it's evil, just that it's pure
  self-interest rather than generosity. GCC's phenomenal popularity has
  led to its maintainers growing massive egos and behaving like total
  [****]. Bugs are introduced faster than Red Hat and Apple can get
  patches for them accepted, and they have a nasty habit of not looking
  at bug reports, then closing them due to inactivity without actually
  fixing them

which chimes in with your observation about the 4-year delay.


答:
For me they are used more less similar meaning to their linguistic sense. Commas are used with lists and semicolons with more separate parts.

In func(a, b, c) we have a list of arguments.

instruction1; instruction2; instruction3 is maybe a list but a list of separate and independent instructions.

While in for ( init1, init2; condition; inc1, inc2 ) we have three separate parts - a list of initializations, a condition and a list of increment expressions.


答:
In C and C++ this is the comma operator, not just a comma.

The grammar for a for loop is something like

```<code>for ([pre-expression]; [terminate-condition]; [increment-expression]) body-expression
</code>```

In the case of your question:

```<code>pre-expression -> init1, init2
terminate-condition -> condition
increment-expression -> inc1, inc2
</code>```

Note that the comma-operator allows you to perform multiple actions in one statement (as the compiler sees it). If your suggestion was implemented there would be an ambiguity in the grammar as to when the programmer intended to write a comma-operator statement or a separator.

In short, ; signifies the end of a statement. A for loop is a keyword followed by a list of optional statements surrounded by (). The comma-operator statement allows the use of , in a single statement.

Body:
In C and C++ this is the comma operator, not just a comma.

The grammar for a for loop is something like

for ([pre-expression]; [terminate-condition]; [increment-expression]) body-expression

In the case of your question:

pre-expression -> init1, init2
terminate-condition -> condition
increment-expression -> inc1, inc2

Note that the comma-operator allows you to perform multiple actions in one statement (as the compiler sees it). If your suggestion was implemented there would be an ambiguity in the grammar as to when the programmer intended to write a comma-operator statement or a separator.

In short, ; signifies the end of a statement. A for loop is a keyword followed by a list of optional statements surrounded by (). The comma-operator statement allows the use of , in a single statement.


答:
The main question is if your "flat area" has to be convex or not.

If it can be non-convex then flood fill algorithm will work fine, and your example area can be treated as the flat area.

If it has to be convex then the answer from below question will work

https://stackoverflow.com/questions/7332065/what-is-the-best-algorithm-to-find-the-largest-black-convex-area-in-an-image

Title: How can I compute maximal area including only given integer pairs of (x,y) coordinates?

Body:
The values of a function of two variables z = f (x, y), where x, y, z take integer values are stored in sql db. Calculate (appoint) the largest surface area of the flat. By 'flat area' we mean an area about which for each pair of x and y lying inside the area about the value of the function is constant (z = const).

I have already tried to use this flood fill algorithm, but I am not sure if this is the right way. e.g. if I have pairs(x,y) as follows: (0,0),(0,2),(2,0),(2,2) for which z equals to 5(z=const) and have point (1,1) where z=1 - how should I compute "flat area"?


问:
How to calculate percentile in Java without using Library
I am trying to calculate 95th Percentile from the data sets which I have populated in my below ConcurrentHashMap.

I am interested in finding out how many calls came back in 95th percentile of time

My Map will look like this and it will always be sorted in ascending order on the keys- In which

```<code>key - means number of milliseconds
value - means number of calls that took that much milliseconds

Milliseconds    Number

0               1702
1               15036
2               14262
3               13190
4               9137
5               5635
6               3742
7               2628
8               1899
9               1298
10              963
11              727
12              503
13              415
14              311
15              235
16              204
17              140
18              109
19              83
20              72
</code>```

For example, from the above data sets, it means

1702 calls came back in 0 milliseconds

15036 calls came back in 1 milliseconds

Now I can calculate the 95th percentile by plugging the above data sets in the Excel sheet. But I was thinking to calculate the percentile in Java code.

I know the algorithm will look something like this-

Sum all values from the map, calculate 95% of the sum, iterate the map keys in ascending order keeping a running total of values, and when sum equals or exceeds the previously calculated 95% of the total sum, the key should be the 95th percentile I guess.

But I am not able to plugin this algorithm in the Java code. Below is the map which will have above datasets.

```<code>Map<Long, Long> histogram = new ConcurrentHashMap<Long, Long>
</code>```

I am not sure what is the best way to calculate the percentile in Java. I am not sure whether I am algorithm is also correct or not. I am just trying to find out how many calls came back in 95th percentile of time.

```<code>private static void calculatePercentile() {

    for (Long time : CassandraTimer.histogram.keySet()) {

    }

}
</code>```

Can anyone provide some example how to do that?

Any help will be appreciated.

Updated code:-

Below is the code I have got so far. Let me know if I got everything correct in calculating the 95th percentile-

```<code>/**
 * A simple method to log 95th percentile information
 */
private static void logPercentileInfo() {

    double total = 0;
    for (Map.Entry<Long, Long> entry : CassandraTimer.histogram.entrySet()) {
        long value = entry.getKey() * entry.getValue();
        total += value;
    }

    double sum = 0.95*total;

    double totalSum = 0;

    SortedSet<Long> keys = new TreeSet<Long>(CassandraTimer.histogram.keySet());
    for (long key : keys) {

        totalSum += CassandraTimer.histogram.get(key);

        if(totalSum >= sum) {
           //this is the 95th percentile I guess
            System.out.println(key);
        }
    }

}
</code>```

答:
I'm not sure what you're trying to accomplish here, but
it's easy to get a percentile. Suppose you have 100 numbers. You sort them and extract the 95th one (if you want the 95th percentile). If you don't have a multiple of 100 numbers you may have to do some interpolation. I assume you know how to do that.

EDIT: OK, you already have the numbers in order. First get the total of the column called "Number". Call that Tot. Then enumerate through them, keeping a running sum of the column and call that RS. When RS passes 0.95 * Tot, you've found it. As I said, you might want to do some interpolation so you get a fractional number of milliseconds.

Your question has the right idea. It's not a big deal.

```<code>for (i=0, sum=0; i<n; i++) sum += Number[i];
tot = sum;
for (i=0, sum=0; i<n && sum < 0.95*tot; i++) sum += Number[i];
// i is about it
</code>```

Body:
I'm not sure what you're trying to accomplish here, but
it's easy to get a percentile. Suppose you have 100 numbers. You sort them and extract the 95th one (if you want the 95th percentile). If you don't have a multiple of 100 numbers you may have to do some interpolation. I assume you know how to do that.

EDIT: OK, you already have the numbers in order. First get the total of the column called "Number". Call that Tot. Then enumerate through them, keeping a running sum of the column and call that RS. When RS passes 0.95 * Tot, you've found it. As I said, you might want to do some interpolation so you get a fractional number of milliseconds.

Your question has the right idea. It's not a big deal.

for (i=0, sum=0; i<n; i++) sum += Number[i];
tot = sum;
for (i=0, sum=0; i<n && sum < 0.95*tot; i++) sum += Number[i];
// i is about it


答:
First of all, some of the books you mentioned are written with examples in multiple programming languages. For example, GOF's DP is written with C++ and, if fewer, Smalltalk examples, and TDD is written with Java and Python examples.

If you are well trained in picking up what's useful, dropping what's not, and translating what you've picked up, you'll benefit from reading most of generally recommended books for programmers. However, if you have little experience in doing this, you could start from "near-transfer" books. Otherwise, you will learn very little, or even you will learn bad ideas and habits -- some of the practices are language-paradigm dependent. I have seen a good deal of Python programmers with all the hassles for implementing GOF's DP in C++.

Transfer is psychological and educational term for applying what you have learned in a different context. They differentiate between near and far transfer. Usually near-transfer is easier and more effective, which means you need to put more effort for far-transfer.

For near-transfer learning, I highly recommend learning from similar languages, in terms of its paradigm, to your target language -- siblings in the language typology. For Python, that would be something like Smalltalk -- or nowadays Ruby but Smalltalk's legacy is greater.

For instance, you will learn a lot more from reading DPSC than from solely reading GOF's DP. (BTW, reading both DPSC and GOF's DP at the same time with careful contrasting and comparing is a very rewarding learning experience)

From my near-transfer experiences, I remember leaps of improvement in my Python programming from reading books(articles, papers, and etc) for Smalltalk, APL, Io, and ICON, all of which are dynamic in nature.

Title: Are programming books in other languages useful for Python?

Body:
I'm a self-taught intermediate Python programmer; I frequently come across popular books on software development and programming written in other languages (often Java).

Typical examples:

Refactoring: Improving the Design of Existing Code

Design Patterns, Gang of Four

Test Driven Development: By Example

The Art of Unit Testing: With Examples in .NET

Generally speaking, how useful is it to read a book written for another language? Specifically, what about Python? Should one stick to language specific books?

For example, a lot of people praise Design Patterns by the GOF, I've never read it because the model applies to other languages (after all Python is about anti-patterns, right?) yet I feel the urge to because of it's place in the CS literature cannon.

Likewise, would The Art of Unit Testing: With Examples in .NET help a Python programmer learn unit testing even though the examples are in .Net?


答:
There is no conceptual reversal.

Semicolons in C represent more major divisions than commas. They separate statements and declarations.

The major divisions in the for loop is that there are three expressions (or a declaration and two expressions) and a body.

The commas you see in C for loops are not part of the syntax of the for loop specifically. They are just manifestations of the comma operator.

Commas are major separators between arguments in function calls and between parameters in function declarations, but semicolons are not used. The for loop is special syntax; it has nothing to do with functions or function calls.


问:
Power of HTML5?
HTML5 is becoming more and more popular everyday. Many great online applications are now being created and described as pure HTML5 apps. (Like Muro)

But I don't understand what is exactly so cool about HTML5?

As far as I understand, it just adds few features for graphics that make good alternative for jQuery or Flash.

But still, it is not a programming language and it can not be used in any way to create an application, right? Still, every of the advertised HTML5 applications have only interface drawn by HTML5 and CSS3, but the core and logic of any application is still written in something more advanced, like JavaScript (at least part that runs on the client side in the browser).

Or is there something else about HTML5 that I just didn't find?

答:
The buzzword HTML5 isn't being used "properly" these days. Now HTML5 includes WebGL, WebSockets, Canvas, LocalStorage, etc... HTML5 is actually just the newest revision of the HTML markup language.

HTML5 (the definition now used by people to encompass many new web technologies) isn't meant to replace JQuery. JQuery is a JavaScript library meant to provide a single, unifying API across all browsers for DOM manipulation, among other things. JQuery is still being used in HTML5 applications.

HTML5 exposes a ton of new APIs to JavaScript which is where HTML5 applications reside in. That's where you program all your logic (apart from presentation and markup).

HTML5 is powerful as it's a combination of lots of different web technologies.

Title: Power of HTML5?


问:
Logging failed login attempts exposes passwords
I started logging failed logins attempts on my website with a message like

Failed login attempt by qntmfred

I've noticed some of these logs look like

Failed login attempt by qntmfredmypassword

I'm guessing some people had a failed login because they typed their username and their password in the username field. Passwords are hashed in the database, but if somehow the db got compromised, these log messages could be a way for an attacker to figure out passwords for whatever small percentage of people end up having a failed login such as this.

Is there a better way to handle this? Should I even worry about this possibility?

答:
Try it like this:

If the username exists, log "failed login attempt by username".  If not, log "failed login attempt by IP 123.45.67.89" instead.  That should take care of the problem of having passwords show up in the log accidentally.


答: If you have a sufficiently tight and restricted specification, you might be able to prove a bug-free program, but only based on unprovable assumptions about the correct functioning of everything else in the system.  This leaves as a given that there's no way to prove that the specifications would be considered correct by whomever posed the original problem, or by whoever was using the service.</p>

Title: Is it possible to reach absolute zero bug state for large scale software?

Body:
I am talking about 20-30+ millions lines of code, software at the scale and complexity of Autodesk Maya for example.

If you freeze the development as long as it needs to be, can you actually fix all the bugs until there is simply not a single bug, if such a thing could be verified by computers? What are the arguments for and against the existence of a bug-free system?

Because there is some notion that every fix you make creates more bugs, but I don't think that's true.

By bugs I meant from the simplest typos in the UI, to more serious preventative bugs that has no workaround. For example a particular scripting function calculates normals incorrectly. Also even when there are workarounds, the problem still has to be fixed. So you could say you can do this particular thing manually instead of using the provided function but that function still has to be fixed.


答:
The easiest way to see it is the following:

```<code>for(x = 0; x < 10; x++)
</code>```

is:

```<code>for(
x = 0;
x < 10;
x++
)
</code>```

In other words, those x = 0 thingy is actually a statement/instructions rather than a parameter. You insert a statement there. Hence they are separated by semicolon.

In fact there is no way they are separated by comma. When do the last time you insert things like x<10 as a parameter? You do that if you want to computer x<10 once and insert the result of that operation as parameter. So in comma world you would put x<10 if you want to pass on the value of x < 0 to a function.

Here you specify that the program should check x<10 every time the loop is passed. So that's an instruction.

x++ is definitely another instructions.

Those are all instructions. So they are separated by semi colon.

Body:
The easiest way to see it is the following:

for(x = 0; x < 10; x++)

is:

for(
x = 0;
x < 10;
x++
)

In other words, those x = 0 thingy is actually a statement/instructions rather than a parameter. You insert a statement there. Hence they are separated by semicolon.

In fact there is no way they are separated by comma. When do the last time you insert things like x<10 as a parameter? You do that if you want to computer x<10 once and insert the result of that operation as parameter. So in comma world you would put x<10 if you want to pass on the value of x < 0 to a function.

Here you specify that the program should check x<10 every time the loop is passed. So that's an instruction.

x++ is definitely another instructions.

Those are all instructions. So they are separated by semi colon.


问:
How can a beginning programmer begin to learn and apply testing best practices when developing software?
While learning to develop in PHP it has been easy enough that my short, one page, 20 line little scripts I could add "testing code" directly to my functions to figure out where I am or get close to the area in the code where the issue is found (for example, "print_r($var)," "var_dump($var)," "print 'you are here') type stuff.

Now that my code bases are growing lines and lines deep and accross multiple files, it's becoming a pain to go through and uncomment out all of my test code, and then go back and recomment it out again once an issue is resolved.

Recently I have discovered git in managing my larger applications. I've latched onto branches, and I have a testing branch and production branch I jump between when debugging.  The testing branch of course has all my 'print this or that' testing code.

However, this still doesn't feel right.

As code grows, what are ways I can test and debug it? What are best practices for testing and debugging code as applications get larger and more complex? The phrase "Unit testing" catches my eye now and then, but it's still unfamiliar to me. Is this something I should be paying attention more to? Do large projects have different testing and production code bases and is a version control system the correct way to approach managing it?

答:
Yes, you should absolutely be paying attention to unit testing. You should be breaking your code into units (functions, classes), which you can test individually. And you do this by writing code which executes those units with known inputs and tests the return for expected outputs.

"Testing" by inserting print statements is not really testing, it's debugging. And it's a useful debugging technique, but you do not leave those print statements in your code. You should only insert them as needed for a quick test run or two to give you a hint as to what the problem you're debugging is, then you remove them. Of course, with a real debugger hooked up to the code you can debug values without needing to alter the code at all.

You should also get into the habit of logging. You may and should have your code interspersed with log statements of various levels which you can switch on and off as necessary.

Start reading here: http://www.phpunit.de/manual/current/en/automating-tests.html

Then look into remote debugging: http://xdebug.org/docs/remote

And then into logging: https://github.com/Seldaek/monolog

This will probably start you down the road of "how do I break my code into units?", for which you should learn the proper use of functions, followed by classes and objects. And that very quickly gets you into the realm of patterns, endless discussions and proper application architecture.


答:
Errare humanum est

Even if you write code with a formal language, like B-method, that you can use to mathematically prove that requirements are met,

Even if you use a formal specification language,

There is always a human step consisting in extracting the user's needs from one or more brains to a computer.

This human step is error-prone, and the worm is in the apple.


问:
RESTFul: state changing actions
I am planning to build a RESTfull API but there are some architectural questions that are creating some problems in my head. Adding backend business logic to clients is an option that I would like to avoid since updating multiple client platforms is hard to maintain in real time when business logic can rapidly change.

Lets say we have article as a resource ( api/article ), how should we implement actions like publish, unpublish, activate or deactivate and so on but to try to keep it as simple as possible?

1) Should we use api/article/{id}/{action} since a lot of backend logic can happen there like pushing to remote locations or change of multiple properties. Probably the hardest thing here is that we need to send all article data back to API for updating and multiuser work could not be implemented. For instance editor could send 5 seconds older data and overwrite fix that some other journalist just did 2 seconds ago and there is no way that I could explain to clients this since those publishing an article is really not in any way connected to updating the content.

2) Creating new resource can also be an option, api/article-{action}/id , but then returned resource would not be article-{action} but article which I am not sure if this is proper. Also in server side code article class is handling actuall work on both resource and I'm not sure if this goes against RESTfull thinking

Any suggestions are welcomed..

答:
Here's another example that deals not with documents content but more with transient state.  (I find versioning -- given that, in general, each version can be a new resource -- a kind of easy problem.)

Let's say I want to expose a service running on a machine via a REST so that it can be stopped, started, restarted, and so forth.

What is the most RESTful approach here?  POST /service?command=restart, for example?  Or POST /service/state with a body of, say, 'running'?

It'd be nice to codify best practices here and whether REST is the right approach this type of situation.

Second, let's assume I want to drive some action from a service that doesn't affect its own state, but rather triggers a side effect.  For example, a mailer service that sends out a report, built at the time of call, to a bunch of emails addresses.

GET /report might be a way of getting a copy of the report myself; but what if we want to push to the server side further actions such as emailing as I say above.  Or writing to a database.

These cases dance around resource-action divide, and I see ways of handling them in a REST-oriented manner, but frankly it feels a like a bit of a hack to do so.  Perhaps the key question is whether a REST API should support side-effects in general.

ContentLicense: CC BY-SA 4.0

Title: RESTFul: state changing actions


问:
How to authenticate an archive
Background:
I have a updator feature in my program which will downloads updates to a directory specified be the user. Then user can install these updates whenever he/she wants by just opening them. These updates are nothing but a compressed archive file which is associated to be opened by my app.

Problem:
Now, I want when the user install the updates, my program should ensure that they are original updates created by me and are not modified by someone else. How can I ensure that? I have heard about Winrar authenticity verification. but I'm unsure whether it is good or not?

Edit: User have two ways to install the updates.

A) User download the updates from the server. An update file will get saved on user PC. User will open the update file to install it.

B) This is for user who don't have internet connectivity on his PC User download the update on a cyber cafe, copy it to his own PC and then install them.

Since in option B, user don't have internet connectivity in his PC, so my program can not check the base value on update server.

答:
A hash can be provided along with the archive, and used to ensure that the entire patch contains what is expected.  This is generally known as a checksum, (even if the term isn't 100% correct) and is commonly seen on some software sites as a means of verifying the result of a download.  Typically, something like SHA-1 is used for the actual hash, since MD5 is known to have collisions.

Of course, the hash itself could be provided by someone with malicious intent, so it alone cannot be trusted.

Enter public / private key cryptography.  You would keep the private key secret, and use it to sign your patches.  The public key would be embedded in your client software, so that it can verify that the patch comes from someone who has the correct private key (presumably only you).  You can read a bit more about digital signatures, which is typically built around the RSA algorithm.

Caveat:  of course, if the client install was modified (cracked), someone could have installed their own public key in it.  This means they could create their own patches and sign and install them.  Since you're not fully in control of the client environment, there isn't anything you can do to stop this (short of "always-online", and even then...).

Edit:  I'd also add a word of caution against home-brew solutions.  It's all to easy to think something like, "Hey, I'll just come up with a clever little way to signal that the archive is genuine, like it must have a file whose name is the total file size of everything in the archive!".  In this case, this algorithm would be the "secret".  Unfortunately, it's going to be in your client code, and it'd take a skilled programmer a few minutes of disassembly and trawling through your code to figure it out.  Please use tested algorithms like RSA!

Edit 2:  Any commercial, off the shelf solutions are also fine (perhaps even preferred, since there's less chance of implementing it incorrectly), as long as they work along the lines I've outlined above.  I'd investigate each solution carefully, and make a decision.

Title: How to authenticate an archive


答:
There is SELinux project which allows to fine-tune the interactions between processes (and filesystem). The system of permissions is a bit more flexible then Android at cost of increased complexity. Other possibility are, among others, TOMOYO Linux and AppArmor. There are desktop distributions which have them enabled by default like Fedora.

However my guess is that on Linux the applications are trusted and protection is done rather to:

Minimize the effect of security holes (for example to prevent hijacked Apache process from messing with PostgreSQL)

Don't allow user to get outside his/her boundaries and access other users' data

It is somehow justified as most of applications are open source and well-known so it is likely that such code would be discovered.

Title: How to implement better security in Linux?

Body:
I'm just investigating the security and control of the Linux platform in comparison to Android.

In Android there seems to be a huge development around security - Applications are required to ask for system permissions, and if the user grants that permission, then the system allows that application to execute with those granted privileges.

It isn't like that on vanilla Linux. Applications can access anything they want, albeit not granting them to modify files, but nevertheless. Users simply don't know how applications work, and what information - sensitive information - they take and what they do with that information (upload it to a database and sell it to 3rd parties).

So what is this dealt with?

I'd imagine the Linux kernel has to be modified so it accepts access tokens per application basis or something similar.

Windows at least has some type of security system with it's built in firewall and local authority service. (I know little about Windows.)


答:
Half of testing is having the right perspective; one way to look at it is that you're using your code as a way to determine if your code is suitable for production.  That is, if you're righting a class EmailSanitizer, you write a few test scripts that exercise EmailSanitizer, and if those tests all pass, then that builds confidence that the same code you've written for the tests is production-worthy.

I feel that once you start working from that perspective, you'll soon organically get a good feeling about what is and isn't appropriate to consider when writing test code.

Title: How can a beginning programmer begin to learn and apply testing best practices when developing software?

Body:
While learning to develop in PHP it has been easy enough that my short, one page, 20 line little scripts I could add "testing code" directly to my functions to figure out where I am or get close to the area in the code where the issue is found (for example, "print_r($var)," "var_dump($var)," "print 'you are here') type stuff.

Now that my code bases are growing lines and lines deep and accross multiple files, it's becoming a pain to go through and uncomment out all of my test code, and then go back and recomment it out again once an issue is resolved.

Recently I have discovered git in managing my larger applications. I've latched onto branches, and I have a testing branch and production branch I jump between when debugging.  The testing branch of course has all my 'print this or that' testing code.

However, this still doesn't feel right.

As code grows, what are ways I can test and debug it? What are best practices for testing and debugging code as applications get larger and more complex? The phrase "Unit testing" catches my eye now and then, but it's still unfamiliar to me. Is this something I should be paying attention more to? Do large projects have different testing and production code bases and is a version control system the correct way to approach managing it?


答:
I found Jim Shore's section No Bugs a very useful reading on this topic. The short form: It's not possible to develop without producing bugs - but we can work in such a way that we detect them as early as possible.

During the production of the code itself. For example by writing and running Unit Tests frequently during development, we constantly assure the code does what it is supposed to do. Also, it is useful to perpetually rewrite existing code in such a way that it most clearly expresses the intended system behaviour.

In your case, however, you are talking about an already existing codebase with millions of lines of code. If you want to get such a system bug free, you first of all have to know what "is a bug" for this system. You could write suites of post-hoc tests assuring the system's functionality (if not yet existing). The web of those tests may serve as an approximate definition for the correct system behaviour. But the more code you have, the more effort is involved in such exercises. Therefore, most companies make a compromise: they live with the imperfect, working with bug lists and maintenance to get the most annoying bugs out of the system.


答:
The goals of Android security are different than was traditionally with desktop operating systems like Linux or Windows.

Until recently, all systems assumed the administrator and user know and trust the applications they install. Or if the user can't be expected to know, they need the administrator, who is presumably more knowledgeable, to do it for them. Security ensured primarily that users can't read or damage each others data or prevent each other from working. That's still the case of Linux and Windows in desktop mode.

For mobile phones the case is different. Mobile phones are single-user, but they don't have administrator and are expected to be used by non-tech-savvy users. So the mobile phone (and tablet) security is supposed to give user some level of protection against malicious application, especially now the application shops provide thousands of applications.

The traditional security of isolating users is well understood after more than 30 years of experience. It is also well understood how to re-purpose the security mechanisms to separate services on server to limit damage that can be done by exploiting bug in one of them. The mechanisms for this end were greatly improved over time leading to very powerful and flexible SELinux, but it still requires a knowledgeable system administrator to set up.

On the other hand securing user against trojan horses (malicious applications they are fooled into installing) is new, largely unexplored and still severely lacking. The major problem is that if you (rightfully) don't expect the user to be able to judge whether the application is trustworthy, you can't really expect them to know what the permissions they are confirming mean and what the implication of granting them to the application are. Apple and Microsoft work around this by tightly controlling content of their application shops, but that has it's own issues (it's surprising no anti-trust bureau have forbidden it yet), Google mostly ignored it until lately and implemented some form of monitoring now. It should also be noted that the permission system exists at least since Symbian.

It should be noted that the Android security system uses the same underlying mechanisms as the one for desktop Linux. The difference is in how it is set up, not how it works.


问:
SQL Server + database design and non mandatory fields
I am developing an app which allows a user to upload a maximum of 20 photos, the straight forward way is of course adding 20 columns to my database table but if the user only uploads 1 image, the remaining columns becomes redundant. Anyone can advice me on a more efficient way to design it?

Thanks.

答:
You should never use multiple columns to hold more than one of the same item.  This is bad database design and will be a major pain to use (try to write a query that will fetch and display all of a user's photos, or delete one photo, and you will see what I mean).

Another issue is that you might want to store other info about each photo--such as when it was uploaded and what format it is.  Instead of 20 columns, suddenly you might have 60 or 80 columns in your table. Ugh!

Instead, have a table of photos that is separate from the table of users.  This is linked to the user table on user ID.  You can enforce the 20 photo limit with a table constraint, or simply by checking the number of photos programmatically before you allow upload.

Table user:

```<code>Primary Key |       |       |
USER_ID     | FIRST | LAST  | ETC.
12345       | John  | Smith | ... Any other user-specific columns
</code>```

Table photo:

```<code>Primary Key | Foreign Key |        |        |            |
PHOTO_ID    | USER_ID     | PHOTO  | FORMAT | DATE       | ETC.
13516       | 12345       | <data> | JPG    | 2013-05-01 | ... Other photo-specific columns
</code>```

If you set the foreign key for photo to on delete cascade, a user's photos will automatically be deleted if you delete the user.

See this StackOverflow question for info on a table constraint to limit the number of photos per user.

Getting the photos for a user uses a simple query:

```<code>select * from photo
    where user_id = 12345;
</code>```

If you need photos and user information like the name, use a join:

```<code>select first, last, photo from photo p
   inner join user u on p.user_id = u.user_id;
</code>```

Update: I do agree with Pieter B that, in most cases, you are probably better off storing the images separately in the file structure, and just making the images table store the file name of each image.  This will make it a lot easier to, say, display the images on a web page.  But you will also need extra code to make sure the directory stays in sync with the table--if you delete a user, you have to go manually delete all of the images.

Body:
You should never use multiple columns to hold more than one of the same item.  This is bad database design and will be a major pain to use (try to write a query that will fetch and display all of a user's photos, or delete one photo, and you will see what I mean).

Another issue is that you might want to store other info about each photo--such as when it was uploaded and what format it is.  Instead of 20 columns, suddenly you might have 60 or 80 columns in your table. Ugh!

Instead, have a table of photos that is separate from the table of users.  This is linked to the user table on user ID.  You can enforce the 20 photo limit with a table constraint, or simply by checking the number of photos programmatically before you allow upload.

Table user:

Primary Key |       |       |
USER_ID     | FIRST | LAST  | ETC.
12345       | John  | Smith | ... Any other user-specific columns

Table photo:

Primary Key | Foreign Key |        |        |            |
PHOTO_ID    | USER_ID     | PHOTO  | FORMAT | DATE       | ETC.
13516       | 12345       | <data> | JPG    | 2013-05-01 | ... Other photo-specific columns

If you set the foreign key for photo to on delete cascade, a user's photos will automatically be deleted if you delete the user.

See this StackOverflow question for info on a table constraint to limit the number of photos per user.

Getting the photos for a user uses a simple query:

select * from photo
    where user_id = 12345;

If you need photos and user information like the name, use a join:

select first, last, photo from photo p
   inner join user u on p.user_id = u.user_id;

Update: I do agree with Pieter B that, in most cases, you are probably better off storing the images separately in the file structure, and just making the images table store the file name of each image.  This will make it a lot easier to, say, display the images on a web page.  But you will also need extra code to make sure the directory stays in sync with the table--if you delete a user, you have to go manually delete all of the images.


答:
You add a child table

```<code>PhotoID int NOT NULL IDENTITY(1,1) PRIMARY KEY,
UserID int NOT NULL -- FK to User table,
Photo varbinary(max)
</code>```

This changes columns into rows, quite simply as per first normal form

There are storage benefits because you now no longer have potentially 20 BLOBS in one user row. Your user table has a lot less memory footprint for other columns.

And you can allow more then 20 photos very easily if you decide to allow more.

Title: SQL Server + database design and non mandatory fields

Body:
I am developing an app which allows a user to upload a maximum of 20 photos, the straight forward way is of course adding 20 columns to my database table but if the user only uploads 1 image, the remaining columns becomes redundant. Anyone can advice me on a more efficient way to design it?

Thanks.

Body:
You add a child table

PhotoID int NOT NULL IDENTITY(1,1) PRIMARY KEY,
UserID int NOT NULL -- FK to User table,
Photo varbinary(max)

This changes columns into rows, quite simply as per first normal form

There are storage benefits because you now no longer have potentially 20 BLOBS in one user row. Your user table has a lot less memory footprint for other columns.

And you can allow more then 20 photos very easily if you decide to allow more.