问:
How to configure simple game AI setting with jtable
I'm developing an application that has methods of this kind:

```<code>attackIfIsFar();
protectIfIsNear();
helpAfterDeadOf();
helpBeforeAttackOf();
</code>```

etc.

The initialization of my application for n players is something like

```<code>player1.attackIfIsFar(player2);
player2.protectIfIsNear(player4);
player3.helpAfterDeadOf(player1);
player4.helpBeforeAttackOf(player3);
</code>```

etc.

I don't know how to configure a jtable that that can allow me to set the equivalent of this code-block

In others words I need simply a way to create a jtable with 3 column and n row, were I can set in the column 1 and 3, the player, and in the central column one of the available methods that each player on the column 1 must invoke on each player of column 3

答:
First you need an class to represent the expression.

```<code>public class Expression {
  private Person lhs;
  private Person rhs;
  private Action action;
}
</code>```

Then you need to make a TableModel that is backed by a list of Expressions. Column count will be 3 and row count will be the size of the list. The rest of the methods are fairly straight forward to implement by mapping the row and/or column to the respective Expression and/or field.

Then you need a JTable that sets the TableCellEditor for each column. Each of which would be a combo box with the available options for the respective field. If you need more help with tables, read this tutorial.

Once all the values are configured, you will need to create some logic that will evaluate the expressions and calls the correct methods.

Edit

Here is a very basic cell editor example. You could take steps to not populate the combo boxes with a value that will allow the user to select an invalid value.

```<code>@Override
public TableCellEditor getCellEditor(int row, int col)
{
  switch (col) {
  case 0:
  case 2:
    return new DefaultCellEditor(new JComboBox(LIST_OF_PEOPLE));
  case 1:
    return new DefaultCellEditor(new JComboBox(LIST_OF_ACTIONS));
  default:
    return super.getCellEditor(row, col);
  }
}
</code>```

Body:
First you need an class to represent the expression.

public class Expression {
  private Person lhs;
  private Person rhs;
  private Action action;
}

Then you need to make a TableModel that is backed by a list of Expressions. Column count will be 3 and row count will be the size of the list. The rest of the methods are fairly straight forward to implement by mapping the row and/or column to the respective Expression and/or field.

Then you need a JTable that sets the TableCellEditor for each column. Each of which would be a combo box with the available options for the respective field. If you need more help with tables, read this tutorial.

Once all the values are configured, you will need to create some logic that will evaluate the expressions and calls the correct methods.

Edit

Here is a very basic cell editor example. You could take steps to not populate the combo boxes with a value that will allow the user to select an invalid value.

@Override
public TableCellEditor getCellEditor(int row, int col)
{
  switch (col) {
  case 0:
  case 2:
    return new DefaultCellEditor(new JComboBox(LIST_OF_PEOPLE));
  case 1:
    return new DefaultCellEditor(new JComboBox(LIST_OF_ACTIONS));
  default:
    return super.getCellEditor(row, col);
  }
}


问:
Communication between state machines with hidden transitions
The question emerged for me in embedded programming but I think it can be applied to quite a number of general networking situations e.g. when a communication partner fails.

Assume we have an application logic (a program) running on a computer and a gadget connected to that computer via e.g. a serial interface like RS232. The gadget has a red/green/blue LED and a button which disables the LED. The LEDs color can be driven by software commands over the serial interface and the state (red/green/blue/off) is read back and causes a reaction in the application logic. Asynchronous behaviour of the application logic with regard to the LED color down to a certain delay (depending on the execution cycle of the application) is tolerated.

What we essentially have is a resource (the LED) which can not be reserved and handled atomically by software because the (organic) user can at any time press the button to interfere/break the software attempt to switch the LED color.

Stripping this example from its physical outfit I dare to say that we have two communicating state machines A (application logic) and G (gadget) where G executes state changes unbeknownst to A (and also the other way round, but this is not significant in our example) and only A can be modified at a reasonable price. A needs to see the reaction and state of G in one piece of information which may be (slightly) outdated but not inconsistent with respect to the short time window when this information was generated on the side of G.

What I am looking for is a concise method to handle such a situation in embedded software (i.e. no layer/framework like CORBA etc. available). A programming technique which is able to map the complete behaviour of both participants on classical interfaces of a classical programming language (C in this case). To complicate matters (or rather, to generalize), a simple high frequency communication cycle of A to G and back (IOW: A is rapidly polling G) is out of focus because of technical restrictions (delay of serial com, A not always active, etc.).
What I currently see as a general solution is:

the application logic A as one thread of execution

an adapter object (proxy) PG (presenting G inside the computer), together with the serial driver as another thread

a communication object between the two (A and PG) which is transactionally safe to exchange

The two execution contexts (threads) on the computer may be multi-core or just interrupt driven or tasks in an RTOS.
The com object contains the following data:

suspected state (written by A): effectively a member of the power set of states in G (in our case: red, green, blue, off, red_or_green, red_or_blue, red_or_off...etc.)

command data (written by A): test_if_off, switch_to_red, switch_to_green, switch_to_blue

operation status (written by PG): operation_pending, success, wrong_state, link_broken

new state (written by PG): red, green, blue, off

The idea of the com object is that A writes whichever (set of) state it thinks G is in, together with a command. (Example: suspected state="red_or_green", command: "switch_to_blue") Notice that the commands issued by A will not work if the user has switched off the LED and A needs to know this. PG will pick up such a com object and try to send the command to G, receive its answer (or a timeout) and set the operation status and new state accordingly. A will take back the oject once it is no longer at operation_pending and can react to the outcome. The com object could be separated of course (into two objects, one for each direction) but I think it is convenient in nearly all instances to have the command close to the result.

I would like to have major flaws pointed out or hear an entirely different view on such a situation.

答: Unless you can actually prevent the button from being pressed at the application, you will always have a window open for the gadget to have it's state changed in-between the control messages. This window will always exist if you have no means of applying a semaphore between A and G operations.</p>

ContentLicense: CC BY-SA 3.0


问:
Is there a difference between "self-plagiarizing" in programming vs doing so as a writer?
I read this Gawker article about how a writer reused some of his older material for new assignments for different magazines.

Is there any similar ethical (societal?) dilemma when doing the same thing in the realm of Programming?  Does reusing a shared library you've accumulated over the years amount to self-plagarizm?

What I'm getting at is that it seems that the creative world of software development isn't as stringent regarding self-plagarism as say journalism or blogging.  In fact on one of my interviews at GS I was asked what kind of libraries I've developed over the years, implying that me getting the job would entail co-licensing helpful portions of code to that company.

Are there any cases where although it's legal to self-plagarize,  it would be frowned upon in the software world?

答:
I've never heard of it being called "self-plagiarizing" in the software world. It's called "reusable libraries". In journalism, there may be an expectation that a writer will submit and publish new articles, as that is what they are paid to do. A software developer may be expected to help produce new software but if they use pre-existing libraries that they wrote before, that's not so bad. It helps move the project faster, and it prevents you from having to re-invent the wheel.

At the same time, if I had a truly awesome library of reusable components I'd built up over the years, I'm not sure I'd ever give them to an employer to use in their project if the licensing might mean I'd never be able to use them again for any other projects in the future.

As an employer, would I trust some new developer who has a great big library of awesome stuff if I can't get full access and control of the source code? I might be willing to buy pre-built libraries from vendors with support contracts.

And to be honest, I don't even think the comparison to journalists and writers is appropriate. It just doesn't make sense. One of only things these two activities have in common is the verb "writing".


问:
Forking project on Github process
There is a project on Github that I mostly like and want to use. There are a few things I want to do differently/remove that doesn't make sense for what I want/need. Also I want to add a few things as well.

As I understand it, I should fork the project and I can make whatever changes I want and push back to my fork. From there, I also want to occasionally pull into my fork the changes from the original project so I get the latest bug fixes/features.

Am I off-base of how I think it should work? How would bring in the changes from the original project?

答:
Make the fork, then make a branch immediately.

Now you have an "untouched" master that can be updated itself going forward to get the latest changes with git pulls.

Keep you branch local without pushing to remote and you can do rebases which will do the following for you:

save away your changes

apply the latest changes from master to your branch (the ones that came from the update from the remote)

reapply your changes again, on top of the code that was updated from master (or other original branch).

When you are finally done with it, merge it back into master (or whatever branch the initial fork was from) locally and then submit the pull request for the actual owner to pull it in.

That's one workflow (or "forkflow") anyway, as I understand it.  Others are welcome to comment or correct or add more detail.

Title: Forking project on Github process


问:
Handling (many) multiple projects in Git in an enterprise environment
One of the advantages of older version control systems such as CVS and SVN in enterprise development is that anyone can connect to source control and see all the projects that the company has. This can make it easier to get a high level view of what kid of development is happening outside your sprint and also keeps everything in one place and easy to find.

However, distributed version control systems (Git, specifically) use the repository as their base unit. They work best with one project (or several closely related projects) per repository. This makes repository management more difficult in most enterprise environments where it is not unusual to have more than 25-50 projects to support. As far as I have been able to determine, you have to keep a list somewhere else of all the repos you have. There is software available, like GitHub, that help, but that still is an extra step beyond a single connection string and listing the contents of the repository.

