答:
The visitor pattern isn't meant to extend the functionality of some class. It is a pattern that provides an elegant way to operate on some data (e.g. to traverse it) while the visitor can keep state and handle different types of data differently.

For example consider a pseudo-DOM where we want to collect all headlines, in a language with type-overloaded methods:

```<code>class CollectHeadlinesVisitor {
  List<String> headlines = new List<>();

  public void visit(Node n) {
    for (Node child in n.childs()) {
      this.visit(child);
    }
  }

  public void visit(Headline h) {
    list.add(h.text());

    for (Node child in n.childs()) {
      this.visit(child);
    }
  }

  public List<String> value() {
    return headlines;
  }
}
</code>```

Note that in a language without type overloads we have to do the accept/visit_Type indirection.

The above example can't be implemented by adding methods to Node and Headline as a place is needed to store the discovered headlines.

Adding methods to the existing data classes would also violate the Single Responsibility Principle and could lead to namespace issues, e.g. when two pieces of code both monkey-patch some visitor methods. Some languages do solve this, but this doesn't mean that it's recommendable. Subclassing is not an option as we want to be able to perform new behavior on existing data.

Using pattern matching as in ML-derived languages isn't an option either, as this isn't extensible (in my example, I could subclass the visitor to handle another node specially as well).

Title: Visitor Pattern still useful in languages supporting class extensions?

Body:
Is the visitor pattern useful in languages supporting class extensions?

Why bother implementing it, when you have open classes or can subclass. If you want new functionality for a class you could just subclass it, so unless I'm missing something, is it still (very) useful in languages supporting class extensions?

Body:
The visitor pattern isn't meant to extend the functionality of some class. It is a pattern that provides an elegant way to operate on some data (e.g. to traverse it) while the visitor can keep state and handle different types of data differently.

For example consider a pseudo-DOM where we want to collect all headlines, in a language with type-overloaded methods:

class CollectHeadlinesVisitor {
  List<String> headlines = new List<>();

  public void visit(Node n) {
    for (Node child in n.childs()) {
      this.visit(child);
    }
  }

  public void visit(Headline h) {
    list.add(h.text());

    for (Node child in n.childs()) {
      this.visit(child);
    }
  }

  public List<String> value() {
    return headlines;
  }
}

Note that in a language without type overloads we have to do the accept/visit_Type indirection.

The above example can't be implemented by adding methods to Node and Headline as a place is needed to store the discovered headlines.

Adding methods to the existing data classes would also violate the Single Responsibility Principle and could lead to namespace issues, e.g. when two pieces of code both monkey-patch some visitor methods. Some languages do solve this, but this doesn't mean that it's recommendable. Subclassing is not an option as we want to be able to perform new behavior on existing data.

Using pattern matching as in ML-derived languages isn't an option either, as this isn't extensible (in my example, I could subclass the visitor to handle another node specially as well).


问:
Design for a tree using a visitor pattern, how to implement different kinds of traversal?
I've been asked a theoretical design question with an eye upon the GoF patterns.:

"Given a design for a tree using a standard visitor pattern, how would your design look to allow a user to choose between om pre-order, in-order or post-order traversals?"

I'm thinkin of just letting the visitor be, but give the traversal over to an Iterator object following the Iterator Pattern.

The idea would be to implement 3 iterators that enable the desired traversal. They have an interface and the Visitor only needs to interact with this interface, giving itself as an argument to the iterator which provides traversal. The user can choose which iterator to use when giving one to the visitor.

Does this sound like an elegant solution? Any better ideas?

答:
One thing about Visitor Patterns is misconception, that it is somehow tied to tree-like structure. Which is quite wrong. The question sounds as if it was doing just that. So first thing would be fixing this misconception. And then I would exactly like you said. Create 3 different iterators one for each type of traversal.

But this depends on complexity of the tree. If each node has same specified collection of children, then it is easy. The problems start when different types of nodes have different structure of children. Then visitor starts making sense. But the different types of traversal order stop making a sense, because they only work for n-arry trees, not for trees with arbitrary types of children in each node.

ContentLicense: CC BY-SA 3.0


问:
Webservice Design: benefits of piping use-cases to URL rather than using search param's, or vice versa?
I've gotta build a webservice for employee information, and I'm trying to plan it out.

To clarify, we already have a REST-ish service for People and a separate REST-ish service for Companies.

This service will specifically be for the relationship between those two (all the data will be delivered from services to the data-consumers through a client (or clients) ).

Among other tasks, this service will need to:

retrieve all employers (company id's) for a given person ID

retrieve all employees (person id's) for a given company ID

I could see doing this a couple different ways.

Using search parameters could look something like:

http://blah/employee/find?person_id=12345

http://blah/employee/find?company_id=9876

Using the URL could look something like:

http://blah/employee/find/employers?id=12345

http://blah/employee/find/employees?id=9876

Taking the URL approach, I'd be able to specifically validate for a single parameter for each the employer and employee cases .. seems nice and clean, but quite fixed.

Taking the parameter approach seems like it's less-rigid/more-flexible, but then requires more data paths (if/else), and therefore the code can take longer to understand when future-me (or anyone else) comes back to it after it's been long forgotten.

What benefits might there be to going with once vs the other?

To me, the difference seems kinda arbitrary, but this is the first time I've got to make this decision.

答:
I would just go with REST routes and in this case nested resources. This is somewhat similar to your second approach, only the IDs becomes part of the URL too. In this case your URLs would look like this:

```<code>http://blah/company/123/employees
http://blah/employees/789/companies
</code>```

Though a lot depends on how your model works and how good your toolchain helps with RESTful routing. My suggestion comes from the view of a Rails programmer (and somehow the simple fact that REST is a good standard that consumers of your service should be able to understand easily)

For Rails in such a case there would be two controllers: companies and employees.
From the URL the requested controller would get the params. For the first URL params[:company_id] would be set to 123. And in the index action of the employees controller that would be called in that case I would simply do:

```<code>Company.find(params[:company_id]).employees
</code>```

Vice versa for the second URL index in companies controller would do:

```<code>Employee.find(params[:employee_id]).companies
</code>```

So there is not really any repetition. The tasks are clear for both controllers. The correct URL leads to the resource you want. Nesting the URLs defines dependencies between those resources. These are two quite distinct finctions and they actually should reside in different locations instead of trying to force them in a single location. Employees controller lists employees, companies controller lists companies. Can't really be clearer than that.

From here it may depend who the consumers of your service are. If they are developers, they should understand this (and chances are they already know how REST works). If they are not, you would have to get some kind of search page that lists the companies and allows them to select one (and similar for employees). Then this search page would link to the correct URL and they should not have to worry about what exactly that URL is anyway.

Body:
I would just go with REST routes and in this case nested resources. This is somewhat similar to your second approach, only the IDs becomes part of the URL too. In this case your URLs would look like this:

http://blah/company/123/employees
http://blah/employees/789/companies

Though a lot depends on how your model works and how good your toolchain helps with RESTful routing. My suggestion comes from the view of a Rails programmer (and somehow the simple fact that REST is a good standard that consumers of your service should be able to understand easily)

For Rails in such a case there would be two controllers: companies and employees.
From the URL the requested controller would get the params. For the first URL params[:company_id] would be set to 123. And in the index action of the employees controller that would be called in that case I would simply do:

Company.find(params[:company_id]).employees

Vice versa for the second URL index in companies controller would do:

Employee.find(params[:employee_id]).companies

So there is not really any repetition. The tasks are clear for both controllers. The correct URL leads to the resource you want. Nesting the URLs defines dependencies between those resources. These are two quite distinct finctions and they actually should reside in different locations instead of trying to force them in a single location. Employees controller lists employees, companies controller lists companies. Can't really be clearer than that.

From here it may depend who the consumers of your service are. If they are developers, they should understand this (and chances are they already know how REST works). If they are not, you would have to get some kind of search page that lists the companies and allows them to select one (and similar for employees). Then this search page would link to the correct URL and they should not have to worry about what exactly that URL is anyway.


问:
Why do we still use floats?
I understand why floats served a purpose in the past.  And I think I can see why they're useful in some simulation examples today.  But I think those example are more exceptional than common.  So I don't understand why floats are more prevalent in simple simulations rather than very high precision integers.

A classic argument is that floats provide a greater range, but high precision integers can meet this challenge now. For example: with modern 64-bit processors, we can do fast integer calculations up to 2^64. The solar system is a little less than 10 billion km in width. 10 billion km divided by 2^64 is about 5 microns. Isn't being able to represent position within the solar system to the precision of half a human hair enough?

On the flip-side, rounding errors from floating calculations can present problems.  You need to consider the scale of the calculations to make certain that you're not inadvertently introducing error to your simulation.

So why do personal computers even need FPUs anymore?  Why not just leave floats to the supercomputers?

答:
If you want to have coefficients, floats are just better.

For example, 54.2% of 12442, you just do 0.542 * 12442.

Don't forget float are computed by a dedicated unit on the CPU, the FPU. They're obviously not better for embedded hardware, because they do consume more power, but they're very important in game programming and graphic programming.

In science and finance, float are not really liked because there can be data loss.

In scientific simulation, I believe they're not used, the GMP library allows you to make a float of 128 bits or even larger, you can theoretically have precision as large as you can take, at the expense of speed.

In real time simulation however, float are preferred. There are some precautions when using float number if you want to avoid data loss or error accumulating. For example blizzard use a deterministic way to change the game state as a multiplayer game of starcraft 2 is played, since only players orders are transmitted, and not unit positions.

Floats just have their application, they have pros and cons.

OwnerDisplayName: anon

Title: Why do we still use floats?


答:
Maybe I'm missing something but don't you simply need different visitors for each of the traversal types, PreOrderTreeVisitor, InOrderTreeVisitor, PostOrderTreeVisitor with the visit method specific to the type of traversal.  Probably you want them to take some action that could be applied to a node so that they, in effect, become the iterators over the tree.</p>

```<code>interface ITreeVisitor {
   void visit(ITreeNode node);
}

interface ITreeNode {
   ITreeNode getLeft();
   ITreeNode getRight();
   int getValue();
   void accept(ITreeVisitor visitor);
}

interface IAction {
   void do(ITreeNode);
}

class TreeNode implements ITreeNode {
   ...
   public void accept(ITreeVisitor vistor) {
      visitor.visit(this);
   }
}

class PreOrderTreeVisitor implements ITreeVisitor {

   private IAction action;

   public PreOrderTreeVisitor(IAction action) {
        this.action = action;
   }

   public void visit(ITreeNode node) {

       action.do(node);

       ITreeNode left = node.getLeft();
       if (left != null) left.accept(this);

       ITreeNode right = node.getRight();
       if (right != null) right.accept(this);
   }
}
</code>```

Title: Design for a tree using a visitor pattern, how to implement different kinds of traversal?

Body:
I've been asked a theoretical design question with an eye upon the GoF patterns.:

"Given a design for a tree using a standard visitor pattern, how would your design look to allow a user to choose between om pre-order, in-order or post-order traversals?"

I'm thinkin of just letting the visitor be, but give the traversal over to an Iterator object following the Iterator Pattern.

The idea would be to implement 3 iterators that enable the desired traversal. They have an interface and the Visitor only needs to interact with this interface, giving itself as an argument to the iterator which provides traversal. The user can choose which iterator to use when giving one to the visitor.

Does this sound like an elegant solution? Any better ideas?

Body:
Maybe I'm missing something but don't you simply need different visitors for each of the traversal types, PreOrderTreeVisitor, InOrderTreeVisitor, PostOrderTreeVisitor with the visit method specific to the type of traversal.  Probably you want them to take some action that could be applied to a node so that they, in effect, become the iterators over the tree.

interface ITreeVisitor {
   void visit(ITreeNode node);
}

interface ITreeNode {
   ITreeNode getLeft();
   ITreeNode getRight();
   int getValue();
   void accept(ITreeVisitor visitor);
}

interface IAction {
   void do(ITreeNode);
}

class TreeNode implements ITreeNode {
   ...
   public void accept(ITreeVisitor vistor) {
      visitor.visit(this);
   }
}

class PreOrderTreeVisitor implements ITreeVisitor {

   private IAction action;

   public PreOrderTreeVisitor(IAction action) {
        this.action = action;
   }

   public void visit(ITreeNode node) {

       action.do(node);

       ITreeNode left = node.getLeft();
       if (left != null) left.accept(this);

       ITreeNode right = node.getRight();
       if (right != null) right.accept(this);
   }
}


问:
MySQL PHP User/Group Permissions
I am trying to configure a mysql database table that I can use as a per user/group permissions table. Almost like what Facebook has, for a local company intranet site.

What is the best possible way to design this table, that would allow me to find user permissions with the fewest amount or queries?

答:
There are several ways to manage permissions. Wanting to validate these in the database, one of the possible options is to establish a list of permissions, and associate these permissions to possible actions by the user (the creation of groups is a consequence of this report).

Assuming then a very simple case, where the user decides to perform an action on the interface, for example, "add a comment to a post," a possible workflow is as follows

System

Interface

Pressing a button in the interface invokes the "Add Comment" (which acts on the interface to create a text field and a button, if that user has permission to do so. Otherwise the error message will be shown.)

API

All of the methods, not public, in the backend, provide for the control of permissions before running the rest of the code.
So the query is executed in the database to see if the user has permission for action "Comment".

Database

The database performs a select in the table where are recorded users and actions. Responding with a NULL (there is no permission) or ID (allowed).

At this point we can assume that:

Any private action (method exposed in the API), after the validation of input parameters, performs the validity check.

The function in the backend, to authorize the execution of code takes 2 parameters (minimum): UserID, ActionID;

The function in the database (or the query to be executed in the database) involves reading in a table that has 3 fields (minimum): ID, user ID, ActionID;

Groups

The groups should (could) be managed as presets of permission. There are so many ways to manage the permissions of the group. Probably one of the least expensive in terms of development, is to create a table for managing the relationship between Groups and Users.

Conclusions

The structures of our database will therefore be as follows:

Users

UserID

Username

...

Actions

ActionID

ActionName

...

Permissions

ID

UserID

ActionID

Groups

ID

GroupID

UserID

Title: MySQL PHP User/Group Permissions


问:
Extracting data from log files
I will be extracting certain bits from log files using regular expressions to filter out bit of data. Initially I was going to do this with Python. I later started to think about the fastest way I can perform this task. This lead me to parallel programming. I remember hearing somewhere that Python can't be truly parallel. I'm by far an expert programmer. I have been playing with Java for a bit and I was considering parallel programming in Java to perform this task. I was wondering what would be the fastest way to perform this task?</p>

答:
Assuming you are talking about speed of execution and not speed of development, C might be hard to beat. But I don't think it would beat Java or even Python by much these days. Python is largely a thin wrapper on C implementations, albeit with a more efficient syntax and richer library.

Ultimately, I think your program will be I/O bound. Adding more threads or processes probably won't get the data off the disk or network any faster.

To minimize the CPU time of your program (as opposed to the execution time of it), you should use the fastest regex library you can find, and simplify the log format and regexes as much as possible. A multiple pass approach to parsing the log lines might help, too, whereby you use something simple and fast to break up the log lines into phrases, and then pass the phrases to separate regexes that would collectively be simpler and faster than a single regex to parse the entire line.

To parallelize, I would have the main thread vend lines to a pool of line processors, each running on a separate thread, perhaps with n queues for the n threads. You might have lines processed out of order, so beware. And if one processing thread is still faster than disk or network I/O, then you are adding complexity for no real gain.

Above all, when looking to improve speed, profile and measure before and after every change. You need to be able to prove that you are making the program faster.

Title: Extracting data from log files


问:
Visitor Pattern still useful in languages supporting class extensions?
Is the visitor pattern useful in languages supporting class extensions?

Why bother implementing it, when you have open classes or can subclass. If you want new functionality for a class you could just subclass it, so unless I'm missing something, is it still (very) useful in languages supporting class extensions?

答:
The visitor pattern often uses the double dispatch pattern.
So for me the visitor pattern is

double dispatch + structure traversal.

You will need the structure traversal even if you have refinements or subject orientation. But the double dispatch may take on other forms.


问:
Implementing Settings/Preferences in JavaScript
I am making a simple web app mostly in JavaScript. I was wondering as to how do I deploy settings/preferences? Do I just store user preferences somewhere and make use of if...else... statements all over the code?

I think that there must be a better alternative. I am know JS, jQuery & PHP and willing to learn anything new if at all required.

I have already made the app, only the settings are remaining. I know what options to give users and how to program them in js.

What's the most optimal way? How is it done in professional web apps and software made by companies (I am independent Student Developer - this is my first "BIG" project)?

EDIT:

For all the modifications that the settings are supposed to make (in this particular app), the whole js code base would litterally be filled with many branches of if...else...statements and I think that would make the code a lot harder to read and maintain.

In my app, the whole database table to be fetched from the database and the number and types of HTML DOM manipulation to be done, new elements to be added to HTML dom and whether some  are visible or not would change. How do I deal with all that?

答:
There are many solutions. One of these, (which I consider very clean, easy to maintain and to test), comes from MV* architecture.

In a MVC/MOVE/MV* context your user would be represented by a model. All views of your application would be listening for data changes (representing the preferences) of this model (Event Driven).

By focusing the application around the state of the user, each change of state into it, will be reflected in the interfaces due to the binding of the views on this object.

The UserModel object could then have some basic methods, such as:

localLoad: load client data from local storage (LocalStorage, cookies, etc.)

localSave: save client data to local storage (LocalStorage, cookies, etc.)

remoteLoad: load client data from remote API

remoteSave: save client data to remote API

initialize: State control

stayUpdate: timer to update the customer's preferences

The views, could listen to events like these:

LISTEN TO USER.ID

LISTEN TO USER.PREFERENCES.BACKGROUNDCOLOR

An example of how to handle this using Backbone.js is Backbone.ModelBinding

There are different MV* frameworks for creating javascript applications.
  Among the most famous you have Angular.js and Backbone.js.


问:
Best way to assure uniqueness in filename with php
I was wondering, without using any kind of user info (id, nickname, age, etc), what would be the best way to assure filename uniqueness using php in a large database with high traffic and most probably simultaneously between many users? I am using $file = time() for example but I would like to know if this should suffice whenever two users might go over this code at the same time (at a large large large scale, 10000 users at the same time and the same function ran 200 at the same time).

答:
In simple terms a multitasking space there is something called an atom, a semaphore or a spin-lock.  They are somewhat different from each other and I won't get into the details of that, but they are all similar concepts to essentially ensure that only one thing at a time can happen in critical code.  They all rely on the system being designed so one physical resource is locked by a caller in such a way that it prevents any others from locking it until the caller releases it.  Then another caller can lock it while it does it's "critical" thing.  It is something that comes right down to one single CPU machine instruction being the lock.

Now having said all that, while it is possible to approach this sort of absolute lock with a time based value, and thus an approximation of a lock, the down side is that as the number of simultaneously executing processes increase, so does the probability of a collision.  Which is I think one of your concerns.  This is true no matter how fine a clock resolution you choose.

In terms of performance and scalability there is a big trade off between the first method above and the second, with the first method creating an absolute bottle neck that all processes must pass thru, and the second method almost no bottleneck.

So in terms of 'best way", well that depends..., on if you need a really absolute lock, or if just a very good lock that can fail within a certain statistical probability will suffice.

(One of the more cool pieces of software I wrote years ago was the guts of multitasking operating system.  Disk access was shared in common between all tasks so had to be absolutely single threaded for at time.  It was important to keep that locked section of code as thin as possible to keep the bottle neck as unblocking as possible.)

As a side note, there is an interesting similar hardware related problem with the possible collision of electrical signals which you might find interesting to read about to reflect light on your question.  It's called meta-stability.


答:
If you don't want to hash the entire file to generate a unique id, a couple of other ways come to mind:

You can use an 'auto increment' column in a database.  Each insert gives you a unique id, managed by the database.  Then base your file name off of that.

You can create a unique identifier from the existing session id or remote ip address and the time.  You might even use the file size as well.  Concatinating them together should prevent file name collisions at a much better reliability than just using the time.

You can implement some other single process service that distributes unique id's upon request.  The requesting PHP script would request an id and wait until one was returned before proceeding.  Its unlikely simply distributing id's would be a bottleneck even at very high levels of traffic.

Title: Best way to assure uniqueness in filename with php

Body: I was wondering, without using any kind of user info (id, nickname, age, etc), what would be the best way to assure filename uniqueness using php in a large database with high traffic and most probably simultaneously between many users? I am using $file = time() for example but I would like to know if this should suffice whenever two users might go over this code at the same time (at a large large large scale, 10000 users at the same time and the same function ran 200 at the same time).


答:
This is a hard question to answer generally but I'm going to try. Consider the following:

#1 Does that need to be state?

For instance the DOM. One mistake people make a lot is to not see the DOM for the big giant live global data-structure construct that it is. It's there. It's doing work all the time whether you touch it or not. Take advantage of it. Do not save information that the DOM already has or can get very quickly. You will eventually fall out of sync with it and your app will faceplant. I mention this in a settings conversation because settings are exactly the kind of place where DOM concerns typically get way too close to higher-level app logic. If you can check the DOM for the state of something, stick with the DOM.

So, don't set DOM stuff directly from your settings. Your settings should be more about what, in plain English terms, the app does or doesn't do when you flip that switch.

Now mind, DO avoid setting anything in the DOM before you absolutely have to. That's when CSS reflow concerns kick in. Get like crazy but don't set two things at different times if they can happen in the same function.

#2 Let Your Features Check the Settings

If an object knows whether to hide/show the HTML that is its face to the user because it checks the settings itself, you shouldn't have to think about it when flipping a boolean that says whether the feature that object handles is available.

#3 One Setting Value Always Means One Thing

I break this one somewhat regularly to be honest but I think it's worth considering as a heuristic and I've often regretted breaking it. If behavior established by one setting can become altered based on a combination of it and the values of other settings, that can get ugly. It's better to flip a switch that makes an object realize it will have to do a certain set of things depending on its circumstances than to flip a switch that then causes some third party to run around and sort out the circumstances and then tell the object exactly what it and the other relevant objects must do.

#4 Listen, Don't Tell

Odds are good you're using jQuery. It actually has a very nice architectural tool not at all related to the DOM. It can trigger and listen for custom events on the fly on any old object. Try this:

```<code>var someObject = {};

$(someObject).on('ICanMakeUpAnyEventIWant', function(){
    alert('I can do anything I want based on that event.');
} );

$(someObject).trigger('ICanMakeUpAnyEventIWant');
</code>```

On the whole theme of "let your lower-level objects handle the logic" you could also set your settings properties via getter/setter-style methods that trigger events when changes happen. By triggering an event, you can add new things that need to respond to said event without changing the behavior of anything else that responds to that event or the thing that originated said event. This can be very good where settings are concerned.

That trigger method can also be used to hand off an event object with data:

```<code>$(someObject).on('someEvent',function(eventObj){ alert(eventObject.dataForAnyListener); });
//'yay'
$(someObject).trigger({type:'someEvent', dataForAnyListener:'yay'});
</code>```

So for instance, imagine a settings object whose settings were set with methods that also triggered 'someSpecificSettingChange' events with 'newValue' properties in their event objects.

#5 Sometimes you need a crap-ton of logic

Don't get me wrong. It's a good smell to sniff for, but sometimes there's no way around a buttload of flow-control. Always see what you can do to reduce your if/elses but don't assume they're always wrong merely for existing. UI gets hairy sometimes.

#6 Start With Defaults

```<code>function SpyCar(overrides){

    var defaultSettings = {
        ejectionSeatArmed:true,
        oilSlickFlammability:.99,
        car:'Aston Martin DB5'
    }

    for(var x in overrides){
        defaultSettings[x] = overrides[x];
    }
    //See also $.extend(defaultSettings, overrides) if into JQ

    //do important spy car code here based on defaultSettings
}

var boDukeSuperSpy = new SpyCar( { car:'\'69 Dodge Charger' } );
</code>```

Considering defaults before the code is even written can be helpful in organizing code because it kicks off your lazy developer instincts. What's the easiest most common setup you'll deal with? How do those common settings relate? Sometimes you might never need a setting. Other times you might realize that just because nobody will ever want a genre-bending General Lee as a spy car, doesn't mean it wasn't later useful to leave the door open for make/model swapouts.

Title: Implementing Settings/Preferences in JavaScript

Body:
I am making a simple web app mostly in JavaScript. I was wondering as to how do I deploy settings/preferences? Do I just store user preferences somewhere and make use of if...else... statements all over the code?

I think that there must be a better alternative. I am know JS, jQuery & PHP and willing to learn anything new if at all required.

I have already made the app, only the settings are remaining. I know what options to give users and how to program them in js.

What's the most optimal way? How is it done in professional web apps and software made by companies (I am independent Student Developer - this is my first "BIG" project)?

EDIT:

For all the modifications that the settings are supposed to make (in this particular app), the whole js code base would litterally be filled with many branches of if...else...statements and I think that would make the code a lot harder to read and maintain.

In my app, the whole database table to be fetched from the database and the number and types of HTML DOM manipulation to be done, new elements to be added to HTML dom and whether some  are visible or not would change. How do I deal with all that?

Body:
This is a hard question to answer generally but I'm going to try. Consider the following:

#1 Does that need to be state?

For instance the DOM. One mistake people make a lot is to not see the DOM for the big giant live global data-structure construct that it is. It's there. It's doing work all the time whether you touch it or not. Take advantage of it. Do not save information that the DOM already has or can get very quickly. You will eventually fall out of sync with it and your app will faceplant. I mention this in a settings conversation because settings are exactly the kind of place where DOM concerns typically get way too close to higher-level app logic. If you can check the DOM for the state of something, stick with the DOM.

So, don't set DOM stuff directly from your settings. Your settings should be more about what, in plain English terms, the app does or doesn't do when you flip that switch.

Now mind, DO avoid setting anything in the DOM before you absolutely have to. That's when CSS reflow concerns kick in. Get like crazy but don't set two things at different times if they can happen in the same function.

#2 Let Your Features Check the Settings

If an object knows whether to hide/show the HTML that is its face to the user because it checks the settings itself, you shouldn't have to think about it when flipping a boolean that says whether the feature that object handles is available.

#3 One Setting Value Always Means One Thing

I break this one somewhat regularly to be honest but I think it's worth considering as a heuristic and I've often regretted breaking it. If behavior established by one setting can become altered based on a combination of it and the values of other settings, that can get ugly. It's better to flip a switch that makes an object realize it will have to do a certain set of things depending on its circumstances than to flip a switch that then causes some third party to run around and sort out the circumstances and then tell the object exactly what it and the other relevant objects must do.

#4 Listen, Don't Tell

Odds are good you're using jQuery. It actually has a very nice architectural tool not at all related to the DOM. It can trigger and listen for custom events on the fly on any old object. Try this:

var someObject = {};

$(someObject).on('ICanMakeUpAnyEventIWant', function(){
    alert('I can do anything I want based on that event.');
} );

$(someObject).trigger('ICanMakeUpAnyEventIWant');

On the whole theme of "let your lower-level objects handle the logic" you could also set your settings properties via getter/setter-style methods that trigger events when changes happen. By triggering an event, you can add new things that need to respond to said event without changing the behavior of anything else that responds to that event or the thing that originated said event. This can be very good where settings are concerned.

That trigger method can also be used to hand off an event object with data:

$(someObject).on('someEvent',function(eventObj){ alert(eventObject.dataForAnyListener); });
//'yay'
$(someObject).trigger({type:'someEvent', dataForAnyListener:'yay'});

So for instance, imagine a settings object whose settings were set with methods that also triggered 'someSpecificSettingChange' events with 'newValue' properties in their event objects.

#5 Sometimes you need a crap-ton of logic

Don't get me wrong. It's a good smell to sniff for, but sometimes there's no way around a buttload of flow-control. Always see what you can do to reduce your if/elses but don't assume they're always wrong merely for existing. UI gets hairy sometimes.

#6 Start With Defaults

function SpyCar(overrides){

    var defaultSettings = {
        ejectionSeatArmed:true,
        oilSlickFlammability:.99,
        car:'Aston Martin DB5'
    }

    for(var x in overrides){
        defaultSettings[x] = overrides[x];
    }
    //See also $.extend(defaultSettings, overrides) if into JQ

    //do important spy car code here based on defaultSettings
}

var boDukeSuperSpy = new SpyCar( { car:'\'69 Dodge Charger' } );

Considering defaults before the code is even written can be helpful in organizing code because it kicks off your lazy developer instincts. What's the easiest most common setup you'll deal with? How do those common settings relate? Sometimes you might never need a setting. Other times you might realize that just because nobody will ever want a genre-bending General Lee as a spy car, doesn't mean it wasn't later useful to leave the door open for make/model swapouts.


问:
Question about Visual C++ Properties
Could someone explain this line:

In more complicated contexts, such as "+=", a rewrite is performed by
  doing both get and put.

Taken from: MSDN - Property

What do they mean by rewrite?Is it a compile-time rewrite or does it induce run-time overhead?As far as I know in release mode properties are compiled to the same thing, so they must have the same performance as getters/setters, right?

答:
As you see in complete paragraph in MSDN page to that you referred, all work is done by compiler.

When the compiler sees a data member declared with this attribute on the right of a member-selection operator ("." or "->"), it converts the operation to a get or put function, depending on whether such an expression is an l-value or an r-value. In more complicated contexts, such as "+=", a rewrite is performed by doing both get and put.

By then it means that following line:

```<code>s.the_prop = 5;
n = s.the_prop;
</code>```

compiled to:

```<code>s.putprop(5);
n = getprop();
</code>```

A complicated case like:

```<code>s.the_prop += 5;
</code>```

compiled to:

```<code>s.putprop(s.getprop() + 5);
</code>```

I think it is not as complicated as they said in MSDN!

Title: Question about Visual C++ Properties

Body:
As you see in complete paragraph in MSDN page to that you referred, all work is done by compiler.

When the compiler sees a data member declared with this attribute on the right of a member-selection operator ("." or "->"), it converts the operation to a get or put function, depending on whether such an expression is an l-value or an r-value. In more complicated contexts, such as "+=", a rewrite is performed by doing both get and put.

By then it means that following line:

s.the_prop = 5;
n = s.the_prop;

compiled to:

s.putprop(5);
n = getprop();

A complicated case like:

s.the_prop += 5;

compiled to:

s.putprop(s.getprop() + 5);

I think it is not as complicated as they said in MSDN!


答: If you ever have to write a compiler you will need to use visitor pattern.  The number of subclass cases you would have to handle without it would make any other method prohibitive, or at least horribly unenjoyable.</p>


问:
To MVC or not MVC, that is the question
Originally, I started off doing jQuery plugins, then moved onto Backbone.js applications, then been experimenting with MicroJS MVC modules, but these days I'm even wondering if there is any need for them at all.

Recently, I've been prototyping a new application, and the code is slim, sleek, and beautiful. I then proceeded to rewrite it over 3 hours into a Backbone.js application, and the code turned away from its fitness model petiteness, into a bloated, complex, and ugly mess.

The problem is, these days, this always happens. As soon as the MVC/MV* architecture is introduced, it all goes to puke.

I'm wondering if the day and age of requiring these things on the client-side are over now, now that browsers are actually quite capable beings, maybe we don't need all the bloat of MV* frameworks anymore. What are your thoughts? Has others run into this? To MVC, or not MVC?

答:
Maybe your applications aren't very big? I remember the first big app I co-wrote, it consisted only of a large number of complex jQuery plugins. There was no separation of concerns, the code was convoluted, testing it was almost impossible.

The next app we wrote in Backbone. It gave us a basic structure to build upon. Obviously, Backbone introduced its own share of problem but it solved a lot more.

Our problems mainly concerned reacting to model & view changes, we started to have a large number of events & handlers hard to control. Even then, it was heaven compared to what we had in the previous app!

We decided to rewrite the app in AngularJS (personal preference, you can substitute Angular for Ember in this paragraph and arguments will probably stay). It allowed us to make our client code 40% smaller and so much easier to maintain; testability was a bonus too. We could focus more on the app logic than on manual DOM modifications.

To summarize, my experience is contrary to yours. I'd think similarly to you in case of simple sites since MVC always introduce some boilerplate and you need certain application size to experience the benefits.

Title: To MVC or not MVC, that is the question


答:
It depends.

MVC is a visual design pattern that makes it easier to swap out UI technology over the life of an application.

So you need to ask yourself:

Are you throwing out a down-and-dirty little web application that you're never going to come back to?  If so, then don't bother with MVC.  Seriously.

Or are you writing a substantial web app that will have a number of views, and potentially even a measure of logic controlling how a user navigates between pages?  MVC starts looking a lot more attractive in this case.  It increases your chances of being able to re-use controllers, and perhaps even a chance at re-using some of the partial HTML pages you write.

But it's easier making a decision when you're looking at the two extremes.  If your app is somewhere in the middle, then I would suggest you look at the future.  If you hope it will grow into something or if you know you'll keep coming back to working on the application, then I would still recommend MVC.  Yes, there is a cost to creating and maintaining the scaffolding to support things.  But that scaffolding helps promote separation of concerns.  And that separation is what will make your future changes a lot easier to do.

Title: To MVC or not MVC, that is the question

Body:
Originally, I started off doing jQuery plugins, then moved onto Backbone.js applications, then been experimenting with MicroJS MVC modules, but these days I'm even wondering if there is any need for them at all.

Recently, I've been prototyping a new application, and the code is slim, sleek, and beautiful. I then proceeded to rewrite it over 3 hours into a Backbone.js application, and the code turned away from its fitness model petiteness, into a bloated, complex, and ugly mess.

The problem is, these days, this always happens. As soon as the MVC/MV* architecture is introduced, it all goes to puke.

I'm wondering if the day and age of requiring these things on the client-side are over now, now that browsers are actually quite capable beings, maybe we don't need all the bloat of MV* frameworks anymore. What are your thoughts? Has others run into this? To MVC, or not MVC?


问:
Weight-maximizing (weighted vertices) path algorithm
I am looking for description (name of algorithm, code, pseudocode, etc.) that can help me frame this problem and find the appropriate recursion and the most efficient solution.

Problem:

Given a graph with weighted nodes and a starting node, I want to generate a weight-ordered list of nodes that are lying on a path that starts at the starting node and then proceeds by jumping to the next adjacent unvisited highest-value node, then to the next etc. until it can no longer continue (e.g. no adjacent nodes, no unvisited adjacent nodes, or all nodes were visited already once).

Am I correctly assuming that this is a variation on the traveling salesman problem? Any suggestions or pointers would be greatly appreciated. Algorithms just aren't my area of expertise...

Update from comments: This is not a homework question. ... There's actually years of empirical research behind simply being able to frame seemingly random mammalian behavior as an algorithmic problem. ... Without tackling these group dynamics algorithmically I will not be able to expand testing beyond my initial sample and unfortunately, regression analysis just won't do the trick.

答:
If I understand correctly then no, this isn't a variation on the TSP. It's a pretty straight forward greedy algorithm.

Here is some psuedocode:

```<code>List visited = {}

Main(Node startNode)
  FindPath(startNode)
  sort(visited)

FindPath(Node node)
  visited.addNode(node)
  neighbours = node.getAdjactentNodes()
  neighbours.subtract(visited)
  if(neighbours.isEmpty())
    // all adjacted nodes are visited
    return
  else
    sort(neighbours)
    FindPath(neighbours.First())
  end if
</code>```

So -- what's happening here?

We are creating a list to hold all the nodes we've visited on our journey.

In FindPath:
We then visit the node, we add it to the list of visited nodes and ask it for a list of neighbours.
If there are no adjacent nodes then we are finished (no more nodes to visit).
If there are adjactent nodes we sort them by weight and pass the biggest to FindPath.

When the FindPath function bottoms out (eventually we end up on a node that we can't jump anywhere from) we are left with all the nodes we've visited in the visited list and so then we just need to sort it by weight.

Hope that helps.

Body:
If I understand correctly then no, this isn't a variation on the TSP. It's a pretty straight forward greedy algorithm.

Here is some psuedocode:

List visited = {}

Main(Node startNode)
  FindPath(startNode)
  sort(visited)

FindPath(Node node)
  visited.addNode(node)
  neighbours = node.getAdjactentNodes()
  neighbours.subtract(visited)
  if(neighbours.isEmpty())
    // all adjacted nodes are visited
    return
  else
    sort(neighbours)
    FindPath(neighbours.First())
  end if

So -- what's happening here?

We are creating a list to hold all the nodes we've visited on our journey.

In FindPath:
We then visit the node, we add it to the list of visited nodes and ask it for a list of neighbours.
If there are no adjacent nodes then we are finished (no more nodes to visit).
If there are adjactent nodes we sort them by weight and pass the biggest to FindPath.

When the FindPath function bottoms out (eventually we end up on a node that we can't jump anywhere from) we are left with all the nodes we've visited in the visited list and so then we just need to sort it by weight.

Hope that helps.


答:
I think you are asking the wrong question. Its not MVC or not to MVC. I think a seperation of concerns is always a good idea. But do you want to use a framework for that? You can also write MVC in javascript without using frameworks for that.

When you are doing backend stuff in .NET for example I think the MVC framework is great. However, the backend of a website is stateless, so the structure is relatively simple compared to the frontend. You dont have to worry about callbacks or state. Thats why the one-size-fits-all MVC frameworks on the backend work.

The frontend is more complex. Most javascript frameworks i have seen are enforcing a particularly design. Most javascript MVC dont add that much anyway. Most of those frameworks automatically bind your events at the view side, which means you have less control in your controllers and your views are coupled to the controller and in proper MVC it should be the other way around. Another problem is that in GUI code a lot of times you have a component in a component (in maybe another component) and you want to abstract and reuse these components. Most MVC frameworks only allow one layer of abstraction (which is the result of the controllers not having enough control).

Javascript is a really powerful language and you can write great code without a framework. Personally i learned the most about the book Javscript: the Good Parts and reading up a bit about javscript design patterns.

Title: To MVC or not MVC, that is the question


问:
Shallow or deep equal, which one is idiomatic in Java?
I have a domain model in which I use a few aggregation relations, i.e. an object of class A contains zero or more objects of class B.

I use Java for the implementation and I represent such an aggregation as a field of type List in A, and a field of type A in B. In this way, each object can be the root of an aggregation tree. Classes A and B may also contain other shallow fields, i.e. fields of type int, float, String, and so on.

Now I need to define different kinds of equality methods on my model:

Shallow equality: compare two instances of A by comparing its shallow fields only, i.e. leaving out references to other domain objects. In this case, I am only interested to know if two nodes have the same contents.

Deep equality: compare two instances of A by comparing its shallow fields and by recursively comparing its children. In this case, I want to check if two complete trees are equal.

I considered overriding the hashCode() and equals() methods for class A but I do not know if this should be the shallow equality or the deep equality method. Once I decide which of the two equality methods is implemented as A.equals(), I will define the other method with another name. This is an important choice because the equals() method determines such things as membership in a Set.

So, is one of the two possibilities (shallow versus deep equality) considered a more idiomatic choice for implementing the equals method in Java?

答:
This is an important choice because the equals() method determines
  such things as membership in a Set.

You sort of answered your own question there. It's your decision based on your requirements. If you need your objects to be placed in a Set based on shallow equality, you need to implement equals() and hashcode() accordingly. If you need to base it on deep equality, you implement it that way.


答:
As the other answer says, you need to decide based on your own requirements.

Something else to consider is that you should compare equality of fields in your object using your own decision of what is important, but let those objects themselves decide what is important within them.

so if you have class A with int x, int[] y and B z then:

Do you compare x? Do you compare y? Do you compare z? Those are your choices. Comparing y would almost certainly involve use of Arrays.equals() as you would want to compare all members of y.

Whether the .equals() method in class B then goes on to do further deep comparison of its members is then a decision to be delegated to that class B. You wouldn't try and do a comparison of the contents of B from within A unless you really really had to.

So the choice isn't really "deep" or not. It is what members of this class need to be compared. If some of those members are Objects themselves then those objects define their own equality algorithm and that may again dig deeper into further member objects or super class. Each stage just worries about it's own equality though.

Title: Shallow or deep equal, which one is idiomatic in Java?

Body:
I have a domain model in which I use a few aggregation relations, i.e. an object of class A contains zero or more objects of class B.

I use Java for the implementation and I represent such an aggregation as a field of type List in A, and a field of type A in B. In this way, each object can be the root of an aggregation tree. Classes A and B may also contain other shallow fields, i.e. fields of type int, float, String, and so on.

Now I need to define different kinds of equality methods on my model:

Shallow equality: compare two instances of A by comparing its shallow fields only, i.e. leaving out references to other domain objects. In this case, I am only interested to know if two nodes have the same contents.

Deep equality: compare two instances of A by comparing its shallow fields and by recursively comparing its children. In this case, I want to check if two complete trees are equal.

I considered overriding the hashCode() and equals() methods for class A but I do not know if this should be the shallow equality or the deep equality method. Once I decide which of the two equality methods is implemented as A.equals(), I will define the other method with another name. This is an important choice because the equals() method determines such things as membership in a Set.

So, is one of the two possibilities (shallow versus deep equality) considered a more idiomatic choice for implementing the equals method in Java?


问:
What are the drawbacks of immutable types?
I see myself using more and more immutable types when the instances of the class are not expected to be changed. It requires more work (see example below), but makes it easier to use the types in a multithreaded environment.

At the same time, I rarely see immutable types in other applications, even when mutability wouldn't benefit anyone.

Question: Why immutable types are so rarely used in other applications?

Is this because it's longer to write code for an immutable type,

Or am I missing something and there are some important drawbacks when using immutable types?

Example from real life

Let's say you get Weather from a RESTful API like that:

public Weather FindWeather(string city)
{
    // TODO: Load the JSON response from the RESTful API and translate it into an instance
    // of the Weather class.
}
```

<p>What we would generally see is (new lines and comments removed to shorten the code):</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class Weather
{
    public City CorrespondingCity { get; set; }
    public SkyState Sky { get; set; } // Example: SkyState.Clouds, SkyState.HeavySnow, etc.
    public int PrecipitationRisk { get; set; }
    public int Temperature { get; set; }
}
</code>```

On the other hand, I would write it this way, given that getting a Weather from the API, then modifying it would be weird: changing Temperature or Sky wouldn't change the weather in real world, and changing CorrespondingCity doesn't make sense neither.

public sealed class Weather
{
    private readonly City correspondingCity;
    private readonly SkyState sky;
    private readonly int precipitationRisk;
    private readonly int temperature;

    public Weather(City correspondingCity, SkyState sky, int precipitationRisk,
        int temperature)
    {
        this.correspondingCity = correspondingCity;
        this.sky = sky;
        this.precipitationRisk = precipitationRisk;
        this.temperature = temperature;
    }

    public City CorrespondingCity { get { return this.correspondingCity; } }
    public SkyState Sky { get { return this.sky; } }
    public int PrecipitationRisk { get { return this.precipitationRisk; } }
    public int Temperature { get { return this.temperature; } }
}
```

答:
To model any real-world system which where things can change, mutable state will need to be encoded somewhere, somehow.  There are three main ways an object can hold mutable state:

Using a mutable reference to an immutable object

Using an immutable reference to a mutable object

Using a mutable reference to a mutable object

Using first makes it easy for an object to make an immutable snapshot of the present state.  Using the second makes it easy for an object to create a live view of the present state.  Using the third can sometimes make certain actions more efficient in cases where there's little expected need for immutable snapshots nor live views.

Beyond the fact that updating state stored using a mutable reference to an immutable object is often slower than updating state stored using a mutable object, using a mutable reference will require one to forgo the possibility of constructing a cheap live view of the state.  If one won't need to create a live view, that's not a problem; if, however, one would need to create a live view, an inability to use an immutable reference will make all operations with the view--both reads and writes--much slower than they otherwise would be.  If the need for immutable snapshots exceeds the need for live views, the improved performance of immutable snapshots may justify the performance hit for live views, but if one needs live views and doesn't need snapshots, using immutable references to mutable objects is the way to go.


问:
CSS for Visually Impaired people?
So while I was learning HTML I encountered CSS. It's interesting because with CSS you can make a webpage cool or more beautiful. But since it's more about colors, designs, styles etc., I can't know the results of my CSS codes. As someone who is visually impaired, why should I learn CSS if sighted people can always design a webpage better than me because they can see?

Are there blind programmers here who write CSS? How did you do it?

Should I disregard CSS all together and leave it to sighted programmers? Or there are some things in CSS that I can do without asking people to look at my page to know if it has good design?

答:
CSS is a general styling language, and includes properties for aural markup as well. While none of this is implemented by mainstream browsers, it might be useful to screen readers (but I don't know if any implement that, considering that aural markup isn't common “in the wild”).

I, as a seeing person, write CSS in a tight feedback loop where I change a bit of CSS and then watch how the page changes. If this feedback is not possible or very difficult, we have to fall back to design principles, and hope that they work out all right.

Proportions are easier to manage when we think of the page as a grid. A common division is to use the top row for navigation and headlines, and the right column for related content. The left column is used for the main content, and is roughly two to three times as wide as the right column. This is roughly how the Stack Exchange sites are rendered. In CSS, this can be implemented with display: table and related display styles of table-row and table-cell, or with the newer flexbox model. The exact ratios are surprisingly unimportant.

A page looks better when it's horizontally centered.

One doesn't have to use much colors: There is a background color (usually something bright and unsaturated) and a text color (usually something dark and saturated). We can reduce the brightness contrast to de-emphasize text like footnotes, bylines or other details. Using the HSV color model should be a lot easier than RGB for this. A number of color palettes exist that can be used if plain grey is too boring. Color should be used, but sparingly.

Font size can also be used to indicate importance – steps of 2pt and never below 9pt seems sensible. For normal text, a font size of 14pt should not be exceeded. Together, font size and contrast of text are similar to volume of speech.

CSS offers not only absolute units of measurements like px or cm but also relative units like em and keywords like thin or medium. Using relative measurements and these keywords is often easier.

Text shouldn't be any wider than 40em.

Browsers come with default stylesheets. They are not pretty, but you don't have to override everything. Choosing a simple webfont and setting a maximum width for text elements are the two most important things. Writing semantic HTML is important for the default styles to work.

With this, it should be possible to style a simple blog or such. However:

Debugging code is difficult, even more so if you can't see what you're doing. I don't get things right on my first try. But how would you even know when things look “right”?

Some things require precise placement of elements, e.g. in a pop-up menu.

Images and icons can add much depth to a design, but would be difficult for you to choose.

The CSS box model is horrible and often hard to simulate in your head.

I would assume that you would be able to write a bit of CSS, but it would be incredibly frustrating. I don't know what assistive technologies exist, but I assume that tactile feedback would allow you to design a general layout. Maybe pair-programming with somebody with eyesight might be a good solution for smaller details?

Title: CSS for Visually Impaired people?


答: References which are held for the purpose of identifying objects should reference-compared.  References which are held for the purpose of encapsulating the state of an object should be 'deeply' compared.  Collections, however, pose a problem in that the use of items in the collection is dependent not upon the collection itself, but upon the thing holding a reference to the collection.  Collections are generally instantiated by code which knows how the contents will be used, but Framework collections rarely provide any means for making such a distinction (there are a few types like IdentitySet which clearly specify that the keys encapsulate identity, but none of the types distinguish their contents well enough to allow equals or clone to operate at the proper semantic level).


问:
Where do I put the changelog to display the recent changes to the user?
I want to create a changelog for my application to display the set of recent changes to the user. But I'm not sure where I put it.

Do I create a text file and write in it? Where do I put this text file then?

Or do I use an action in the menubar and display the changelog in a new window when clicking on the action?

答:
Ideally, your changelog should be generated from version control checkins. You could have a post-build operation that pulls all checkin comments since the last release build and outputs to a file before packaging.

This requires your developers be diligent in their commits.

In the past, I have used conventions where commits starting with CHANGE: or CHANGELOG: are the only ones included in the output changelog.

This provides a good historical view without external maintenance.

EDIT

Since it seems you are simply asking how you should display it, you need to provide some context - What type of app, language, environment. Try something and then go ask on StackOverflow if you run into specific problems.

Typically, applications will link to the changelog in the about or help window along with the current version. The link could open a viewer for the changelog or link to a url containing the change history anchored to the version requesting it.


答:
I prefer to think of "equals" this way: if a.equals(b) then you can replace all references to b with references to a and the program behavior will not change.  This is true for immutable value classes like String and should be true for quasi-value classes like Date.  I think this is the way most Java programmers expect "equals" to behave.

Defining equals in some other way, so that things are sort-of equal, is likely to lead to subtle bugs when some future programmer puts these instances in a hash table or set.  That programmer will then hate you forever.


答: If Eşref Armağan can paint, then blind people should be able to create web pages.  But given how much harder it is, you should possibly consider other programming areas. I've known several blind programmers, they were highly effective, in part because they needed to keep the entire program in mind at all times.

Title: CSS for Visually Impaired people?

Body:
So while I was learning HTML I encountered CSS. It's interesting because with CSS you can make a webpage cool or more beautiful. But since it's more about colors, designs, styles etc., I can't know the results of my CSS codes. As someone who is visually impaired, why should I learn CSS if sighted people can always design a webpage better than me because they can see?

Are there blind programmers here who write CSS? How did you do it?

Should I disregard CSS all together and leave it to sighted programmers? Or there are some things in CSS that I can do without asking people to look at my page to know if it has good design?


问:
Authenticating users for a website
I'm working on a website and I want to validate that an individual is an employee at one of a large number of companies (probably using their company's email address, which I don't know before hand). The idea being some users are the general public and others are from these companies. And I need some way to authenticate that the users claiming to be employees are being honest while still having a friendly enough UI.

I did an informal survey of people I know and the domains and emails will match in a majority of cases but they might not always match exactly so you might have a company with a website foo.com and an email billy@foobar.com (although foobar.com did redirect back to foo.com).

And while I can easily check that I'm not sure what other variations might be out there (maybe fooLA.com and email billy@foolosangeles.com, etc.)

答:
As in the case of Google Apps For Business (and other Web Apps that have the need to load the profile of a company according to some parameters of the user), you could introduce a step before the log-in.

This first step asks the user a first parameter (the key with the company). During this phase, the system recognizes whether the customer is actually associated with a company. At this point, you can manage different cases.

if (! Company)

Depending on the actual requirements of the business about the case If the client is not associated with any company, maybe you have the following cases:

..., you can not follow through with the operation of log-in/sign-in;

..., you will be prompted to fill in a form with other information to deepen the recognition;

..., it is time to create a new company, with an anonymous profile, which will be filled in later.

Title: Authenticating users for a website


问:
What is dispatch? Does it imply dynamic resolution?
AFAIK, the term dispatch means just a method resolution and calling. It doesn't matter whether it is static or dynamic. I saw many people are using a term like static dispatch and dynamic dispatch.

What makes me confusing is there're also some mysterious descriptions. I was trying to understand what is multiple dispatch, and it seems just selecting a subprogram by parameter types. If I understood it correctly, there can be both of static multiple dispatch and dynamic multiple dispatch, and we can say C++ is providing multiple dispatch via free functions.

But, Wikipedia article about multiple dispatch says C++ has no multiple dispatch because it doesn't have dynamic resolution of function by multiple parameters. And I really don't get conceptual difference between Common Lisp example and C++ overloaded function. Because I can't find any conceptual difference unless the term multiple dispatch implies dynamic dispatch. And I realized that I am confusing what the dispatching really is

I also checked QA entry Multiple Dispatch vs. Function Overloading, and it seems the answer is premising the term dispatch is basically dynamic. That also makes me confusing.

What is correct meaning of the term dispatch? Does it imply dynamic resolution? Is this term well defined or just conventional? What am I missing?

答:
My advice here is: don't overthink this one. Dispatch simply means send. Dispatch an event to a listener, dispatch an interrupt to a handler, dispatch a message to a receiver, dispatch a call to a procedure or function: all aspects of the same basic concept. Send the data to the code that will handle it. Resolution means choosing between available destinations, and is just one part of dispatch.

In code terms, the dispatch starts with some kind of packet of information and something that indicate where it should be sent, and is finished when the packet has been sent (dispatched). All languages have some kind of dispatch mechanism built in, but many implement resolution and dispatching schemes to suit a unique purpose. Interrupt handling and windows message processing are examples that come to mind.

C++ can use static or dynamic resolution, but if it chooses between functions based on argument types it can only do so at compile time. Smalltalk/Objective C and Ruby resolve dispatches at runtime, as do many dynamic languages.

Single dispatch means that a single argument is thought of as the receiver and determines which method is called. The method is typically in the class for that receiver object, and the method signature is converted into an offset in a dispatch table (vtable) in that class. The privileged object in C++ is the one before the dot, which becomes the 'this' pointer.

Multiple dispatch means no privileged receiver but typically a pattern matching operation across all argument types. The Common Lisp Object System uses this approach. See https://en.wikipedia.org/wiki/Multiple_dispatch.

In C++ with overloaded operators, A+B and B+A must dispatch to different methods. In CLOS they can be the same.

I probably prefer the term MultiMethods, since it's multi-factor resolution rather than multiple dispatch per se. See http://c2.com/cgi/wiki?MultiMethods. Also http://www.codeproject.com/Articles/242749/Multiple-dispatch-and-double-dispatch.


问:
Notifying multiple listeners
I am building an Android guitar application and I need a way for GuitarString objects to notify multiple listeners that it has just been played. This includes the current Activity and all instances of GuitarStringView that have it as their GuitarString (the guitar is displayed twice, zoomed in & out).

I have so far handled this by having a ArrayList<OnPlayedListener> on GuitarString and each GuitarStringView or Activity adds themselves to that list. My Guitar class is a Singleton (which I know some may frown upon) so now I have to make sure objects remove themselves from the array of listeners when they're disposed of.

So my question is, is this a good approach, or is there a pattern that I should be using to handle this?

答:
Try the Observer Pattern, AKA publisher/subscribe (pubsub). It's exactly what you need here.
Here is a great video of Derek Banas explaining how it works :

Observer Pattern Derek Banas

Title: Notifying multiple listeners


答:
The terms mean the following:

static dispatch = the dispatch order is defined at compile time. It simply means that any function/method call say foo() or x.foo() will always invoke the very same function -- this is established once and then stays that way. This implies that the compiler can determine the type of x at compile time.

dynamic dispatch = the dispatch order is resolved at run time. This means the compiler builds a lookup table of all functions/methods and determines which one to actually call at run time. Say there there is class A and B, both of which implement interface X with method X.bar(). At runtime, y is examined and based on its actual class either A.bar() or B.bar() is called.

multiple dynamic dispatch = the dispatch order is dependent on function/method name + argument types (=a.k.a. signature), and the actual implementation that gets called is determined dynamically at runtime. Say class A implements methods A.fooBar(int) and A.fooBar(char *), and there is a call to a.fooBar(x) in your program. At runtime both a and x are examined and the actual method to call is determined based on the type of x.

See Wikipedia for more on dynamic dispatch and multiple dynamic dispatch.

Title: What is dispatch? Does it imply dynamic resolution?

Body:
AFAIK, the term dispatch means just a method resolution and calling. It doesn't matter whether it is static or dynamic. I saw many people are using a term like static dispatch and dynamic dispatch.

What makes me confusing is there're also some mysterious descriptions. I was trying to understand what is multiple dispatch, and it seems just selecting a subprogram by parameter types. If I understood it correctly, there can be both of static multiple dispatch and dynamic multiple dispatch, and we can say C++ is providing multiple dispatch via free functions.

But, Wikipedia article about multiple dispatch says C++ has no multiple dispatch because it doesn't have dynamic resolution of function by multiple parameters. And I really don't get conceptual difference between Common Lisp example and C++ overloaded function. Because I can't find any conceptual difference unless the term multiple dispatch implies dynamic dispatch. And I realized that I am confusing what the dispatching really is

I also checked QA entry Multiple Dispatch vs. Function Overloading, and it seems the answer is premising the term dispatch is basically dynamic. That also makes me confusing.

What is correct meaning of the term dispatch? Does it imply dynamic resolution? Is this term well defined or just conventional? What am I missing?


答:
Use a GUID. This is the canonical solution to this problem. See https://en.wikipedia.org/wiki/Globally_unique_identifier. Also https://www.rfc-editor.org/rfc/rfc4122.

A GUID is a 128-bit identifier that you can use to uniquely identify just about anything you like. The large number of bits reduces the risk of collision to the point where it can be ignored. You'll never see one.

Find a reputable algorithm, or use a library function from your existing libraries. A quick web search found several in PHP.

Convert it to string in the usual way eg {21EC2020-3AEA-1069-A2DD-08002B30309D}. Problem solved.


问:
In Ruby, change global in thread safe block
In Ruby, I have a use case for a few common configuration options, e.g. NOOP, TRACE, SILENT. Right now I am using local vars instead of globals and passing them around all over the place and it's a pain. I be perfectly happy to use globals for these, if I could run a block where the globals can be temporarily changed and then reverted back. e.g.

```<code> global_configure(:TRACE=>true) do
   ...
 end
</code>```

But how can I make that block of code thread safe, so that other threads can't change the globals on it?

答:
I think the best answer is: don't do that.

You aren't giving away a lot about your specifics, but one key question is: why are there other threads?

If the other threads are concurrent requests that happen to share the code and some global data, they you really don't want to arbitrarily turn on tracing for an entirely different request.

If the other threads are part of the current request (say background processing) then you want to ensure consistency, so  you should be setting the global state at a point where you control the thread state, preferably when the other threads are inactive.

In general, this kind of problem is better solved with a configuration class that you inject into the request/thread as you start it, so each has its own.

With more details about your environment a better answer might be possible.


问:
How should an embedded OS be combined with user code?
As a side-effect of an embedded project I've been working on, I've developed a small operating system for an ARM processor. While the OS and my user code are in separate directories and have clean boundaries between them, they're built into a single image using a single Makefile.

I'd like to release the OS as open source. It consists of an exokernel and userland driver libraries.

What I'm trying to decide is how a user of this OS should combine it with their own code at build time so they have a single image to flash. I can think of three possibilities:

1) Have the user include the OS source files as part of their project. They'd be recreating the setup I currently have, and it's how FreeRTOS, for example, appears to do it (although it only has three files).

2) Have the OS build itself into a .a file that the user code can link with. That would allow the user full control over memory placement using their own linker script (and allow the linker to tell them when a combined text, BSS or data section exceeds its space).

3) Have the OS build itself into a raw binary that expects to have the user code concatenated onto the end of it. The user code would begin with a small header (placed by the linker script) that had the address of the main function. The user code would also link with a .a file of just the userland drivers, not the kernel.

(1) would make it easiest for me to develop the OS and my user code in parallel with git subtree. (2) seems to have the most useful link process. (3) gives the biggest separation.

If you were using it, which would you prefer and why?

答:
Let me first say that I agree with Bart's answer, but I want to argue for option (2+).

Assume that your OSS project is a success, that you have some dozens (or hundreds) of developers using your OS, and you are busy working on V2, which has some breaking changes with V1. A few users have weird problems you can't reproduce, which you suspect are related to their build environment. Suddenly you find your clean boundaries are not so clean.

Given a software component and an application that uses it, it is highly desirable that the point at which the two get combined be as late in the build process as possible. Separate compilation is better than include files, linkable libs are better than objects, dynamic libraries are better than static, runtime is better than compile time. [Obviously not all choices are available on all technologies.]

It's your call based on the technologies you have at your disposal, but erring on the side of separation should deliver benefits over time. The bigger the separation the better.


答:
Clojure has a solution with dynamic variables and the binding form, which allows you to set a global variable to a value only for the execution of a code block, without affecting other threads that might use that variable.

Ruby doesn't have that feature built-in, but I've found a gem that implements something similar: http://cirw.in/blog/lspace. You use it like this:

```<code>LSpace.with(:TRACE=>true) do
    # ... code code code
    puts LSpace[:TRACE]
    # ... code code code
end
</code>```

One key difference between the Clojure implementation and the Ruby gem to keep in mind is that in the Clojure version if you spawn a new thread from inside the block where the variable is bound, the new thread will get the bounded value, and in the Ruby version it wouldn't - so if you have to depend on that functionality you better pass those configuration options as arguments (or as member fields).

Title: In Ruby, change global in thread safe block

Body:
In Ruby, I have a use case for a few common configuration options, e.g. NOOP, TRACE, SILENT. Right now I am using local vars instead of globals and passing them around all over the place and it's a pain. I be perfectly happy to use globals for these, if I could run a block where the globals can be temporarily changed and then reverted back. e.g.

```<code> global_configure(:TRACE=>true) do
   ...
 end
</code>```

But how can I make that block of code thread safe, so that other threads can't change the globals on it?

Body:
Clojure has a solution with dynamic variables and the binding form, which allows you to set a global variable to a value only for the execution of a code block, without affecting other threads that might use that variable.

Ruby doesn't have that feature built-in, but I've found a gem that implements something similar: http://cirw.in/blog/lspace. You use it like this:

LSpace.with(:TRACE=>true) do
    # ... code code code
    puts LSpace[:TRACE]
    # ... code code code
end

One key difference between the Clojure implementation and the Ruby gem to keep in mind is that in the Clojure version if you spawn a new thread from inside the block where the variable is bound, the new thread will get the bounded value, and in the Ruby version it wouldn't - so if you have to depend on that functionality you better pass those configuration options as arguments (or as member fields).


问:
What is casting supposed to mean?
When coding in low level languages like C I find that casting sometimes means 'reinterpret these bytes as if it had always been of this other type' and at other times as 'convert this value intelligently into this other type'.

What is the original meaning of the word and is there any consistency in when to expect a conversion and when to expect a raw reinterpretation?

答:
Casting in C is unique, quite unlike other languages. It is also never intelligent.

Casting in C converts values from one type to another using carefully defined rules. If you really need to know, read the standard. Otherwise the main points are:

Conversion between integer types preserve the value, if possible. If the destination has more bits this is widening and generally safe, but may involve sign extension. If narrower, bits will be lost.

Conversion between pointer types preserves the pointer value, but the results are often undefined, often non-portable and often useful for advanced scenarios.

Conversion between integer types and pointers are OK if the integer is big enough, and preserves the bit pattern (whatever that might happen to mean). If the integer is too small, the result is undefined but not useful. As a rule 'long' is wide enough for 'void *', but no guarantees! Pointers created this way may be invalid, in all kinds of interesting ways.

Conversion between float and integer types are arithmetic conversions as defined by an appropriate library routine (with truncation, not rounding).

You can cast the return value of a function to void. I never have. It does nothing.

Some casts are applied implicitly, and in some of those the compiler will issue a warning. Best to heed the warnings!

The dictionary definition for cast is best ignored, as being unhelpful. Many casts are better described by the terms conversion or coercion, so it's worth knowing those too.

C++ is MUCH more complicated, but you didn't ask that, did you?

Title: What is casting supposed to mean?


答:
C++ does not have multiple (dynamic) dispatch. Consider the following:

```<code>#include <iostream>

struct Foo {
   virtual ~Foo() {}
};

struct FooOne : public Foo {};

struct Bar {
   virtual ~Bar() {}
   virtual void dispatch (const Foo &) {
      std::cout << "Bar::Dispatch(const Foo &)\n";
   }
};

struct BarOne : public Bar {
   using Bar::dispatch;
   virtual void dispatch (const Foo &) {
      std::cout << "BarOne::Dispatch(const Foo &)\n";
   }
   virtual void dispatch (const FooOne &) {
      std::cout << "BarOne::Dispatch(const FooOne &)\n";
   }
};

void process (Bar & bar, const Foo & foo) {
   bar.dispatch (foo);
}

int main () {
   Foo foo;
   Bar bar;
   FooOne foo_one;
   BarOne bar_one;

   process (bar, foo);
   process (bar, foo_one);

   process (bar_one, foo);
   process (bar_one, foo_one);

   bar_one.dispatch (foo_one);

   return 0;
}
</code>```

The output from the above is

```<code>Bar::Dispatch(const Foo &)
Bar::Dispatch(const Foo &)
BarOne::Dispatch(const Foo &)
BarOne::Dispatch(const Foo &)
BarOne::Dispatch(const FooOne &)
</code>```

Within process(Foo& foo, const Bar& bar), C++ uses dynamic dispatch on argument foo in the statement foo.dispatch(bar). The third and fourth output lines show this C++-style dynamic dispatch in action. The fourth output line demonstrates that C++ does not have multiple dispatch. If it did, that fourth output line would be the same as the last.

That final line? That's static dispatch. The compiler knows at compile time exactly which function needs to be called. This final call does not go through the virtual table.

Body:
C++ does not have multiple (dynamic) dispatch. Consider the following:

#include <iostream>

struct Foo {
   virtual ~Foo() {}
};

struct FooOne : public Foo {};

struct Bar {
   virtual ~Bar() {}
   virtual void dispatch (const Foo &) {
      std::cout << "Bar::Dispatch(const Foo &)\n";
   }
};

struct BarOne : public Bar {
   using Bar::dispatch;
   virtual void dispatch (const Foo &) {
      std::cout << "BarOne::Dispatch(const Foo &)\n";
   }
   virtual void dispatch (const FooOne &) {
      std::cout << "BarOne::Dispatch(const FooOne &)\n";
   }
};

void process (Bar & bar, const Foo & foo) {
   bar.dispatch (foo);
}

int main () {
   Foo foo;
   Bar bar;
   FooOne foo_one;
   BarOne bar_one;

   process (bar, foo);
   process (bar, foo_one);

   process (bar_one, foo);
   process (bar_one, foo_one);

   bar_one.dispatch (foo_one);

   return 0;
}

The output from the above is

Bar::Dispatch(const Foo &)
Bar::Dispatch(const Foo &)
BarOne::Dispatch(const Foo &)
BarOne::Dispatch(const Foo &)
BarOne::Dispatch(const FooOne &)

Within process(Foo& foo, const Bar& bar), C++ uses dynamic dispatch on argument foo in the statement foo.dispatch(bar). The third and fourth output lines show this C++-style dynamic dispatch in action. The fourth output line demonstrates that C++ does not have multiple dispatch. If it did, that fourth output line would be the same as the last.

That final line? That's static dispatch. The compiler knows at compile time exactly which function needs to be called. This final call does not go through the virtual table.


问:
2 closest points between 2 rectangles
On a 2D plane, I have 2 rectangles.
I want to find the closest pair of points (one on each rectangle), which are closest to each other. By points I mean the corners of the rectangles. And no, they do not overlap.

Is there any way to do that other than checking all the distances between all the combinations of points and finding the smallest one?

答:
How you do it depends on what your "business" requirements are.

If simplicity of source code (maintainability) is your primary concern, then brute force calculation of all of the point to point distances will be a simple and effective method.  If you have to optimize for processing speed, then you may want to find an optimized algorithm.  I suspect that brute force will be nearly optimal in any case since there are only 16 point-to-point distances to calculate.

Title: 2 closest points between 2 rectangles


问:
What is an example of a computationally impossible business problem?
I have coworker who refuses to accept the reality that Turing machines (and Von Neuman machines by extension) cannot solve their own halting problem stating:

You can do anything with enough time and money.

He also dislikes theoretical problems arguing that:

In our field, we'll never run into those questions. We're application developers, not theoretical scientists.

Is there a good example of a business problem that is computationally impossible that I could use to help convince him of this?

答:
Perhaps the answer is that your co-worker is correct. Perhaps you have misunderstood Turing, or how it applies here?

All machines are finite, therefore there are no 'real' Turing machines and no programs that will never halt. A trivial program that executes a simple infinite loop could run 5 minutes or 50 years but on a finite machine it will halt. A non-trivial non-halting problem such as 'calculate pi exactly' will also halt, because eventually the calculation will exceed the capacity to store further digits.

The Turing result does not guarantee anything particularly useful on finite machines, so your quest is ultimately fruitless. Better to focus on how much time and how much money and leave infinity to the mathematicians.

You may think that a program like { while true: print "running"; print "halted"; } is a counter-example but it is not. This program has side effects, which may or may not cause it to halt. Ignoring the side effects, it is possible to devise a formal proof that this program will not halt. In this question we are only concerned with programs that evade formal proof of non-halting, where the question of halting is undecidable. This is not such a program.

It may help to distinguish 'strong' Turing from 'weak' Turing. Strong Turing machines are actually infinite and if they fail to halt, will run for infinite time. We cannot build those.

Weak Turing machines have finite limits on time and space, and they are the only kind we can build. We are interested in programs that cannot be proven to halt within those limits. Turing tells us that there are such programs but we cannot identify them. If the limits are low enough we can identify them by writing the program and running it to its limits.

The essence of Turing is that there are no shortcuts. The only way to be certain whether a problem is computationally feasible is to write the program, run it and find out. With enough time and money you can write all the programs, run them forever and over time, and find the ones that produce results (the halters). The others will still be running. Does you co-worker have enough time and money to do that?

Seriously though, the dispute is about limits. Turing and NP complete tell us that certain classes of problems cannot be solved by computers within any given budget or on any given schedule, no matter how large that budget or how generous that schedule may be. Examples of that kind of problem abound: breaking cryptographic keys; optimising the routes for making deliveries to hundreds of addresses; packing boxes in trucks; finding bugs in large programs!

So ask your co-worker for a budget and a schedule, and make a promise that you can produce a problem that cannot be solved within that budget or schedule. That promise will be very easy to keep.


答:
It may be useful to separate C casts to two groups:

Numeric casts - convert a number between one representation to another, attempting to keep the value. For example - (int)3.1 would be 3. There are exact rules defining what happens when the exact value can't be kept.

Pointer casts - Keep the memory address, but change the way it's dereferenced. For example, for float x=3.5, *(int *)&x will give 1080033280 - this integer is represented  by the same bit pattern that represents the float 3.5.

Title: What is casting supposed to mean?

Body:
When coding in low level languages like C I find that casting sometimes means 'reinterpret these bytes as if it had always been of this other type' and at other times as 'convert this value intelligently into this other type'.

What is the original meaning of the word and is there any consistency in when to expect a conversion and when to expect a raw reinterpretation?


问:
Data structures for bioinformatics
What are some data structures that should be known by somebody involved in bioinformatics?

I guess that everyone is expected to know about lists, hashes, balanced trees, etc, but I expect that there are domain specific data structures. Is there any book devoted to this subject?

Thanks,
Lucian

答:
If you are to do any work on large datasets you need to learn how to handle those efficiently.

Just think if you are going to do image analysis on a 2 Gb TIFF image.  Or sequence matching on a 150 Gb genome dataset.

When you move from a "nothing is slow" to a "this operation is fast and THIS is very, very slow but then THESE operations are fast" mindset, your algorithms tend to change.  It is relatively cheap to manipulate data in memory as opposed to having to fetch them from disk all the time, and it is relatively cheap to manipulate data in the cpu cache as opposed to having to fetch them from memory all the time.  In other words, algorithms that take that in consideration will be faster resulting in faster results, more publications and fame and Nobel prizes.

Title: Data structures for bioinformatics

ContentLicense: CC BY-SA 2.5


问:
Why are pointers to literals not possible?
Reference to a literal is possible only if the reference  is declared as constant.

But why is a pointer to a const object not possible in case of literals?
i.e.

```<code>int const& ref = 5;//
</code>```

But why is the same feature not available for a pointer, pointing to a constant object?

答:
In C++, literals exist only in the compiler. They are used in expressions, assignments and initialisations. The value of a literal may be found in the running program if it has been used to initialise a variable or temporary, but the literal itself is not.

A name that is a reference to a literal has meaning, because a reference is a value, so that wherever the name is used it can be replaced by the literal value itself. In certain special cases it is replaced by a temporary variable initialised to that value, and the required const qualifier protects that variable against being modified.

A name that is a pointer to a literal has no meaning. Pointers refer to storage locations, and a literal doesn't have one.

It would be hypothetically possible for C++ to allow pointers to literals, and to interpret them as pointing to a temporary variable initialised to that value, and presumably to protect that value with a const qualifier. The reasons it wasn't defined that way is either (a) it's not very useful (b) it would be incompatible with C. You'd have to ask Bjarne about that one.

Please note that the above applies to integers and floats. Literal strings have different rules, because in many ways they are already const pointers.


问:
DAL vs BLL functions' return types
Here is how I see the main differences between the DAL and the BLL:

The DAL directly query the database.

The DAL doesn't create new information. It may execute complex sql requests, joining several tables, but the result of such a request never gives any information that wasn't already in the database.

The BLL applies a business logic on the DAL's informations to create new informations.

Now, I wonder what datatypes these layers' functions are supposed to return. For the moment, all my DAL's function return DataTable. But my BLL's functions return some class or list of class that I created.

For example:

dal.getAllPortfolios() returns a DataTable (I'm working with Visual Studio), result of a join on several tables.

bll.getAllPortfolios() calls dal.getAllPortfolios, but return a List of Portfolio. With my public Portfolio class being in the BLL's namespace.

Sometimes, the BLL function doesn't really apply any "business logic" but only map the DataTable from de DAL into a BLL's class.

I wonder if this is ok. Maybe all the mapping work should be done by the DAL?
If this is the case, where to put my personal mapping classes? In the BLL or DAL namespace (those classes being required in layers above the BLL)?

答:
[Feedback]

So, I left my architecture how it was described in my first message, with my DAL returning DataTable objects. I was criticized for that choice. The argument was that, if different persons work on the DAL and the BLL, the one working on the BLL is going to need more documentation to use the DataTable objects. This person doesn't know the name of the columns in the DataTable, and maybe not even how to extract informations from a DataTable.

Title: DAL vs BLL functions' return types