What is the best way to deal with the complexity of multiple repositories?

答: If you are looking for a governable repository management system, try RhodeCode. It has support for forking, LDAP/AD integration, code reviews and pull-requests (coming soon).


答:
Self-plagiarizing (by Joshua Bloch) below code has been officially considered copyright violation:

```<code>private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                   ") > toIndex(" + toIndex+")");
    if (fromIndex < 0)
        throw new ArrayIndexOutOfBoundsException(fromIndex);
    if (toIndex > arrayLen)
        throw new ArrayIndexOutOfBoundsException(toIndex);
}
</code>```

But as long as one self-plagiarizes within the same company, it's likely legally OK.

Self-plagiarizing is also OK ethically, as long as it does not fall into violation of DRY.

Title: Is there a difference between "self-plagiarizing" in programming vs doing so as a writer?

Body:
I read this Gawker article about how a writer reused some of his older material for new assignments for different magazines.

Is there any similar ethical (societal?) dilemma when doing the same thing in the realm of Programming?  Does reusing a shared library you've accumulated over the years amount to self-plagarizm?

What I'm getting at is that it seems that the creative world of software development isn't as stringent regarding self-plagarism as say journalism or blogging.  In fact on one of my interviews at GS I was asked what kind of libraries I've developed over the years, implying that me getting the job would entail co-licensing helpful portions of code to that company.

Are there any cases where although it's legal to self-plagarize,  it would be frowned upon in the software world?

Body:
Self-plagiarizing (by Joshua Bloch) below code has been officially considered copyright violation:

private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                   ") > toIndex(" + toIndex+")");
    if (fromIndex < 0)
        throw new ArrayIndexOutOfBoundsException(fromIndex);
    if (toIndex > arrayLen)
        throw new ArrayIndexOutOfBoundsException(toIndex);
}

But as long as one self-plagiarizes within the same company, it's likely legally OK.

Self-plagiarizing is also OK ethically, as long as it does not fall into violation of DRY.


答:
If you have the right to reuse code, or use a library, I can't see how that would be frowned upon. Unless they wanted you to develop the code from scratch.

Why would they want that?

to take advantage of updated technology.

to have a library of code with hooks in place for expansion.

to have the source code.

If they were paying you the hours to rewrite the code, but you use the same libraries, they will feel that they over paid.


问:
The Apache License, v2.0: Copyright License vs Patent License

The Apache License, v2.0

[..]

2. Grant of Copyright License

Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense and distribute the Work and such Derivative Works in Source or Object form.

[..]

3. Grant of Patent License

Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including cross-claim or counterclaim in lawsuit) alleging that the Work or a Contribution incorporated within theWork constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

While the meaning of the Copyright License provision is rather clear, I did not get the meaning of the Patent License provision.

Which advantages does the "Grant of Patent License" provision further give to Contributors? Why are they useful?

Is the "Grant of Patent License" provision useful only in case of patent litigation?

答:
The license wants avoid this situation:

Contributor-A creates a free project.

Contributor-A convinces to Contributor-B, Contributor-C and Contributor-D of to collaborate with the project.

All people is very happy right now. The world is wonderful.

The contributors sell products based on the code of the project.

The contributor make much money from the products based on this project.

Contributor-A has various patents related to the project and decides to demand to the other contributors.

Contributor-A reclaims a fee for each product sold by the other contributors.

Can you see the problem?. Let me give you a real example:

A common theme used by the comedy crew Monty Python was to emphasize and exaggerate ridiculousnesses that their target had imposed upon themselves. Few things could be considered as humorous as making a redundancy protocol... redundant; e.g. being forced to replace it by Cisco lawyers and IETF policy.

We've been working a few years now on our packet filtering software pf(4) and it became time to add failover. We want to be able to set up pf firewalls side by side, and exchange the stateful information between them, so that in case of failure another could take over 'keep state' sessions. Our pfsync(4) protocol solves this problem. However, on both sides of the firewall, it is also necessary to have all the regular hosts not see a network failure. The only reliable way to do this is for both firewall machines to have and use the same IP and MAC addresses. But the only real way to do that is to use multicast protocols.

The IETF community proposed work in this direction in the late 90's, however in 1997 Cisco informed them that they believed some of Cisco's patents covered the proposed IETF VRRP (Virtual Router Redundancy Protocol); on March 20, 1998 they went further and specifically named their HSRP "Hot Standby Router Protocol" patent. Reputedly, they were upset that IETF had not simply adopted the flawed HSRP protocol as the standard solution for this problem. Despite this legal pressure, the IETF community forged ahead and published VRRP as a standard even though there was a patent in the space. Why? There was much deliberation at all levels of the IETF, and unfortunately for all of us the politicians within eventually decided to allow patented technology in standards -- as long as the patented technology is licensed under RAND (Reasonable And Non Discriminatory) terms. As free software programmers, we therefore find ourselves in the position that these RAND standards must not be implemented by us, and we must deviate from the standard. We find all this rather Unreasonable and Discriminatory and we will design competing protocols. Some standards organization, eh?

Due to some HSRP flaws fixed by VRRP and for compatibility with the (HSRP-licensed) VRRP implementations of their competitors, Cisco in recent times has largely abandoned HSRP and now relies on VRRP instead -- a protocol designed for and by the community, but for which they claim patent rights.

On August 7 2002, after many communications, Robert Barr (Cisco's lawyer) firmly informed the OpenBSD community that Cisco would defend its patents for VRRP implementations -- meaning basically that it was impossible for a free software group to produce a truly free implementation of the IETF standard protocol. Perhaps this is because Cisco and Alcatel are currently engaged in a pair of patent lawsuits; a small piece of which is Cisco attempting to use the HSRP patent against Alcatel for their use of VRRP. Some IETF working group members took note of our complaints, however an attempt in April 2003 to have the IETF abandon the use of patented technology failed to "reach consensus" in the IETF.

A few years ago, the W3C, who designs our web protocols, tried to move to a RAND policy as well (primarily because of pressure from Microsoft and Apple), but the community outrage was so overpowering that they backed down. Some standards groups use this policy, while others avoid it -- the one differentiation being the amount of corporate participation. In the IETF, the pro-RAND agents work for AT&T, Alcatel, IBM, Cisco, Microsoft, and other large companies. Since IETF is an open forum, they can blend in as the populace, and vote just like all others, except against the community.

Translation: In failing to "reach consensus", the companies who benefit from RAND won, and the community lost again.

Left with little choice, we proceeded to reinvent the wheel or, more correctly, abandon the wheel entirely and go for a "hovercraft". We designed CARP (Common Address Redundancy Protocol) to solve the same problem that these other protocols are designed for, but without the same technological basis as HSRP and VRRP. We read the patent document carefully and ensured that CARP was fundamentally different. We also avoided many of the flaws in HSRP and VRRP (such as an inherent lack of security). And since we are OpenBSD developers, we designed it to use cryptography.

The combination of pf(4), pfsync(4), and carp(4) has permitted us to build highly redundant firewalls. To date, we have built a few networks that include as many as 4 firewalls, all running random reboot cycles. As long as one firewall is alive in a group, traffic through them moves smoothly and correctly for all of our packet filter functionality. Cisco's low end products are unable to do this reliably, and if they have high end products which can do this, you most certainly cannot afford them.

As a final note of course, when we petitioned IANA, the IETF body regulating "official" internet protocol numbers, to give us numbers for CARP and pfsync our request was denied. Apparently we had failed to go through an official standards organization. Consequently we were forced to choose a protocol number which would not conflict with anything else of value, and decided to place CARP at IP protocol 112. We also placed pfsync at an open and unused number. We informed IANA of these decisions, but they declined to reply.

If you want know more info about this case, search the mails related to CARP and patents in the "misc" mailing list of OpenBSD. I think that this case was the first big one case related to this situation (a open protocol with patents).

Probably you can also found information related to SCO lawsuits of the last decade. The clause about patents in the GPLv3 license exists due to the SCO lawsuits.

A lot of projects (and lawyers) have learned very much of the lawsuits of the last decade.

Warning: the license doesn't protect you against lawsuit from companies external to the project.


问:
Why are so many languages passed by value?
Even languages where you have explicit pointer manipulation like C it's always passed by value (you can pass them by reference but that's not the default behavior).

What is the benefit of this, why are so many languages passed by values and why are others passed by reference ? (I understand Haskell is passed by reference though I'm not sure).

答:
There is different behavior depending on the calling model of the language, the type of arguments and the memory models of the language.

With simple native types, passing by value allow you to pass the value by the registers. That can be very fast since the value aren't need to be loaded from memory neither save back.  Similar optimization is also possible simply by reusing the memory used by the argument once the callee is done with it, without risking to mess with the caller copy of the object.  If the argument was a temporary object, you would have probably save a full copy doing so (C++11 make this kind of optimization even more obvious with the new right-reference and its move semantic).

In a lot of OO languages (C++ is more an exception in this context), you cannot passed an object by value. You are force to pass it by reference.  This make the code polymorphic by default and are more inline with the notion of instances proper to OO.  Also, if you want to pass by value, you must make a copy yourself, acknowledging the cost of performance that generated such action.  In this case, the language choose for you the approach that is more likely to give you the best performance.

In case of functional languages, I guess passing by value or reference is simply a question of optimization.  Since the functions in such language are pure and so free of side effects, there is really no reason to copy the value except for speed.  I'm even pretty sure that such language often shared the same copy of objects with the same values, a possibility available only if you used a pass by (const) reference semantic.  Python also used this trick for integer and common strings (like methods and class names), explaining why integer and strings are constant objects in Python.  This also help to optimize the code again, by allowing for example pointer comparaison instead of content comparaison, and doing lazy evaluation of some internal data.


问:
Which is more important in a web application code promotion hierarchy? production environment to repo resemblance or unidirectional propagation?
Lets say you have a code promotion hierarchy consisting of several environments, (the polar end) two of which are development (dev) and production (prod).

Lets say you also have a web application where important (but not developer controlled) files are created (and perhaps altered) in the production environment.

Lets say that you (or someone above you) decided that the files which are controlled/created/altered/deleted in the production environment needed to go into the repository.

Which of the following two sets of practice / approaches do you find best:

Committing these non-developed file modifications made in the production environment so that the repository resembles the production environment as closely and as often as possible.

Generally ignoring the non-developed production environment alterations, placing confidence in backups to restore the production environment should it be harmed, and keeping a resolution to avoid pushing developments through the promotion hierarchy in the reverse direction (avoiding pushing from prod to dev), only committing the files found in the production environment if they were absolutely necessary in other environments for development.

So, 1 or 2, and why?

PS - I am currently slightly biased toward maintaining production environment to repository resemblance (option 1), but I keep an open mind and would accept an answer supporting either.

答:
I'll go with "Save early, save often."  Or, in this case, "Commit early, commit often."

Your #1 approach seems sensible, provided you get the granularity right. In any coding context, check-ins are done when they makes sense. It may not make sense to create six new control revisions for minor spelling errors, in the name of near-real-time fidelity.

On the other hand, your #2 approach seems destined to fail, if for no other reason than it has the words "confidence in backups" in it.  [shudder]  It also seems to run afoul of the decision-maker's instincts to put these files into source control in the first place.


问:
Why do websites restrict the number & choice of characters in a password?
Registering on an insurance company's website right now, and my password is 16 characters long, using a nice variety of letters, numbers, special characters, etc. However, here's their list of restrictions:

Note your password:

must be between 6 and 12 characters

must not contain spaces, special/international characters

must not contain your user name, first name or last name

is case-sensitive

should contain at least 1 number and 1 letter

I can understand minimum 6 characters, not allowing parts of your name, being case-sensitive, and needing at least 1 number and letter. The part I don't get is restricting your choice of characters you can use, and having an upper bound.

Why do websites do this? The only thing I can think of it they don't know the basics of hashing a password, which would secure it better than anything, and get rid of any security concerns.

If I choose to type DELETE FROM users WHERE 1=1 as my password, I should be allowed to. PHP's MD5 hash of it becomes fe5d54132b51b7d65ab89b739b600b4b which I don't think will harm anything.

答:
Not that I agree with the password restriction in this case, but generally allowing full set of unicode characters for password might introduce some problems. E.g. if the system allows retrieving password via email through some validation mechanism, the password might not get rendered properly in the email client due to lack of unicode support.

As for why spaces and other special characters are no allowed, e.g. in the password retrieval email:

Your password is :actually something else, not this one

Ermm... confusing yea?

vs

Your password is ActuallySomethingElseNotThis1

ContentLicense: CC BY-SA 2.5


答:
If the application is creating its own files, separate from those the developers create, you are essentially talking about using your development source control as a backup system. There are no advantages over any other kind of backup system and you're allowing files to be edited by people who don't understand source control. This seems dangerous to me.

Now that doesn't mean that you shouldn't take a copy of these files every now and then and deploy them to dev, just to keep the systems in sync, so that your tests are a more valid reproduction of production. Just don't do that through source control and your normal build process. If you did then what would happen if you start a build and then the application edits a file that is then overwritten by the deployment?

Another option, of course, is to put them in their own source control and give bi-directional control to the application (in essence, use VCS as a database for your application). This way you can handle revision history and such without having it all mixed up with the developers' changes. DVCS would be good for this, so that you can make changes on one environment and then push them to another -- perhaps even have a content-test environment where you can make changes, test them, then push them to both production and the application-test environment.

Even if the files edited by the application are the same files edited by developers, and thus they need to be merged, if the files are binary and edited often, I'd have to think very hard about the consequences with respect to the size of my source control database.

If they were text then fair enough but, unless I was very sure of the people making changes, I would again want to use a DVCS and make sure the application commits to a clone of the database, just so that I can pull them to a developer's machine and check them before committing to the master build database.

Title: Which is more important in a web application code promotion hierarchy? production environment to repo resemblance or unidirectional propagation?

Body:
Lets say you have a code promotion hierarchy consisting of several environments, (the polar end) two of which are development (dev) and production (prod).

Lets say you also have a web application where important (but not developer controlled) files are created (and perhaps altered) in the production environment.

Lets say that you (or someone above you) decided that the files which are controlled/created/altered/deleted in the production environment needed to go into the repository.

Which of the following two sets of practice / approaches do you find best:

Committing these non-developed file modifications made in the production environment so that the repository resembles the production environment as closely and as often as possible.

Generally ignoring the non-developed production environment alterations, placing confidence in backups to restore the production environment should it be harmed, and keeping a resolution to avoid pushing developments through the promotion hierarchy in the reverse direction (avoiding pushing from prod to dev), only committing the files found in the production environment if they were absolutely necessary in other environments for development.

So, 1 or 2, and why?

PS - I am currently slightly biased toward maintaining production environment to repository resemblance (option 1), but I keep an open mind and would accept an answer supporting either.


问:
Question about modeling with MVC (the pattern, not the MS stuff / non web)
I'm working on an application in which I'm looking to employ the MVC pattern, but I've come up against a design decision point I could use some help with.

My application is going to deal with the design of state-machines. Currently the MVC model holds information about the machine's states, inputs, outputs, etc. The view is going to show a diagram for the machine, graphically allowing the user to add new states, establish transitions, and put the states in a pleasing arrangement, among other things.

I would like to store part of the diagram's state (e.g. the x and y state positions) when the machine information is stored for later retrieval, and am wondering how best to go about structuring the model(s?) for this.

It seems like this UI information is more closely related to the view than to the state-machine model, so I was thinking that a secondary model might be in order, but I am reluctant to pursue this route because of the added complexity. Adding this information to the current model doesn't seem the right way to go about it either.

This is the my first time using the MVC pattern so I'm still figuring things out. Any input would be appreciated.

答:
You have two models

one model is the state-machine: inputs, outputs, states, transitions, et al

the other model is the presentation/rendering of a state-machine: icons, x/y/z coordinates, fonts, scales, etc.


答:
Why are so many languages passed by value?

The point of breaking up large programs into small subroutines is that you can reason about the subroutines independently. Pass-by-reference breaks this property. (As does shared mutable state.)

Even languages where you have explicit pointer manipulation like C it's always passed by value (you can pass them by reference but that's not the default behavior).

Actually, C is always pass-by-value, never pass-by-reference. You can take an address of something and pass that address, but the address will still be passed by value.

What is the benefit of this, why are so many languages passed by values and why are others passed by reference ?

There are two main reasons for using pass-by-reference:

simulating multiple return values

efficiency

Personally, I think #1 is bogus: it's almost always an excuse for bad API and/or language design:

If you need multiple return values, don't simulate them, just use a language which supports them.

You can just as well simulate multiple return values by packaging them into some lightweight data structure such as a tuple. This works particularly well if the language supports pattern matching or destructuring bind. E.g. Ruby:

```<code>def foo
  # This is actually just a single return value, an array: [1, 2, 3]
  return 1, 2, 3
end

# Ruby supports destructuring bind for arrays: a, b, c = [1, 2, 3]
one, two, three = foo
</code>```

Oftentimes, you don't even need multiple return values. For example, one popular pattern is that the subroutine returns an error code and the actual result is written back by reference. Instead, you should just throw an exception if the error is unexpected or return an Either<Exception, T> if the error is expected. Another pattern is to return a boolean which tells whether the operation was successful and return the actual result by reference. Again, if the failure is unexpected, you should throw an exception instead, if the failure is expected, e.g. when looking up a value in a dictionary, you should return a Maybe<T> instead.

Pass-by-reference may be more efficient than pass-by-value, because you don't have to copy the value.

(I understand Haskell is passed by reference though I'm not sure).

No, Haskell is not pass-by-reference. Nor is it pass-by-value. Pass-by-reference and pass-by-value are both strict evaluation strategies, but Haskell is non-strict.

In fact, the Haskell Specification doesn't specify any particular evaluation strategy. Most Hakell implementations use a mixture of call-by-name and call-by-need (a variant of call-by-name with memoization), but the standard doesn't mandate this.

Note that even for strict languages, it doesn't make sense to distinguish between pass-by-reference or pass-by-value for functional languages since the difference between them can only be observed if you mutate the reference. Therefore, the implementor is free to chose between the two, without breaking the semantics of the language.

Body:
Even languages where you have explicit pointer manipulation like C it's always passed by value (you can pass them by reference but that's not the default behavior).

What is the benefit of this, why are so many languages passed by values and why are others passed by reference ? (I understand Haskell is passed by reference though I'm not sure).

Body:
Why are so many languages passed by value?

The point of breaking up large programs into small subroutines is that you can reason about the subroutines independently. Pass-by-reference breaks this property. (As does shared mutable state.)

Even languages where you have explicit pointer manipulation like C it's always passed by value (you can pass them by reference but that's not the default behavior).

Actually, C is always pass-by-value, never pass-by-reference. You can take an address of something and pass that address, but the address will still be passed by value.

What is the benefit of this, why are so many languages passed by values and why are others passed by reference ?

There are two main reasons for using pass-by-reference:

simulating multiple return values

efficiency

Personally, I think #1 is bogus: it's almost always an excuse for bad API and/or language design:

If you need multiple return values, don't simulate them, just use a language which supports them.

You can just as well simulate multiple return values by packaging them into some lightweight data structure such as a tuple. This works particularly well if the language supports pattern matching or destructuring bind. E.g. Ruby:

def foo
  # This is actually just a single return value, an array: [1, 2, 3]
  return 1, 2, 3
end

# Ruby supports destructuring bind for arrays: a, b, c = [1, 2, 3]
one, two, three = foo

Oftentimes, you don't even need multiple return values. For example, one popular pattern is that the subroutine returns an error code and the actual result is written back by reference. Instead, you should just throw an exception if the error is unexpected or return an Either<Exception, T> if the error is expected. Another pattern is to return a boolean which tells whether the operation was successful and return the actual result by reference. Again, if the failure is unexpected, you should throw an exception instead, if the failure is expected, e.g. when looking up a value in a dictionary, you should return a Maybe<T> instead.

Pass-by-reference may be more efficient than pass-by-value, because you don't have to copy the value.

(I understand Haskell is passed by reference though I'm not sure).

No, Haskell is not pass-by-reference. Nor is it pass-by-value. Pass-by-reference and pass-by-value are both strict evaluation strategies, but Haskell is non-strict.

In fact, the Haskell Specification doesn't specify any particular evaluation strategy. Most Hakell implementations use a mixture of call-by-name and call-by-need (a variant of call-by-name with memoization), but the standard doesn't mandate this.

Note that even for strict languages, it doesn't make sense to distinguish between pass-by-reference or pass-by-value for functional languages since the difference between them can only be observed if you mutate the reference. Therefore, the implementor is free to chose between the two, without breaking the semantics of the language.


答:
Call-by-value and call-by-reference are implementation techniques that were mistaken for parameter-passing modes a long time ago.

In the beginning, there was FORTRAN.  FORTRAN only had call-by-reference, since subroutines had to be able to modify their parameters, and computing cycles were too expensive to allow multiple parameter-passing modes, plus not enough was known about programming when FORTRAN was first defined.

ALGOL came up with call-by-name and call-by-value.  Call-by-value was for things that were not supposed to be changed (input parameters).  Call-by-name was for output parameters.  Call-by-name turned out to be a major crock, and ALGOL 68 dropped it.

PASCAL provided call-by-value and call-by-reference.  It did not provide any way for the programmer to tell the compiler that he was passing a large object (usually an array) by reference, to avoid blowing the parameter stack, but that the object should not be changed.

PASCAL added pointers to the language design lexicon.

C provided call-by-value, and simulated call-by-reference by defining a kludge operator to return a pointer to an arbitrary object in memory.

Later languages copied C, mostly because the designers had never seen anything else.  This is probably why call-by-value is so popular.

C++ added a kludge on top of the C kludge to provide call-by-reference.

Now, as a direct result of call-by-value vs. call-by-reference vs. call-by-pointer-kludge, C and C++ (programmers) have horrible headaches with const pointers and pointers to const (read-only) objects.

Ada managed to avoid this whole nightmare.

Ada does not have explicit call-by-value vs. call-by-reference.  Rather, Ada has in parameters (which may be read but not written), out parameters (which MUST be written before they can be read), and in out parameters, which may be read and written in any order.  The compiler decides whether a particular parameter is passed by value or by reference: it is transparent to the programmer.

Title: Why are so many languages passed by value?


答:
I would go with option 2.

Separation of concerns makes me think that features and functionality should be as independent of content as possible.

Also backups are for restoring an environment into a production state, ie a harddrive dies ect.. If the backup is the development environment (or even test/staging) and someone has committed a half baked feature.. you can not restore your production environment.


问:
Reporting in Visual Studio 2010 Express
I want to download Visual Studio 2010 Express Edition to learn all that is new in it. I find it insufficient as there is no Crystal Reports integration in it. Apart from that I want to learn other enterprise features that are bundled with the Professional Edition.

If I download the VS 2010 Professional Edition, it is just limited to 90 days. Is there any other alternative for learners?

Also, is there any FREE alternative for reporting in Express Edition.

答:
The problem is that most reporting packages are commercial.  That being said, have you thought about programs like Bizspark and websitespark that offer free software licenses?  There are requirements to enroll, but from the sounds of it you should be eligible.  Here are the links -
http://www.microsoft.com/bizspark/ and http://www.bizspark.com/Programs/Pages/WebsiteSpark.aspx</p>

Title: Reporting in Visual Studio 2010 Express


答:
You clearly have 2 options:

If the UI info is just a few things, the best approach is to unite both "models" and avoid unncessesary complexity.

If the UI info is large, create a UI Model should be the correct choice.

It's understandable your doubt in this matter, is a common one. That UI info needs to persisted, so you need some kind of "model" representing the view info to load when the editor loads. Programmatically you could relate both models by an id.

Hope it helps!

Title: Question about modeling with MVC (the pattern, not the MS stuff / non web)

Body:
I'm working on an application in which I'm looking to employ the MVC pattern, but I've come up against a design decision point I could use some help with.

My application is going to deal with the design of state-machines. Currently the MVC model holds information about the machine's states, inputs, outputs, etc. The view is going to show a diagram for the machine, graphically allowing the user to add new states, establish transitions, and put the states in a pleasing arrangement, among other things.

I would like to store part of the diagram's state (e.g. the x and y state positions) when the machine information is stored for later retrieval, and am wondering how best to go about structuring the model(s?) for this.

It seems like this UI information is more closely related to the view than to the state-machine model, so I was thinking that a secondary model might be in order, but I am reluctant to pursue this route because of the added complexity. Adding this information to the current model doesn't seem the right way to go about it either.

This is the my first time using the MVC pattern so I'm still figuring things out. Any input would be appreciated.


问:
What's the term for re-implementing an old API in terms of a newer API
The reason for doing it is to solve the case when a newer API is no longer backwards compatible with an older API.

To explain, just say that there is an old API v1.0. The maker of this API decides it is broken and works on a new API v1.1 that intentionally breaks compatibility with the old API v1.0. Now, any programs written against the old API cannot be recompiled as-is with the new API.

Then lets say there is a large app written against the old API and the developer doesn't have access to the source code. A solution would be to re-implement a "custom" old API v1.0 in terms of the new API v1.1 calls. So the "custom" v1.0 API is actually keeping the same interface/methods as the v1.0 API but inside its implementation it is actually making calls to the new API v1.1 methods.

So the large app can be then compiled and linked against the "custom" v1.0 API and the new v1.1 API without any major source code changes.

Is there a term for this practice?

There's a recent example of this happening in Jamie Zawinski's port of XScreenSaver to the iPhone - he re-implemented the OpenGL 1.3 API in terms of the OpenGL ES 1.1 API. In this case, OpenGL 1.3 represents the "old" API and OpenGL ES 1.1 represents the "new" API.

答:
If I understand you right, you'd be implementing the adapter pattern to isolate the API calls from the rest of your application. So when the time came to switch from v1.0 to v1.1, you'd just modify your API wrapper implementation to make different calls and the rest of your application wouldn't know or care.

So your application structure would look something like this:

```<code>.----------.       .-------------.       .----------.
| Your App | ----> | API Wrapper | ----> | API v1.0 |
'----------'       '-------------'       '----------'
                              |
                              |          .----------.
                              `--------> | API v1.1 |
                                         '----------'
</code>```

Body:
If I understand you right, you'd be implementing the adapter pattern to isolate the API calls from the rest of your application. So when the time came to switch from v1.0 to v1.1, you'd just modify your API wrapper implementation to make different calls and the rest of your application wouldn't know or care.

So your application structure would look something like this:

.----------.       .-------------.       .----------.
| Your App | ----> | API Wrapper | ----> | API v1.0 |
'----------'       '-------------'       '----------'
                              |
                              |          .----------.
                              `--------> | API v1.1 |
                                         '----------'


问:
A programmer should concentrate on at least how many languages?
For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>

答:
When you're not a native English speaker, at least you must concentrate in improving your English. I'm saying that based on my experience. Understanding that language helped me a lot.

All good materials(books, articles, code, etc.) for learning programming languages, technologies and new concepts are written in English.


问:
arrays format (Javascript)
I have a list of users, with minions, something like this:

```<code>User52:
       minion10
       minion12
User32:
      minion13
      minion11
</code>```

I've been keeping in an array where the "location" is the id, like this:

```<code>Users:
       [52]User
               minions:
                       [10]minion
                       [12]minion
       [32]User
               minions:
                       [13]minion
                       [11]minion
</code>```

so I can access them easily like this: user[UserID].minions[MinionID] (ex: user[32].minions[11]).

But when I print it or send it by json I get something like this:

```<code>{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,minion,,,,,,,,,,,,,,minion}
</code>```

But should I keep using like this or should I change to something like this:

```<code>User = function(){
   this.minions = ...;
   this.getMinion = function(value){
     for(var m in this.minions){
      if(this.minions[m].id == value){
         return this.minions[m];
         break;
      }
     }
   }
}
</code>```

and get it like this:

```<code>user.getMinion(MinionID);
</code>```

Question: I get better performance using a "short" array but using loops every time I need a minion, or using "long" arrays, but no need for loop and getting values directly from the id "name"?

答:
Mr. Melo raise a good question for JavaScript Object Access Pattern.
I leave the prior 'introductory' answer for others to interpret your code.

My answer is to override a print method, and another way, to convert the data into a human-readible data-translation.

when print it or send it by json you get non sensible output:

{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,minion,,,,,,,,,,,,,,minion}

Here is where I can give a suggestion.
What you are seeing above is the Object-Literal converted to string. Perhaps nested in a JSON.stringify() method or another perhaps toString() use. You can improve this with two potential solutions depending on your context.

A ToString Method Override. - One solution is to dig into the function (step-debug) 'down-into' the method that is converting your object to String, and copy, rename, and change it to yourOwnStringifyMethod(). This is an essentially a toString() method override. Instead of printing

","+","+","+data+",",

override it to print something else. Call it minion.minionToString() or something.

Indices could easily be inserted in the iterator to produce:

{0,1,2,data,...}

Or Print the id of a minion by printing the data-members like +minion.name+. Search for toString override, this would be perhaps ideal, if you are transferring the JSON asynchronously, or real-time web-sockets, and just want to translate the data.

B. Templates. If the data is to be viewed on screen, instead of transferred, data-bind it from json to a template. Data-binding is great. The syntax is something like var arg = " ...
<%data-field*>
" Then you send that into a templ(arg) function, for example, and it spits out a var x = templ(htmltemplate, data-stream). Var x is now your template-data-loaded-html to be inserted into the dom.

There are a number of ways to do this.

C. This is an interesting incarnation of code where you hint:

i've been keeping in an array where the "location" is the id

That reminds me somehow of CouchDB. CouchDB and Mongo are JavaScript Databases, that use JSON objects persisted over time by a long unique ID. Maybe this will help you evolve an accessor and display best-practice.

D. The lookup function loop looks potentially costly for very-large data-sets. There are certain indexing and search algorithms that can cut down on processing iterations if you are running a high number of minions, and wish to optimize lookup. Paul Irish wrote a book, or paper, on 10 things that I learned by reading jQuery source code. I imagine there is some advanced fruit in there about efficient dom node traversal, which could, in the least, be enlightening to your armament of minions.

Hope that helps.
All the best!
Nash

Title: arrays format (Javascript)

Body:
Mr. Melo raise a good question for JavaScript Object Access Pattern.
I leave the prior 'introductory' answer for others to interpret your code.

My answer is to override a print method, and another way, to convert the data into a human-readible data-translation.

when print it or send it by json you get non sensible output:

{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,minion,,,,,,,,,,,,,,minion}

Here is where I can give a suggestion.
What you are seeing above is the Object-Literal converted to string. Perhaps nested in a JSON.stringify() method or another perhaps toString() use. You can improve this with two potential solutions depending on your context.

A ToString Method Override. - One solution is to dig into the function (step-debug) 'down-into' the method that is converting your object to String, and copy, rename, and change it to yourOwnStringifyMethod(). This is an essentially a toString() method override. Instead of printing

","+","+","+data+",",

override it to print something else. Call it minion.minionToString() or something.

Indices could easily be inserted in the iterator to produce:

{0,1,2,data,...}

Or Print the id of a minion by printing the data-members like +minion.name+. Search for toString override, this would be perhaps ideal, if you are transferring the JSON asynchronously, or real-time web-sockets, and just want to translate the data.

B. Templates. If the data is to be viewed on screen, instead of transferred, data-bind it from json to a template. Data-binding is great. The syntax is something like var arg = " <html>...<div><%data-field*></div></html>" Then you send that into a templ(arg) function, for example, and it spits out a var x = templ(htmltemplate, data-stream). Var x is now your template-data-loaded-html to be inserted into the dom.

There are a number of ways to do this.

C. This is an interesting incarnation of code where you hint:

i've been keeping in an array where the "location" is the id

That reminds me somehow of CouchDB. CouchDB and Mongo are JavaScript Databases, that use JSON objects persisted over time by a long unique ID. Maybe this will help you evolve an accessor and display best-practice.

D. The lookup function loop looks potentially costly for very-large data-sets. There are certain indexing and search algorithms that can cut down on processing iterations if you are running a high number of minions, and wish to optimize lookup. Paul Irish wrote a book, or paper, on 10 things that I learned by reading jQuery source code. I imagine there is some advanced fruit in there about efficient dom node traversal, which could, in the least, be enlightening to your armament of minions.

Hope that helps.
All the best!
Nash


问:
How to properly document functionality in an agile project?
So recently, we've just finished the first phase of our project.

We used agile with fortnightly sprints. And whilst the application turned out well, we're now turning our eyes on some of the maintenance tasks.

One maintenance task is that all of our documentation appears in the form of specs. These specs describe 1 or more stories and generally are a body of work which a few devs could knock over in a week.

For development, that works really well - every two weeks, the devs get handed a spec and it's a nice discrete chunk of work that they can just do.

From a documentation point of view, this has become a mess. The problem with writing specs that are focused on delivering just-in-time requirements to developers is we haven't placed much emphasis on the big picture.

Specs come from all different angles - it could be describing a standard function, it could describing parts of a workflow, it could be describing a particular screen...

And now, we have business rules about our application scattered across 120 documents. Looking for any document for a particular business rule or function in particular is quite hard because you don't know which document has this information, and making a change request is equally hard because once again, we are unsure about which spec to make the change.

So we have maybe a couple of weeks of lull before it's back to specing out functionality for the next phase but in this time, I'd like to re-visit our processes. I think the way we have worked so far in terms of delivering fortnightly specs works well.

But we also need a way to manage our documentation so that our business rules for a given function / workflow are easy to locate / change.

I have two ideas.

One is we compile all of our specs into a series of master specs broken by a few broad functional areas. The specs describe the sprint, the master spec describe the system. The only problem I can see is
1) Our existing 120 specs are not all neatly defined into broad functional areas. Some will require breaking up, merging etc. which will take a lot of time.
2) We'll be writing specs and updating master specs in each new sprint. Seems like double the work, and then do the devs look at the spec or the master spec?

My other suggestion is to concede that our documentation is too big of a mess, and manage that mess going forward. So we go through each spec, assign like keywords to it, and then when we want to search for a function, we search for that keyword. Problems I can see
1) Still the problem of business rules scattered everywhere, keywords just make it easier to find it.

anyway, if anyone has any decent ideas or any experience to share about how best to manage documentation, would really appreciate it.

答:
The spec should be your unit tests and knowledge of developers. There should be no "document", that describes what software should do. You probably mistaked user story cards, that many agile developers use for some kind of "spec". But those are short-lived and only used for comunication before this user story gets turned into code. It is thrown away afterwards.

I would question using spec as user stories. I would prefer a system, where business experts have their own document, that describes what the system does, but this document is only theirs. They don't pass it to programmers as "what to develop", they only use it to keep track of what the sytem does. So if they want to change anything in software, they need to create real user story, pass that to developers and update their own document after it is finished.

And I would recomend you looking at Domain-driven development/design. I believe it would be good fit for your problem.


答:
Your questions sounds like a rant on something that you thought it would be an agile way of documentation.

Agile documentation doesn't mean creating a huge mess, where it would be difficult to find necessary information, but it means creating structured (only necessary) documentation.

You haven't said how far you are in the project, also how big it is, but paying that part of technical dept would be good on long run. Therefor, my suggestion is to invest some time, and do what you have to do to make it good. That also means adapting some rules how to write specs, where to store them, etc. so in the future you do not run into same problems.

In order to fix the mess :

form a directory structure, and put right documents in proper directories. You can divide into architecture, high level design, user stories, testing, and whatever is required

divide user stories (is that what spec is for you?) by functionality in such a way that it is easy to find every piece of information

make nice document naming scheme. Do not put some generic G562GDVKASDF235.doc type naming, but for example maingui_panel1.doc, maingui_screenorganization.doc, etc. This way you do not need a document that converts document name into what information is needed.

write some overview document explaining what to find where, naming scheme, etc

add document templates

Title: How to properly document functionality in an agile project?

Body:
So recently, we've just finished the first phase of our project.

We used agile with fortnightly sprints. And whilst the application turned out well, we're now turning our eyes on some of the maintenance tasks.

One maintenance task is that all of our documentation appears in the form of specs. These specs describe 1 or more stories and generally are a body of work which a few devs could knock over in a week.

For development, that works really well - every two weeks, the devs get handed a spec and it's a nice discrete chunk of work that they can just do.

From a documentation point of view, this has become a mess. The problem with writing specs that are focused on delivering just-in-time requirements to developers is we haven't placed much emphasis on the big picture.

Specs come from all different angles - it could be describing a standard function, it could describing parts of a workflow, it could be describing a particular screen...

And now, we have business rules about our application scattered across 120 documents. Looking for any document for a particular business rule or function in particular is quite hard because you don't know which document has this information, and making a change request is equally hard because once again, we are unsure about which spec to make the change.

So we have maybe a couple of weeks of lull before it's back to specing out functionality for the next phase but in this time, I'd like to re-visit our processes. I think the way we have worked so far in terms of delivering fortnightly specs works well.

But we also need a way to manage our documentation so that our business rules for a given function / workflow are easy to locate / change.

I have two ideas.

One is we compile all of our specs into a series of master specs broken by a few broad functional areas. The specs describe the sprint, the master spec describe the system. The only problem I can see is
1) Our existing 120 specs are not all neatly defined into broad functional areas. Some will require breaking up, merging etc. which will take a lot of time.
2) We'll be writing specs and updating master specs in each new sprint. Seems like double the work, and then do the devs look at the spec or the master spec?

My other suggestion is to concede that our documentation is too big of a mess, and manage that mess going forward. So we go through each spec, assign like keywords to it, and then when we want to search for a function, we search for that keyword. Problems I can see
1) Still the problem of business rules scattered everywhere, keywords just make it easier to find it.

anyway, if anyone has any decent ideas or any experience to share about how best to manage documentation, would really appreciate it.


问:
Recognizing text fields according to their label value
I have an application who has text fields (not select, not checkbox or other types) where an user can enter some value, like this:

ISBN and E-Mail are the label of each input.

Now I have to automatically test these inputs according to their label. The question is: how to recognize that, for example, the first input requires an ISBN code? I programmed something like this:

turn the label value to lowercase

check if the label value contains isbn

if so set the field value to a random ISBN code (i.e.: 1234567890), else set it to a random value (default)

For the email field:

turn the label value to lowercase

check if the label value contains e-mail or email or mail

if so set the field value to a random email (i.e.: abcd@abcd.com), else set it to a random value (default)

And so on for each text field I encounter.

Is that reliable? How can I improve the "recognizing part"? I know only the label value and the field value (what is already written in the field by default) for each text input.

答:
As for the correctness of your feature, it simply is not. In fact, it cannot be.

Trivial counter-example: Someone creates the label "Do not enter E-mail or ISBN here, but your name:"

The problem is that you should not have to guess which textfield is for which purpose, but the text-field itself should contain this information for various reasons.

For example, if you have a textfield for ISBNs, you do not want a keypress for a non-digit-character to even appear (with the possible exception of the - and X characters maybe).

The main problem is how to add this semantic information to the text-fields such that you can access it in the test framework. This of course depends on the specific implementation tools being used. Examples include:

HTML: assign a class/id/name-attribute to the input tag (look f.ex. at the source code of the google login page. This is used as the basis of how your browser knows in which text field it should auto-complete your e-mail address)

GUI API: If you create an instance of some TextField widget, you can create subclasses for the different semantical purposes, like an EMailTextField, and instantiate that. By reflecting on the dynamic type of the textfields, your tests can then determine what kind of textfield it is, and additionally, the implementation can easily realize semantic-dependant behaviors (like disallowing certain characters to be entered, etc.)


答: It comes down to their programmers (or their management) being lazy and/or uneducated.  It doesn't take that much more work to make your system accept any characters, but it means you need to spend some time thinking about SQL injection attacks, cross site scripting, making sure that all parts of the system are able to deal with it, etc.  It can be cheaper and quicker just to forbid any characters that could be a problem.</p>

Title: Why do websites restrict the number & choice of characters in a password?

Body:
Registering on an insurance company's website right now, and my password is 16 characters long, using a nice variety of letters, numbers, special characters, etc. However, here's their list of restrictions:

Note your password:

must be between 6 and 12 characters

must not contain spaces, special/international characters

must not contain your user name, first name or last name

is case-sensitive

should contain at least 1 number and 1 letter

I can understand minimum 6 characters, not allowing parts of your name, being case-sensitive, and needing at least 1 number and letter. The part I don't get is restricting your choice of characters you can use, and having an upper bound.

Why do websites do this? The only thing I can think of it they don't know the basics of hashing a password, which would secure it better than anything, and get rid of any security concerns.

If I choose to type DELETE FROM users WHERE 1=1 as my password, I should be allowed to. PHP's MD5 hash of it becomes fe5d54132b51b7d65ab89b739b600b4b which I don't think will harm anything.


问:
Should a software developer get a yearly equipment budget?
I am looking at a new position with a new company.  I have talked to some people in the past (in general, not at this company) that they had been given a yearly budget to buy new computer stuff to keep up to date.

Now why I feel this question is worth asking here is that Joel comes right out and says an employer should pay for the best equipment money can buy... within reason of course.

From The Joel Test: 12 Steps to Better Code

9. Do you use the best tools money can buy?

Writing code in a compiled language is one of the last things that still can't be done instantly on a garden variety home computer...

Top notch development teams don't torture their programmers. Even minor frustrations caused by using underpowered tools add up, making programmers grumpy and unhappy. And a grumpy programmer is an unproductive programmer...

Does anyone know if the industry has such a standard to offer an allowance or budget?

I have never worked for a company like this, but I am thinking I should toss this in the ring for negotiations.  Seems reasonable.  How do bigger companies like MS, Google, and Apple handle this?  If you say yes, give a range... I have been told numbers from $5k to $10k.  Seems high to me, but hey I would gladly take it.

答:
Yearly engineers salaries are high, therefore investing in equipment is good. 5-10k$ is nothing, if it is going to be used well.

To quote author of boost MSM library :

Compilation times of state machines with > 80 transitions that are
  going to make you storm the CFO's office and make sure you get a shiny
  octocore with 12GB RAM by next week, unless he's interested in paying
  you watch the compiler agonize for hours... (Make sure you ask for
  dual 24" as well, it doesn't hurt).

However, if the current equipment is still good, I do not see a point in wasting money.


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
Zero Blocking

BUT have a clean convention in place at office and educate new developers(even old ones) about the perils of having to clean up damages due to the perils of viruses and attacks.
Good developers will follow , mainly by a sense of righteousness to do the right thing for their company. Bad ones wont and shouldnt have been hired in the first place.


答:
I guess it depends on the environment you're working in. Take Delphi for instance, blazingly fast compile times so speed of computer matters less. Screen realestate does.

Also, while giving new tools is nice, don't underestimate the time lost when setting up a new computer, configuring your settings like they were before. The things just not working.

Title: Should a software developer get a yearly equipment budget?

Body:
I am looking at a new position with a new company.  I have talked to some people in the past (in general, not at this company) that they had been given a yearly budget to buy new computer stuff to keep up to date.

Now why I feel this question is worth asking here is that Joel comes right out and says an employer should pay for the best equipment money can buy... within reason of course.

From The Joel Test: 12 Steps to Better Code

9. Do you use the best tools money can buy?

Writing code in a compiled language is one of the last things that still can't be done instantly on a garden variety home computer...

Top notch development teams don't torture their programmers. Even minor frustrations caused by using underpowered tools add up, making programmers grumpy and unhappy. And a grumpy programmer is an unproductive programmer...

Does anyone know if the industry has such a standard to offer an allowance or budget?

I have never worked for a company like this, but I am thinking I should toss this in the ring for negotiations.  Seems reasonable.  How do bigger companies like MS, Google, and Apple handle this?  If you say yes, give a range... I have been told numbers from $5k to $10k.  Seems high to me, but hey I would gladly take it.


问:
Are there any standards for preparing a user manual of electronic device?
Are there any standards for preparing a user manual of electronic device?

I am trying to prepare a manual for a device. However, I could not find any format. If I find, I will take this as guide for me.

If there is no standard, what should be in the manual or what should not be in?

答:
The manual should contain whatever the owner of the device needs to know, including but not limited to:

Unpacking: how to unpack it

Operation: how to operate it

Integration: how to use it in conjunction with other devices, if appropriate

Care: how to care for it

Supplies: where to get any supplies that the device requires

Troubleshooting: what to do when it doesn't seem to work

Service: who to contact if it needs repair

Safety: any necessary safety information

Recycling and Disposal: how to get rid of it responsibly

Warrantee: statement of warrantee and any disclaimers or other legalese

Index: a thorough index

If using the device is complicated and/or if the users aren't expected to already be knowledgeable, it may be a good idea to include some examples.

I'm not aware of any general manual-writing standards, but I'm sure that some exist for specific markets. For example, one can easily imagine that you'd have to supply a manual meeting certain criteria if you plan to sell to the military, and certain countries might require that the manual be provided in the official language of that country.

For ideas, take a look at the manuals that came with your car, blender, stereo, DVR, printer, microwave oven, and any other devices you have around your house.


答:
Personally, I would want the company to just sort out the equipment I need, not give me a budget and make me to deal with all the research, negotiation and other hassle that goes into buying and installing corporate hardware.

In the end, all I want to have to do about hardware is state my few requirements, and have someone else do all of that work, so that I can get on with mine.

More important and appropriate (IMHO) is a personal training budget, with which you can buy books and attend courses and conferences.


答:
Say you're working on a project that does a dozen compiles or test builds a day, and each one takes ten minutes.

If you had a better machine, maybe they would only take eight minutes. Or five minutes. And your machine might still be snappy enough to do other stuff so you can keep working while it's building.

Work out how much time you would save every day, add it up for a whole year. Convert it to a dollar value by using your hourly rate.

Surprised yet?


答:
A yearly budget would be nice, but I can see some wastage happening if you have to "use it or lose it". E.g. some years you might need to provision up and spend more than you are allocated but other years you might not need to spend much. So allowing for the budget to rollover into the next year would be essential to the policy.

Another option would be to combine the hardware budget with training, so you can choose to put a portion of it into training and a portion into hardware. Of course a good employer would be placing you on training courses every year anyway, but in my experience this rarely happens.


答: A programmer need to concantrate on programming not on a spesific language/s.

Title: A programmer should concentrate on at least how many languages?

Body: For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>


答:
A yearly individual equipment allowance is a dangerous path to follow:

The manager will expect negligible compilation time, therefore increased productivity.

You will have to deal with all the hassle associated to maintaining a professional equipment, from buying to getting rid of through the many failures that will eventually occur.

What about common equipments? servers, routers, sysadmins, licenced/corporate software... If I were the boss, I would sell these services as a couterpart of allowance.

What about going further? phone allowance, desk, office, coffe machine, electric power, A/C...


问:
How to visualize timer functionality in sequence diagram?
I am developing software for communication with external device through serial port. To better understand the new functionality I am trying to display it in sequence diagram. Flow of events is as follows. I send to the device command to reset it. This is asynchronous operation so there is some delay between request and response (typically 100 ms). There can be case when the answer never comes (for example device is not connected to the specified port or is currently turned off). For this purpose I create a timer with period twice the maximum answer time. In my case it is 2 * 125 ms = 250 ms. If the answer comes in predefined time interval, I destroy already running timer. If the answer doesnt come in predefined interval, timer initiates some action. After this action we can destroy it. How to effectively model this situation in sequence diagram?

Addendum 1:

Based on advices made by scarfridge i drew following UML diagram. Comment by Ozair is also helpful for simplifying the diagram even more.

答:
See this page for how you can model delays between messages in general.

If you want to create a sequence diagram that covers only the positive case, then that's all you need. If you want to cover both possibilities in one diagram, you need to use an alternatives box, where you have one delay that is larger than 250ms and one that is smaller, and then of course, the different reactions you want to perform.


答:
Keep in mind that you are just drawing diagrams. This is not coding in some graphic language. If you use the timer-mechanism in all your communication with the device, just model it once (a suggestion for this can be found at the end of this answer). Leave out the timer in most diagrams. You should model at a specific level of abstraction. Don't leave this level or your diagram will get bloated and readers will miss the point you're trying to make. State clearly what case you are modelling. If communication failure does not matter to the situation, don't model it. If you want to explain behavior after a communication failure, don't model the error free case. If you want to model both, consider using multiple diagrams. And again, state clearly what case you are modelling.

For the actual timer I don't see much of a problem. I suggest you create one lifeline for your timer, one for the device and one for whoever talks to the device (let's call it controller) and the timer. Draw a message "reset" from the controller to the device followed by a message "countdown" from the controller to the timer. If you want to model the case of the answer received, draw a message "reset finished" from the device to the controller. Now the controller tells the timer to stop. In the no response case you can draw a message "time up" from the timer to the controller. You can combine both of these with an alt fragment and guards like "device not connected".

Title: How to visualize timer functionality in sequence diagram?

Body:
I am developing software for communication with external device through serial port. To better understand the new functionality I am trying to display it in sequence diagram. Flow of events is as follows. I send to the device command to reset it. This is asynchronous operation so there is some delay between request and response (typically 100 ms). There can be case when the answer never comes (for example device is not connected to the specified port or is currently turned off). For this purpose I create a timer with period twice the maximum answer time. In my case it is 2 * 125 ms = 250 ms. If the answer comes in predefined time interval, I destroy already running timer. If the answer doesnt come in predefined interval, timer initiates some action. After this action we can destroy it. How to effectively model this situation in sequence diagram?

Addendum 1:

Based on advices made by scarfridge i drew following UML diagram. Comment by Ozair is also helpful for simplifying the diagram even more.


问:
Is micro-optimisation important when coding?
I recently asked a question on Stack Overflow to find out why isset() was faster than strlen() in PHP. This raised questions around the importance of readable code and whether performance improvements of micro-seconds in code were worth even considering.

My father is a retired programmer, and I showed him the responses. He was absolutely certain that if a coder does not consider performance in their code even at the micro level, they are not good programmers.

I'm not so sure - perhaps the increase in computing power means we no longer have to consider these kind of micro-performance improvements? Perhaps this kind of considering is up to the people who write the actual language code? (of PHP in the above case).

The environmental factors could be important - the Internet consumes 10% of the world's energy. I wonder how wasteful a few micro-seconds of code is when replicated trillions of times on millions of websites?

I'd like to know answers preferably based on facts about programming.

Is micro-optimisation important when coding?

My personal summary of 25 answers, thanks to all.

Sometimes we need to really worry about micro-optimisations, but only in very rare circumstances. Reliability and readability are far more important in the majority of cases. However, considering micro-optimisation from time to time doesn't hurt. A basic understanding can help us not to make obvious bad choices when coding such as

```<code>if (expensiveFunction() || counter < X)
</code>```

Should be

```<code>if (counter < X || expensiveFunction())
</code>```

(Example from @zidarsk8) This could be an inexpensive function and therefore changing the code would be micro-optimisation. But, with a basic understanding, you would not have to, because you would write it correctly in the first place.

答:
There's micro-optimisations and micro-optimisations. In VB (both VB6 and VB.NET, but ignoring the IsNullOrEmpty offering from the framework) I always use Len(str) <> 0 rather than str <> "". However, I normally don't "fix" others code where they've used the latter.

Yes, the latter is more readable, but, in this case, the former is not unreadable.

Performance should be a consideration when designing the code, but not at the detrement of readability and maintainability.


答:
Social Networking and anything instant messenger related.

They're so evil and distracting. Too easy to get people out of their "Zone"

Title: What is the right level of site blocking for you as a developer?

Body:
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?


答:
As many as is needed to do your job.

But C# and Java are as close as UK English and US English.  You might learn something new by going for Finnish or Navajo.


问:
Why is it better for a programmer to design the algorithm before starting to write the code?
Does an appropriate algorithm really help improve the quality and ultimately the efficiency of a program?

Can we still produce a good quality program without the algorithm?

Is an appropriate algorithm a MUST in modern programming?

答:
When you sit down and start coding, you have an algorithm in mind, whether "designed" or not.

If you sat down and starting coding with no complete algorithm in mind, you'd be doing one of the following:

1) mashing keys randomly. This will probably produce a compiler error

2) writing compilable code that probably does anything except the thing you want it to do

3) writing code to solve little parts of the problem, and building on it as you go  in an aggregating fashion, but not really thinking ahead -- so eventually the problem is solved -- but the code is not very efficient manner, and with possibility of having to backtrack and wasting time along the way

So people usually program with an algorithm in their head. It may have be fleshed out or reasoned about on paper or some other medium.

It can be good discipline to think about your attack on a problem away from the keyboard, especially in your earlier days as a programmer. As other answers have noted, as you get more experienced, you can get better at coding some more managable chunks of problem "on the fly". However, for difficult or large problems, thinking and designing away from the keyboard is useful: when engaged with code, you're more likely to be thinking in terms of constructs of the language, and in how to approach the most immediate task in the problem. Whereas thinking about the problem with, say, a pen and paper, frees you more from language aspect of the code and lets you think at a higher more abstract level.

OwnerDisplayName: Jervis


答:
Scarfridge's suggestions are very valid, that you need to have a certain abstraction level for graphic diagrams.

You can use the interaction operator negative as depicted in the following diagram.

Reference: http://www.uml-diagrams.org/sequence-diagrams.html


问:
How to get better at solving Dynamic programming problems
I recently came across this question: "You are given a boolean expression consisting of a string of the symbols 'true', 'false', 'and', 'or', and 'xor'. Count the number of ways to parenthesize the expression such that it will evaluate to true. For example, there are two ways to parenthesize 'true and false xor true' such that it evaluates to true."

I knew it is a dynamic programming problem so i tried to come up with a solution on my own which is as follows. Suppose we have a expression as A.B.C.....D where '.' represents any of the operations and, or, xor and the capital letters represent true or false. Lets say the number of ways for this expression of size K to produce a true is N. when a new boolean value E is added to this expression there are 2 ways to parenthesize this new expression  1. ((A.B.C.....D).E) ie. with all possible parenthesizations of A.B.C.....D we add E at the end.
2. (A.B.C.(D.E)) ie. evaluate D.E first and then find the number of ways this expression of size K can produce true.

suppose T[K] is the number of ways the expression with size K produces true then T[k]=val1+val2+val3 where val1,val2,val3 are calculated as follows.

1)when E is grouped with D.

i)It does not change the value of D

ii)it inverses the value of D

in the first case val1=T[K]=N.( As this reduces to the initial A.B.C....D expression ).
In the second case re-evaluate dp[K] with value of D reversed and that is val1.

2)when E is grouped with the whole expression.

//val2 contains the number of 'true' E will produce with expressions which gave 'true' among all parenthesized instances of A.B.C.......D
i) if true.E = true then val2 = N

ii) if true.E = false then val2 = 0

//val3 contains the number of 'true' E will produce with expressions which gave 'false' among all parenthesized instances of A.B.C.......D

iii) if false.E=true then val3=( 2^(K-2) - N ) = M ie. number of ways the expression with size K produces a false [ 2^(K-2) is the number of ways to parenthesize an expression of size K ].

iv) if false.E=false then val3 = 0

This is the basic idea i had in mind but when i checked for its solution http://people.csail.mit.edu/bdean/6.046/dp/dp_9.swf the approach there was completely different. Can someone tell me what am I doing wrong and how can i get better at solving DP so that I can come up with solutions like the one given above myself.

Thanks in advance.

答:
The answer, as with many things, is:

Practice, practice, practice.

By the way, I believe that in your solution you got into a dead-end by making a trivial mistake really early on: "There are 2 ways to parenthesize this new expression" -- aren't there more than 2? How about (A.B.(C.D.E)), for example?


答:
Do not block, but publish the visited URLs and bandwidth consumption.

Of course, you must inform everyone in advance that the URLs that they visit using office network will be viewable by everyone.

Do not block, because you can't predict which sites should be blocked. A site may have suspicious URLs etc but actually contains necessary info for work.

Publish the URLs and bandwidth consumption so you can rely on social control and peer review.


答:
I've never met with such budget. On long-term contracts, the corporations provide the computer stuff and they care if something gets broken. It's more rational than giving the employees the money and expect they will buy for it what they want. What when someone's laptop breaks down? A few days are wasted before he/she gets it repaired or buys new parts etc. When the company manages the hardware, he/she will get replacement for the broken laptop within a few hours.

Another case are contractors/freelancers, which are hired for short term, and they manage their stuff themselves. They handle the repairs themselves and they simply expect the payment will be good enough so that it will be profitable for them.


答:
I can understand prohibiting special characters, but there is no excuse for password length limits.  I use a password manager and like to use ridiculously long passwords.  Since I don't have to remember them or type them, why not?

I can think of only one reason why a site might limit password length.  The people who run the site are afraid that if they let their users use really good passwords, they will forget them more frequently and they will have to field a couple more support calls or emails.  It's a very lame excuse, but it's the only possible reason for such a stupid policy that I can come up with.


答:
I think there are pros and cons (as usual). Having individual equipment budgets can mean a wide variety of hardware, good for debugging, bad for maintenance.

Do the individuals also track the warrantees on the equipment? Time wasted if they do, administrative problem if they don't.

It may depend on your situation. A small/medium sized company selling software into the general market place, then an individual budget may be a good thing, (good for debugging). A large corporattion working on internal software, then individual budgets may be a bad thing (everybody has the same hardware).

There is also the argument that developers should have to test on machines that are about average, so they get he same perfomance as the target user.


问:
Programming for digital photo frames
A project has recently come to my attention, but I have no idea where to start or even if it's possible. The idea revolves around programming a clock that is displayed in a digital photo frame. The user would then be able to put different pictures corresponding to different times inside a USB pen, for example, which would load as soon as you put the USB in.

The project itself would be a really neat project - if it was just on a computer. I have no idea if what I'm talking about is even possible on a digital photo frame and if it is, what language would I use? If anyone can provide any input, it would be great.

My current idea is to maybe have a small device at the back, SSD, that runs the program through a screen, completely bypassing standard digital photo frames, although I don't even know how to begin this.

答:
There are already dpf that display a clock or calendar, some even work in networks. Those are obviously capable of being programmed. Though you would in most cases have to do something similar to jailbraking an iphone or get in contact with the manufacturer of either the device or the chipset/microcontroller.

To start you should find out what technologies are used in such frames. A bit googling (digital photo frame cpu) shows, that for example Samsung builts chips that are used in those devices. Example or some manufacturer here

Next thing is finding out more about those chipsets and how they are programmed. Most likely either C or some proprietary language. Though some may even run Linux.

Just found this post on Stackoverflow where somebody had asked the same question. Seems there are some manufacturers who offer devices designed to be programmed.

Title: Programming for digital photo frames


问:
What does RESTful web applications mean?

Possible Duplicate:

  What is REST (in simple English)

What does RESTful web applications mean?

A web service is a function that can be accessed by other programs over the web (Http). To clarify a bit, when you create a website in PHP that outputs HTML its target is the browser and by extension the human being reading the page in the browser. A web service is not targeted at humans but rather at other programs.

SOAP and REST are two ways of creating WebServices. Correct me if i am wrong?

What are other ways i can create a WebService?

What does it mean fully RESTful web Application?

答:
Yes, the REST design is first meant for services. But your web application is nothing else but offering such a service to your browser application. So if I design an application in a RESTful way, most likely within a MVC framework, my controlers are organized following REST principles.

As an example: I have a shopping cart. To this shopping cart I can add items, can edit or remove them. So I have a controller named CartItem, that implements the REST service and takes the requests from the browser. A 'fully' RESTful Application would have all it interactions organized as resources and RESTful requests. Even a static page has a controller that reacts to the show action.


答:
Please refer to the excellent answers on StackOverflow to the question What exactly is RESTful programming?

Here's some of the major points:

To understand REST, you have to first understand HTTP. The HTTP
protocol is oriented around verbs and resources. The two verbs in
mainstream usage are GET and POST, however, the HTTP standard defines
several other such as PUT and DELETE. These verbs are then applied to
resources.

In a RESTful application you'll never modify data using a GET
request. This is what PUT, POST and DELETE are for. Most web
applications do this all the time, though, and are therefore not
RESTful.

Also, the actual representation retrieved for a resource, returned by
the HTTP response, is dependent on the HTTP Accept headers to control whether you want     XML, HTTP, or even a Java Object representing the requested resource.

The above points are dealing with RESTful web applications, which is a specific implementation (over HTTP) of the more general REST architectural style, which was originated in a dissertation by Roy Fielding.

Body:
Possible Duplicate:

  What is REST (in simple English)

What does RESTful web applications mean?

A web service is a function that can be accessed by other programs over the web (Http). To clarify a bit, when you create a website in PHP that outputs HTML its target is the browser and by extension the human being reading the page in the browser. A web service is not targeted at humans but rather at other programs.

SOAP and REST are two ways of creating WebServices. Correct me if i am wrong?

What are other ways i can create a WebService?

What does it mean fully RESTful web Application?


答:
I agree with occulus that practice is most required, also would like to add that you need to pay attention in recognizing the patterns in problems that can be solved using DP (this is explained pretty well in CLRS)

You can find spoj problems that involve dynamic programming here :)

Title: How to get better at solving Dynamic programming problems

Body:
I recently came across this question: "You are given a boolean expression consisting of a string of the symbols 'true', 'false', 'and', 'or', and 'xor'. Count the number of ways to parenthesize the expression such that it will evaluate to true. For example, there are two ways to parenthesize 'true and false xor true' such that it evaluates to true."

I knew it is a dynamic programming problem so i tried to come up with a solution on my own which is as follows. Suppose we have a expression as A.B.C.....D where '.' represents any of the operations and, or, xor and the capital letters represent true or false. Lets say the number of ways for this expression of size K to produce a true is N. when a new boolean value E is added to this expression there are 2 ways to parenthesize this new expression  1. ((A.B.C.....D).E) ie. with all possible parenthesizations of A.B.C.....D we add E at the end.
2. (A.B.C.(D.E)) ie. evaluate D.E first and then find the number of ways this expression of size K can produce true.

suppose T[K] is the number of ways the expression with size K produces true then T[k]=val1+val2+val3 where val1,val2,val3 are calculated as follows.

1)when E is grouped with D.

i)It does not change the value of D

ii)it inverses the value of D

in the first case val1=T[K]=N.( As this reduces to the initial A.B.C....D expression ).
In the second case re-evaluate dp[K] with value of D reversed and that is val1.

2)when E is grouped with the whole expression.

//val2 contains the number of 'true' E will produce with expressions which gave 'true' among all parenthesized instances of A.B.C.......D
i) if true.E = true then val2 = N

ii) if true.E = false then val2 = 0

//val3 contains the number of 'true' E will produce with expressions which gave 'false' among all parenthesized instances of A.B.C.......D

iii) if false.E=true then val3=( 2^(K-2) - N ) = M ie. number of ways the expression with size K produces a false [ 2^(K-2) is the number of ways to parenthesize an expression of size K ].

iv) if false.E=false then val3 = 0

This is the basic idea i had in mind but when i checked for its solution http://people.csail.mit.edu/bdean/6.046/dp/dp_9.swf the approach there was completely different. Can someone tell me what am I doing wrong and how can i get better at solving DP so that I can come up with solutions like the one given above myself.

Thanks in advance.