答:
I'll start with the generic language neutral stuff first, and then I'll cover the python specific bits.

Why are you so sure that there needs to be a seperate library?  Is it because different developers working on the code? or are there plans to reuse the library in additional applications? or even to distribute the library on its own to customers.

In general, if your library has its own independent life, then you need to consider how you are going to manage the different release life cycle, and making it a seperate repository would help with that, at the cost of increasing the complexity for the developers working on both projects as part of the same development task.  Which way you decide on this will have long term impact on your team, and will have wide reaching consequences in how you optimise your teams work patterns and development practices.  both ways can work if implemented well, and both can fail badly if implemented and managed poorly.

With Python, best practice is to release your components as python packages. Whilst it is possible to have multiple packages in the same repository, I probably would push hard for a different repository per package, and then to have multiple python virtual environments. The development environment would have the packages installed using the source files in place, with the release environment would be created by installing the packages as finished packages.  Switching between these environments allows easy testing of all possible comnbinations.  This is the pythonic way.

Title: How to structure project where a library and application using the library are concurrently developed?

Body:
I am planning to develop a new application that will heavily use a library that will be developed from scratch specifically for the application, but made general enough for it to be used for other programs once it's finished.

So the development of this library is going to be heavily driven by the development of the application. It'll get features based on how important that feature is to the paired application. All the same, I want the library to be completely decoupled from the application. The application uses the library, but the library is unaware of the application and at some point of time, I'll want to ensure that the library can easily be used in other applications.

I'm looking for advice on how to structure this. In particular, where the code for the library should be located (same/different repo, some kind of build tool to keep them separate, etc).

Since this may be language dependent (as a result of build tools and other language differences), I am planning to use Python.


问:
Design Pattern for retry and error handling
I'm trying to find a good design pattern, or perhaps series of patterns, for injecting error handling and retry handling when getting data from a webservice.

For instance, I have:

```<code>do {
    //get the data here
    data = Datagetter.getMyData(request)

    if(data.hasError())
    {
        //handle error
    }
} while(shouldRetry());
</code>```

And I am trying to figure out a way to inject the mechanism the discovers and deals with any error, as well as the mechanism that handles how retrying works (should I wait? have I retried enough? should I modify a request parameter? etc).

I would guess I am not the first person faced with this, and there is a way to do this I just haven't discovered yet.

I have looked into chain-of-responsibility and strategy as possible solutions, but I can't seem to quite finagle them to work.

答:
What language are you using? Depending on the language(synchronious, asynchronious) you will have different solutions.

If it is JavaScript, promise is indeed the way to go.
Promises in JavaScript

If it is something like C#, you probably don't want to have a loop like you indicated, because you will be blocking the thread. In that scenario, I would look into setting up queuing system in combination with Command Design Pattern:

rabbitMQ |
0mq

Using queue you can send failed messages into the retry queue and retry them in the order they were submitted, potentially with some delay.

ContentLicense: CC BY-SA 3.0


答:
There are several things to consider here. It is worth reading up on the HTTP specification, specifically about idempotent rules, and to also consider a RESTful style of webservice interface.

In short, if you implement a webservice with GET or HEAD, then in theory it should be safe to call multiple times with the same parameters, but webservices that are implemented as POST, PUT or DELETE should only be called once, and if they fail then it should not be retried without consideration to the consequences of multiple requests.

The theory is that if you are GET'ing a resource, multiple gets to the same resource should be logically equivilent, and that there are no server state consequences for multiple GET requests for the same resource.  If the verb is a PUT, POST or DELETE then it is expected that the request could change the state of the server data, and so multiple / repeat requests are likely to have unwanted side effects.

To handle retries well, requires you to consider the error that occured. Retrying an error caused by a 404 may be handled differently from a tcp timeout error, or a 301 redirect, and to understand what that means in the context of this URL.

Title: Design Pattern for retry and error handling

Body:
I'm trying to find a good design pattern, or perhaps series of patterns, for injecting error handling and retry handling when getting data from a webservice.

For instance, I have:

```<code>do {
    //get the data here
    data = Datagetter.getMyData(request)

    if(data.hasError())
    {
        //handle error
    }
} while(shouldRetry());
</code>```

And I am trying to figure out a way to inject the mechanism the discovers and deals with any error, as well as the mechanism that handles how retrying works (should I wait? have I retried enough? should I modify a request parameter? etc).

I would guess I am not the first person faced with this, and there is a way to do this I just haven't discovered yet.

I have looked into chain-of-responsibility and strategy as possible solutions, but I can't seem to quite finagle them to work.


问:
How to structure project where a library and application using the library are concurrently developed?
I am planning to develop a new application that will heavily use a library that will be developed from scratch specifically for the application, but made general enough for it to be used for other programs once it's finished.

So the development of this library is going to be heavily driven by the development of the application. It'll get features based on how important that feature is to the paired application. All the same, I want the library to be completely decoupled from the application. The application uses the library, but the library is unaware of the application and at some point of time, I'll want to ensure that the library can easily be used in other applications.

I'm looking for advice on how to structure this. In particular, where the code for the library should be located (same/different repo, some kind of build tool to keep them separate, etc).

Since this may be language dependent (as a result of build tools and other language differences), I am planning to use Python.

答:
First, if your library is generic, it should NOT be influenced by the application. It should provide the functionality that it is designed to provide. Application is based on the library, not the other way around.

Whether you keep it the same repository or different one, doesn't matter - have it a separate project though.

I would do a technical design first and define all the required functionality. Then I would separate the functionality into presentation layer, business layer and data persistent layer. Then I would implement it starting from the bottom (persistence layer).


问:
Unit testing functions calling other tested functions
I have three functions:

ValidateUsername(), which determines if a string is a valid username according to some rules

SetUsername() which sets a string as a user's Username if it passes validation

AddNewUser(), which creates a new user and, among others, sets a string as his or hers Username using SetUsername()

All three should fail if the supplied username string is incorrect, yet ValidateUsername() is where the rules reside. How would I unit test this? Testing validation only in ValidateUsername() leaves the possibility that someone will mistakenly omit validation and set the username directly in AddNewUser(). On the other hand, repeating all different validation test cases for all functions seems counterproductive. What's the best practice?

答:
Unit testing is called that way because you are intending to test units of work, in your case each method is a unit of work and not the whole integration between them.

Let's assume your business requirement for ValidateUsername() method is to validate the user name according to certain requirements. Your unit test in this case should verify that validation was correct and rules are implemented correctly.

Now seems like for you other methods,  one of the business requirements is to call validation method - do just that. Ensure that the ValidateUsername was called indeed. You don't care whether it was executed correctly or not - that part is to be tested by your previous test for ValidateUsername unit.


答:
If I'm interpreting your question correctly, AddNewUser() calls SetUsername(), and SetUsername() calls ValidateUsername(). Two options come to mind:

1) Keep the existing structure, and write unit tests for the "one thing" that each function is responsible for, while assuming the "happy path" for its dependencies. So the ValidateUsername() tests would check valid and invalid usernames, the SetUsername() test would pass in a valid username and make sure that username ends up in the right place, and the AddNewUser() test would pass in valid user-construction data and make sure a user got added using that data.

2) Change the structure to something "flatter" so that the functions no longer depend on each other. So you might have a AttemptToAddUser() function that calls ValidateUsername(), then SetUsername(), then AddNewUser() all at the same level of the call stack.

The optimal answer depends heavily on your exact code, but I would expect it to be either #1 or something between #1 and #2. It might make perfect sense to pull ValidateUsername() up to the same level as AddNewUser(), but I have a hard time imagining a SetUsername() function being of any use outside the AddNewUser() function (assuming it's not a method on a User object or something).

And of course, regardless of how the unit tests work, you probably still want a small number of integration tests that check all of these functions together.

Title: Unit testing functions calling other tested functions

Body:
I have three functions:

ValidateUsername(), which determines if a string is a valid username according to some rules

SetUsername() which sets a string as a user's Username if it passes validation

AddNewUser(), which creates a new user and, among others, sets a string as his or hers Username using SetUsername()

All three should fail if the supplied username string is incorrect, yet ValidateUsername() is where the rules reside. How would I unit test this? Testing validation only in ValidateUsername() leaves the possibility that someone will mistakenly omit validation and set the username directly in AddNewUser(). On the other hand, repeating all different validation test cases for all functions seems counterproductive. What's the best practice?


问:
Abstracton layer to control services access to denormalized db entity
Our db is optimized for minimum join count (partially denormalized). E.g. our User entity contains account data (nickname, facebook id, etc), user numerical statistics (total games played, total wins, etc), guild related user information (guild id, membership type, etc) and so on - everything in the same table.

We use ORM - NHibernate. The user table is mapped (with all the fields) to User class.

Now I'm refactoring a model class AccountManagementService that provides a possibility to do some actions on an enclosed User. The model has the two dependencies: NHibernate and the User entity. The model logic is strictly tied to ORM methods (performs selects, does updates).

I think it's bad that the model knows about so many fields which it's not going to use. It doesn't need User.GuildId, statistics, etc. But since the model already should use ORM it's logical that it should know about entity classes.

I'm also worried that some operations with User should be done only through special services but other services theoretically can access and change any of the User's fields. E.g. AccountManagementService should not change User.Money directly but use UserMoneyService instead. But from a compiler viewpoint such change is perfectly valid.

Should I introduce other abstraction layers between services and entities to control an access and how can I do it? Can you see any other possibilities to improve the situation?

答:
You would probably want some layer(Facade pattern may be) that would expose only the necessary fields. Sounds like right now you are exposing your ORM models to all the layers and creating a spaghetti/unsecure code :)

Start by defining clear responsibilities of each layer and only exposing the model data that is necessary for the layers above.

If it requires a  translation layer in between, so be it.


问:
Class becoming God Object what pattern to use
I am developing Android app and my MainActivity is becoming God Object.

By the way native Activity class implementation is some sort of God Object already.

The problem is that my activity class is growing and growing.

Let me explain class responsibilites, for those who are not familiar with android.

Activity is like a screen with it's UI, lifecycle, functionality to communicate with OS.

Drawer is part of UI that brings to the activity side menu for navigation in the app.
What is the problem.

```<code>public abstract class MainActivity extends SingleFragmentToolBarActivity<T> implements Drawer.OnDrawerItemClickListener {
    private static final int PROFILE_HEADER_IDENTIFIER = 200;
    private float mDisplayDpWidth;
    private float mDisplayDpHeight;
    private Drawer.Result mNavigationDrawer;
    private AccountHeader.Result mAccountHeader;
    private double mDrawerWidthFactor = 0.9;
    private double mDrawerHeaderHeightFactor = 0.3;
    private IProfile<ProfileDrawerItem> mGuestProfile;
    private IProfile<ProfileDrawerItem> mLoggedInProfile;
    private boolean userIsLogged = false;
    public Drawer.Result getNavigationDrawer() {
        return this.mNavigationDrawer;
    }
    private AccountHeader.Result geAccountHeader() {
        return this.mAccountHeader;
    }
    private static final int PROFILE_SETTING = 1;
    private final AccountHeader.OnAccountHeaderSelectionViewClickListener mHeaderSelectionViewClickListener = new AccountHeader.OnAccountHeaderSelectionViewClickListener(.....);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setUpNavigationDrawer(savedInstanceState);
    }

    private void setUpNavigationDrawer(Bundle savedInstanceState) {
        DrawerImageLoader.init(new DrawerImageLoader.IDrawerImageLoader() {
            @Override
            public void set(ImageView imageView, Uri uri, Drawable placeholder) {
                Picasso.with(imageView.getContext()).load(uri).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Picasso.with(imageView.getContext()).cancelRequest(imageView);
            }

            @Override
            public Drawable placeholder(Context ctx) {
                return null;
            }
        });
        getDisplayMetrics();
        mGuestProfile = buildGuestProfile();
        mAccountHeader = buildNavigationHeader(savedInstanceState);
        mNavigationDrawer = buildDrawer(savedInstanceState);
    }
    protected Drawer.Result buildDrawer(Bundle savedInstanceState) {
     Drawer drawer =  new Drawer(this)
            .withActivity(this);
    ........
    }
    protected List<IProfile> getProfileItemList() {
    ......
    }
    protected AccountHeader.Result buildNavigationHeader(Bundle savedInstanceState) {
    ......
    }
    private ProfileDrawerItem buildGuestProfile() {
        .......
    }
    private ProfileDrawerItem buildLoggedInProfile(UserBean userBean) {
        .......
    }
    private void getDisplayMetrics() {
       .....
    }
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem iDrawerItem) {
     ......
    }

    protected Drawer addItemsIntoDrawer(Drawer buildDrawer) {
        ......
    }
    public void setDrawerWidthFactor(double factor) {
      ......
    }
    public void setDrawerHeaderHeightFactor(double factor) {
      ......
    }
</code>```

This is only declaration of some methods and class members.

This code above is ONLY for setting navigation drawer in my MainActivity, there will be quite more code in the future here for communicating with services and so on, if to left this as it is, soon I will get class with millions line of code, tons of class members and ton of methods.

Ho to solve this problem, what pattern can be acceptable in this way.

Setting drawer requires reference to the Activity.

I have some ideas how to solve this problem.

Use strategy pattern create interface with all these methods responsible for setting navigation drawer, but how can I pass reference to the activity into the interface implementation in this case I have to create not interface but abstract class and pass reference to the Activity into it's constructor.

 This will work, but I still think that it is not perfect, clean solution.

Please suggest what can I do to stop class growing.

EDIT

There is only small responsibility of my activity, there will be more important responsibilities in the future, so I have to get rid of writing a lot initialization code. I haven't post body of methods (300 lines of code). I have found one possible way here is to create some abstract class with basic methods and than create implementation and just use it in my activity when I need this.And in this case it will be possible to change it in runtime (before view has been inflated).

答:
I would first break it down into a number of classes with their own SINGLE responsibilities.

You would need to apply GRASP principals here first. GRASP

Secondly, I would look into strategy design pattern. Strategy Design Pattern


问:
Managing Massive Updates with Resource Access
I have a number of data servers that are pushing data to a main server as in this kind of architecture:

These data points (points for short) are updated randomly from each server. On the server, there are other user-defined data points (called Tags) that are expressions based on one or more points. The server has potentially hundreds of thousands of these Tags.

For example:

```
Points = {DataPointA, DataPointB, DataPointC}
Tags = {DataPointA * 1.8 + 32, DataPointA * DataPointC / 2, DataPointC * DataPointC}
```

The server back-end is written in C# and I've decided to use JavaScript to allow the user to define the expressions that make up the Tag values (mainly because the other part of this is a web-based visualization and I only want one scripting language).

Problem

I don't want to create a single JavaScript Engine for each Tag since that would be memory intensive. I've selected JInt for the JavaScript Engine (has to be mono-compatible so V8 is out) and I can create variables (Tags) and assign values (Points) but its not thread-safe. So I would have to wait until one Tag is finished updating before starting another. This is a performance bottleneck.

So I thought about creating a pool of Engines and pass out engines as they are available, the Tag locks it while using it and then releases it when it is finished. I'm not sure this is the best approach though because during my testing I've found the single Engine to be about 25% faster (or maybe its my implementation).

How would you approach this problem? I can't delegate the calculations down to the data servers because the expressions may use tags from multiple servers and that would require the servers to talk to each other or a bi-directional exchange with a repository on the main server.

Here is some code if you'd like to look through it:

Minimal Example with No Dependencies

Minimal Example with JInt Requirement

Note about the code: There is a level of indirection here with the use of Variable, this is because the data point "names" are actually GUID's, and a GUID doesn't make a good (or valid) variable name, so they have to be aliased into something that is a valid variable name.

答:
I would go a bit of different route here:

Setup  a Node.js based service on the mainframe.

Setup queuing system. (0MQ, RabbitMQ)

Use your Node.js to read from the queue and process.

Return the results to your main process through the queue as well.

Fully asynchronous and independent system.

Advantages: Node.js can handle millions of connections simultaniously. It's single threaded but asynchronious.

To take it a level up, spawn as many instances of of Node.js as you need and put them behind a load balancer (I doubt you will need that though).


问:
Would you create a specialized type just to wrap a primitive?
Often times in programming, we need to represent some value which can easily be represented using a simple primitive type.

For example, in a game we might need to represent the velocity of a moving object. This could easily be represented with a double value. This object might also have a value of mass; this can also be represented with a double.

Some would argue that we should have a Speed type and a Mass type for each of these, instead of the general-purpose double type. The argument for that is that this way we take advantage of 'strong-typing'; the compiler doesn't let us pass a speed for a mass or a mass for a speed and make mistakes like those.

This argument makes sense. However, I can't help but thinking that this would be an overkill.

So what would you use? A simple double (following KISS and keeping everything as simple as possible) or a type made for a specific purpose?

答: If the value is just that - the value, stick to using it as a field on another object. Mass and Speed are 2 different things indeed, but the fact that I created a separate type for each doesn't really mean I wouldn't mix the two up when I create new instances of those objects - in other words - NO, simple types are simple for a reason and you shouldn't complicate your code with new type for each simple value, because you could layer after layer trying to protect the future developer from mistakes, but you can only do so much.</p>


问:
how to do temporary tables in Linq to Entity Framework
Our application queries the database primarily using Linq queries backed by Entity Framework but we sometimes call legacy stored procedures.  Sometimes we want to replace an existing stored procedure with a Linq / Entity Framework query.  Is this possible to do even if the stored procedure uses temporary tables?  If so, how?</p>

答: Entity Framework doesn't support temporary tables in this manner.  The "temporary" table would have to be defined as a permanent one in the database, perhaps named with a tmp prefix.  You could then remove and add records in the usual way using Entity Framework.


问:
Drawing concentric circles without gaps
I want to fill a circle with alternate colors like a lollipop by drawing circumferences of increasing radius on a Cell matrix. I am currently using the Midpoint circle algorithm to get the points. The problem I have is that there are some gaps when filling a circle this way.

In the example below (original is number 1) I used pink and white to highlight the various circumferences. (Notice the black pixels)

The code of my implementation (1) is here: https://gist.github.com/beppe9000/e4a29542a76b8ee3b47f

I am looking for an algorithm that does not produce such gaps.

Update

It is important that the circle is filled using concentric passes because i also update some metadata in the cells as I get them in groups (each one corresponding to a circumference). I tried simplifying the problem, so you didn't get it all, I'm sorry if I'm not a great communicator... ;)

Basically I need the circumferences produced to be perfectly contiguous. That means no gaps between circles of radius n and n+1

Update 2

I tried the brute-force algorithm with some results, still lacking the ability to get individual circumferences. In particular I had great hopes for number 3...

答:
If you are interested in drawing concentric circles and don't mind performing a broard sweep of the AABB then the test to perform on each pixel is:

```<code>distanceFromCenter <= radius && distanceFromCenter > (radius - someThreshold)
</code>```

Or as a more concrete example:

```<code>void drawCircle(Point center, int radius, int thickness, Color color) {
    for (var x = center.x - radius; x < center.x + radius; x++) {
        for (var y = center.y - radius; y < center.y + radius; y++) {
            float distance = distanceFrom(x, y, center.x, center.y);
            if (distance <= radius && distance > radius - thickness) {
                drawPixel(x, y, color);
            }
        }
    }
}
</code>```

If these circles will need to be updated frequently and performance becomes an issue, then the relevant pixels could be stored a point array or a mask.

Title: Drawing concentric circles without gaps

Body:
If you are interested in drawing concentric circles and don't mind performing a broard sweep of the AABB then the test to perform on each pixel is:

distanceFromCenter <= radius && distanceFromCenter > (radius - someThreshold)

Or as a more concrete example:

void drawCircle(Point center, int radius, int thickness, Color color) {
    for (var x = center.x - radius; x < center.x + radius; x++) {
        for (var y = center.y - radius; y < center.y + radius; y++) {
            float distance = distanceFrom(x, y, center.x, center.y);
            if (distance <= radius && distance > radius - thickness) {
                drawPixel(x, y, color);
            }
        }
    }
}

If these circles will need to be updated frequently and performance becomes an issue, then the relevant pixels could be stored a point array or a mask.


答:
Honestly, why force a square peg into a round hole? Entity Framework supports calling stored procedures for a reason; because Entity Framework cannot address every use case that the database itself can support.

I would just use the right tool for the job (which in some of these cases appears to be stored procedures) and not worry about trying to create a faux "pure" architecture by forcing everything into Entity Framework.

Title: how to do temporary tables in Linq to Entity Framework

Body: Our application queries the database primarily using Linq queries backed by Entity Framework but we sometimes call legacy stored procedures.  Sometimes we want to replace an existing stored procedure with a Linq / Entity Framework query.  Is this possible to do even if the stored procedure uses temporary tables?  If so, how?</p>


问:
Does it affect the burn down chart?
We finished the development and closed the sprint(two weeks). But the code has not been reviewed. So in the third week we don't start a new sprint and keep clean up(refactor) the code. The scrum master told us that we can still log the time to the previous tasks.

My question is that since we close the sprint, does it effect the sprint's burn down chart?

答:
At the end of the day, if you're still working on a previous sprint in to week 3, it's still active. Most sprints are designed with refactoring and code review requirements already in mind. If you're coming to find that your refactoring/code review is bleeding over in to another week, I'd suggest adjusting your team's point forecasting to save time for those (pretty important) processes. </p>

<p>To answer your question more bluntly: no, I don't think it affects the burndown because of your current situation, but it ought to. Adjust/iterate on your proceses to save your team enough time to handle all sprint requirements during its alloted time. </p>

Title: Does it affect the burn down chart?

Body:
At the end of the day, if you're still working on a previous sprint in to week 3, it's still active. Most sprints are designed with refactoring and code review requirements already in mind. If you're coming to find that your refactoring/code review is bleeding over in to another week, I'd suggest adjusting your team's point forecasting to save time for those (pretty important) processes.

To answer your question more bluntly: no, I don't think it affects the burndown because of your current situation, but it ought to. Adjust/iterate on your proceses to save your team enough time to handle all sprint requirements during its alloted time.


问:
Simple and clean way of comparing three numbers
I've got some code that has a sequence of ifs that work, but just feel messy. Basically, I want to choose the largest of three integers and set a status flag to say which was chosen. My current code looks like this:

```<code>a = countAs();
b = countBs();
c = countCs();

if (a > b && a > c)
    status = MOSTLY_A;
else if (b > a && b > c)
    status = MOSTLY_B;
else if (c > a && c > b)
    status = MOSTLY_C;
else
    status = DONT_KNOW;
</code>```

This pattern occurs a few times, and with long variable names it gets a little difficult to visually confirm that each if is correct. I feel there might be a better and clearer way to do this; can anyone suggest anything?

There are some potential duplicates, but they don't quite align with this question.

In the suggested duplicate:   Approaches to checking multiple conditions?  all of the suggested solutions seem equally clumsy as the original code, so they do not provide a better solution.

And this post Elegant ways to handle if(if else) else deals only with nesting levels and asymmetry, which is not the problem here.

答:
I've had more of a think about this, so since my issue was mostly visual confirmation that all comparisons used the same variables, I think this might be a useful approach:

```<code>a = countAs();
b = countBs();
c = countCs();

if (FIRST_IS_LARGEST(a, b, c))
    status = MOSTLY_A;
else if (SECOND_IS_LARGEST(a, b, c))
    status = MOSTLY_B;
else if (THIRD_IS_LARGEST(a, b, c))
    status = MOSTLY_C;
else
    status = DONT_KNOW; /* NO_SINGLE_LARGEST is a better name? */
</code>```

That each macro takes a, b and c in the same order is easy to confirm, and the macro name saves me having to work out what all the comparisons and ANDs are doing.

Body:
I've had more of a think about this, so since my issue was mostly visual confirmation that all comparisons used the same variables, I think this might be a useful approach:

a = countAs();
b = countBs();
c = countCs();

if (FIRST_IS_LARGEST(a, b, c))
    status = MOSTLY_A;
else if (SECOND_IS_LARGEST(a, b, c))
    status = MOSTLY_B;
else if (THIRD_IS_LARGEST(a, b, c))
    status = MOSTLY_C;
else
    status = DONT_KNOW; /* NO_SINGLE_LARGEST is a better name? */

That each macro takes a, b and c in the same order is easy to confirm, and the macro name saves me having to work out what all the comparisons and ANDs are doing.


问:
Avoid numeric errors in Naive Bayes method
I am implementing the Naive Bayes method with Gaussian distribution.

The problem that I have is that the variance used on the Gaussian curve (calculated from a training set) is REALLY small. They are on the order of e-07. That means the whole equation,

```<code>(1/:math.sqrt(2*:math.pi*:math.sqrt(variance))) *
:math.exp(-0.5*(:math.pow(elem - mean, 2) / variance))
</code>```

results in really high values (such as 500, or even more). That becomes a problem later, when I multiply every probability p(x|C) together (it is a vector of 256 features).

I heard that is possible to use logarithms to avoid these kind of numbers. I searched on google but didn't find anything related to the subject. Does anyone know about that?

答:
Working with log-probabilities helps with the problem of intermediate values overflowing (and underflowing). Instead of calculating L = P(x1|C)P(x2|C)..., you calculate log L = log P(x1|C) + log P(x2|C) + .... You can do two things with log L:

If you're trying to maximize likelihood, you can directly maximize log-likelihood instead since log is monotonic and increasing.

If you want a normalized probability L/Z in [0,1], you can calculate this as exp(log L - log Z), which is possible even if L and Z are too large to fit in your floating point type.

In my experience this trick is often necessary when implementing probabilistic graphical models.


问:
Find the maximum number of pairs of numbers that are in a range, between two arrays
Lets say I have two arrays A and B

```<code>A = {1,2,3}
B = {12,11,67}
and have max sum value S = 10
</code>```

How many maximum number of unique pairs can be formed between the two arrays who's sum is less than or equal to S.

For e.g., the two possible values here are [1,11] [2,12] hence the answer is 2. If there are none, the answer is 0.

My solution was to sort both the arrays and then go do

```<code> if((Math.abs(A[i]-B[i]))<=S)
                 {
                 ans++;
             }
</code>```

Although it works for this case, clearly this is incorrect.

答:
The key to doing this efficiently is exploiting the fact that if a1 < a2, then pair(a2) \subseteq pair(a1), where pair(a) = {b \in B : a + b <= S}. Example Java code:

```<code>Arrays.sort( A );
Arrays.sort( B );
int count = 0;
int j = B.length - 1;
for( int i = 0; i < A.length; ++i ) {
    while( j >= 0 ) {
        if( A[i] + B[j] <= S ) {
            break;
        }
        --j;
    }
    if( j < 0 ) {
        break;
    }
    count += (j + 1);
}
</code>```

This code assumes there are no duplicates in A or B. The dominant operation is the O(n log n) sort. The loop traverses each list once, so the overall complexity is O(n log n + 2n) which is in O(n log n). If there are duplicates they can be removed from the sorted lists in linear time.

Body:
The key to doing this efficiently is exploiting the fact that if a1 < a2, then pair(a2) \subseteq pair(a1), where pair(a) = {b \in B : a + b <= S}. Example Java code:

Arrays.sort( A );
Arrays.sort( B );
int count = 0;
int j = B.length - 1;
for( int i = 0; i < A.length; ++i ) {
    while( j >= 0 ) {
        if( A[i] + B[j] <= S ) {
            break;
        }
        --j;
    }
    if( j < 0 ) {
        break;
    }
    count += (j + 1);
}

This code assumes there are no duplicates in A or B. The dominant operation is the O(n log n) sort. The loop traverses each list once, so the overall complexity is O(n log n + 2n) which is in O(n log n). If there are duplicates they can be removed from the sorted lists in linear time.


问:
@SuppressWarnings in generic array declaration
While doing a coding test, I ran into a problem where I need to initialize an array of generic type in Java. While trying to figure out how to do that, I looked at this Stack Overflow question and it requires that I suppress a warning which doesn't seem like a good practice, and might have other type safety issues. For clarity, here is the code:

```<code>public class GenSet<E> {
  private E[] a;

  public GenSet(Class<E> c, int s) {
    // Use Array native method to create array
    // of a type only known at run time
    @SuppressWarnings("unchecked")
    final E[] a = (E[]) Array.newInstance(c, s);
    this.a = a;
  }

  E get(int i) {
    return a[i];
  }
}
</code>```

Does this mean I am going about the problem wrong? Is it ok to have the @SuppressWarnings("unchecked") in this case?

Should I just use an ArrayList?

答:
In this case, it is perfectly okay to suppress the unchecked cast warning.

It's an unchecked cast because E is not known at runtime. So the runtime check can only check the cast up to Object[] (the erasure of E[]), but not actually up to E[] itself. (So for example, if E were Integer, then if the object's actual runtime class was String[], it would not be caught by the check even though it's not Integer[].)

Array.newInstance() returns Object, and not E[] (where E would be the type argument of the Class parameter), because it can be used to create both arrays of primitives and arrays of references. Type variables like E cannot represent primitive types, and the only supertype of array-of-primitive types is Object. Class objects representing primitive types are Class parameterized with its wrapper class as the type parameter, e.g. int.class has type Class<Integer>. But if you pass int.class to Array.newInstance(), you will create an int[], not E[] (which would be Integer[]). But if you pass a Class<E> representing a reference type, Array.newInstance() will return an E[].

So basically, calling Array.newInstance() with a Class<E> will always return either an E[], or an array of primitives. An array-of-primitives type is not a subtype of Object[], so it would fail a runtime check for Object[]. In other words, if the result is an Object[], it is guaranteed to be an E[]. So even though this cast only checks up to Object[] at runtime, and it doesn't check the part from Object[] up to E[], in this case, the check up to Object[] is sufficient to guarantee that it is an E[], and so the unchecked part is not an issue in this case, and it is effectively a fully checked cast.

By the way, from the code you have shown, you do not need to pass a class object to initialize GenSet or to use Array.newInstance(). That would only be necessary if your class actually used the class E at runtime. But it doesn't. All it does is create an array (that is not exposed to the outside of the class), and get elements from it. That can be achieved using an Object[]. You just need to cast to E when you take an element out (which is unchecked by which we know to be safe if we only put Es into it):

```<code>public class GenSet<E> {
  private Object[] a;

  public GenSet(int s) {
    this.a = new Object[s];
  }

  @SuppressWarnings("unchecked")
  E get(int i) {
    return (E)a[i];
  }
}
</code>```

Body:
In this case, it is perfectly okay to suppress the unchecked cast warning.

It's an unchecked cast because E is not known at runtime. So the runtime check can only check the cast up to Object[] (the erasure of E[]), but not actually up to E[] itself. (So for example, if E were Integer, then if the object's actual runtime class was String[], it would not be caught by the check even though it's not Integer[].)

Array.newInstance() returns Object, and not E[] (where E would be the type argument of the Class parameter), because it can be used to create both arrays of primitives and arrays of references. Type variables like E cannot represent primitive types, and the only supertype of array-of-primitive types is Object. Class objects representing primitive types are Class parameterized with its wrapper class as the type parameter, e.g. int.class has type Class<Integer>. But if you pass int.class to Array.newInstance(), you will create an int[], not E[] (which would be Integer[]). But if you pass a Class<E> representing a reference type, Array.newInstance() will return an E[].

So basically, calling Array.newInstance() with a Class<E> will always return either an E[], or an array of primitives. An array-of-primitives type is not a subtype of Object[], so it would fail a runtime check for Object[]. In other words, if the result is an Object[], it is guaranteed to be an E[]. So even though this cast only checks up to Object[] at runtime, and it doesn't check the part from Object[] up to E[], in this case, the check up to Object[] is sufficient to guarantee that it is an E[], and so the unchecked part is not an issue in this case, and it is effectively a fully checked cast.

By the way, from the code you have shown, you do not need to pass a class object to initialize GenSet or to use Array.newInstance(). That would only be necessary if your class actually used the class E at runtime. But it doesn't. All it does is create an array (that is not exposed to the outside of the class), and get elements from it. That can be achieved using an Object[]. You just need to cast to E when you take an element out (which is unchecked by which we know to be safe if we only put Es into it):

public class GenSet<E> {
  private Object[] a;

  public GenSet(int s) {
    this.a = new Object[s];
  }

  @SuppressWarnings("unchecked")
  E get(int i) {
    return (E)a[i];
  }
}


问:
How safe is it to compile a piece of source code from a random stranger?
Suppose I'm reviewing code that job applicants send to prove their skills. Clearly I don't want to run executables they send. Not so clearly I'd rather not run the result of compilation of their code (just for example, Java allows to hide runnable code in comments).

What about compiling their code? I want compiler warnings if any but what if their code contains some clever character sequences which exploit my compiler and my compiler compromises my machine?

When I Google for "compiler vulnerabilities" the hits I get are all about compiler optimizations and code emission and whether emitted code is as secure as original source code was intended to be.

Are compilers typically validated to ensure they won't compromise the user machine when compiling some clever piece of code? How safe is it to compile a piece of code from a stranger?

答:
Well, I would start with "reviewing their code".  Why is there a need to actually run the code?

Apart from that, there are a lot of online compilers where you can just put in the code and compile and/or run it. You can make that a requirement: it compiles in this and that online compiler.

Here's an example of a page with online compilers: Online compilers

Code for review for a job interview shouldn't be so large anyhow as for you not to understand what's going on.


答:
There shouldn't be any risk just compiling the code. In theory there could be a bug in the compiler that a clever hacker could take advantage of but is sounds extremely unlikely.

Be aware that building may be unsafe. For example in C# 'build event' allows you to specify arbitrary command lines to execute before and after building, which is obviously dangerous, and a lot easier to exploit than say buffer overflows in the compiler code.

Title: How safe is it to compile a piece of source code from a random stranger?

Body:
Suppose I'm reviewing code that job applicants send to prove their skills. Clearly I don't want to run executables they send. Not so clearly I'd rather not run the result of compilation of their code (just for example, Java allows to hide runnable code in comments).

What about compiling their code? I want compiler warnings if any but what if their code contains some clever character sequences which exploit my compiler and my compiler compromises my machine?

When I Google for "compiler vulnerabilities" the hits I get are all about compiler optimizations and code emission and whether emitted code is as secure as original source code was intended to be.

Are compilers typically validated to ensure they won't compromise the user machine when compiling some clever piece of code? How safe is it to compile a piece of code from a stranger?


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
"Evil" arguments aside, in my experience I've found a high correlation between a programmer's use the ternary operator and the likelihood of his or her entire codebase being difficult to read, follow, and maintain (if not outright undocumented). If a programmer's more concerned with saving a few 1-2 character lines than someone being able to understand his or her code, then any minor confusion understanding a ternary statement is usually the tip of the iceberg.

Ternary operators attract magic numbers like s**t attracts flies.

If I was looking for an Open Source library to solve a particular problem, and I saw code such as the original poster's ternary operators in a candidate for said library, warning bells would start going off in my head and I'd start considering moving on to some other project to borrow from.

Title: Ternary operator considered harmful?

ContentLicense: CC BY-SA 2.5


答:
Reading source code: totally safe.
Compiling source code: totally safe.
Executing compiled binaries: well... that depends.

Compiling is just the computer reading the source code and writing its equivalent in binary form. After compilation, you just have 2 documents: one human-readable, and another computer-readable. Unless you get the computer to read (ie run) the 2nd document, nothing is going to happen.


问:
Separate interface for mutation methods
I've been working on refactoring some code, and I think I may have taken the first step down the rabbit hole. I'm writing the example in Java, but I suppose it could be agnostic.

I have an interface Foo defined as

```<code>public interface Foo {

    int getX();

    int getY();

    int getZ();
}
</code>```

And an implementation as

```<code>public final class DefaultFoo implements Foo {

    public DefaultFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    private final int x;
    private final int y;
    private final int z;
}
</code>```

I also have an interface MutableFoo that provides matching mutators

```<code>/**
 * This class extends Foo, because a 'write-only' instance should not
 * be possible and a bit counter-intuitive.
 */
public interface MutableFoo extends Foo {

    void setX(int newX);

    void setY(int newY);

    void setZ(int newZ);
}
</code>```

There are a couple of implementations of MutableFoo that could exist (I haven't implemented them yet). One of them is

```<code>public final class DefaultMutableFoo implements MutableFoo {

    /**
     * A DefaultMutableFoo is not conceptually constructed
     * without all values being set.
     */
    public DefaultMutableFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public void setX(int newX) {
        this.x = newX;
    }

    public int getY() {
        return y;
    }

    public void setY(int newY) {
        this.y = newY;
    }

    public int getZ() {
        return z;
    }

    public void setZ(int newZ) {
        this.z = newZ;
    }

    private int x;
    private int y;
    private int z;
}
</code>```

The reason I have split these is because it is equally likely for each to be used. Meaning, it is equally likely that someone using these classes will want an immutable instance, as it is they will want a mutable one.

The primary use-case that I have is an interface called StatSet that represents certain combat details for a game (hitpoints, attack, defense). However, the "effective" stats, or the actual stats, are a result of the base stats, that can never be changed, and the trained stats, which can be increased. These two are related by

```<code>/**
 * The EffectiveStats can never be modified independently of either the baseStats
 * or trained stats. As such, this StatSet must never provide mutators.
 */
public StatSet calculateEffectiveStats() {
    int effectiveHitpoints =
        baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    int effectiveAttack =
        baseStats.getAttack() + (trainedStats.getAttack() / 4);
    int effectiveDefense =
        baseStats.getDefense() + (trainedStats.getDefense() / 4);

    return StatSetFactory.createImmutableStatSet(effectiveHitpoints, effectiveAttack, effectiveDefense);
}
</code>```

the trainedStats are increased after every battle like

```<code>public void grantExperience() {
    int hitpointsReward = 0;
    int attackReward = 0;
    int defenseReward = 0;

    final StatSet enemyStats = enemy.getEffectiveStats();
    final StatSet currentStats = player.getEffectiveStats();
    if (enemyStats.getHitpoints() >= currentStats.getHitpoints()) {
        hitpointsReward++;
    }
    if (enemyStats.getAttack() >= currentStats.getAttack()) {
        attackReward++;
    }
    if (enemyStats.getDefense() >= currentStats.getDefense()) {
        defenseReward++;
    }

    final MutableStatSet trainedStats = player.getTrainedStats();
    trainedStats.increaseHitpoints(hitpointsReward);
    trainedStats.increaseAttack(attackReward);
    trainedStats.increaseDefense(defenseReward);
}
</code>```

but they aren't increased just after battle. Using certain items, employing certain tactics, clever use of the battlefield all can grant different experience.

Now for my questions:

Is there a name for splitting interfaces by accessors and mutators into separate interfaces?

Is splitting them in this way the 'right' approach if they are equally likely to be used, or is there a different, more accepted pattern that I should use instead (eg. Foo foo = FooFactory.createImmutableFoo(); which could return DefaultFoo or DefaultMutableFoo but is hidden because createImmutableFoo returns Foo)?

Are there any immediately foreseeable downsides to using this pattern, save for complicating the interface hierarchy?

The reason I started designing it this way is because I'm of the mindset that all implementers of an interface should adhere to the simplest interface possible, and provide nothing more. By adding setters to the interface, now the effective stats can be modified independently of its parts.

Making a new class for the EffectiveStatSet does not make much sense as we're not extending the functionality in any way. We could change the implementation, and make an EffectiveStatSet a composite of two different StatSets, but I feel that is not the right solution;

```<code>public class EffectiveStatSet implements StatSet {

    public EffectiveStatSet(StatSet baseStats, StatSet trainedStats) {
        // ...
    }

    public int getHitpoints() {
        return baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    }
}
</code>```

答:
Is there a name for splitting interfaces by accessors and
  mutators into separate interfaces?

There could be a name for this if this seperation is usefull and provides a benefit which i donot see. If the separatons does not provide a benefit the other two questions make no sense.

Can you tell us any business use-case where the two seperate Interfaces provide us benefit or is this question an academic problem (YAGNI)?

I can think of shop with a mutable cart (you can put more articles in) that can become an order where the articles cannote be changed by the customer any more. The order-status is still mutable.

Implementations that i have seen do not seperate the interfaces

there is no interface ReadOnlyList in java

The ReadOnly version uses the "WritableInterface" and throws an exception if a write method is uesed

Title: Separate interface for mutation methods


答:
I am pretty sure somewhere in the business there are some clever guys who have already created such a hack for a specific language and compiler version. My favorite place to look for something like this would probably be the International Obfuscated C contest - (do not know if there is something comparable for Java).  However, in reality, how high do you consider the risk, assumed that

the applicant makes a plausible impression on you he really wants the job at your company (and not a lawsuit)

the guy does not know how much reviewing is done at yours

he / she does not know which exact compiler version you are using

he / she does not know if you use a virtual environment or an online compiler, just to be safe

you do not accept programs which are too large to be effectively reviewed

you do not compile anything which looks suspicious to you

there are not many people in the world who actually know how to technically accomplish such a task (and googling alone won't give you a "quick ref" or tutorial on this, as you have already found out by yourself).

So though compiling is not "totally safe" in theory, IMHO in reality the risk is extremely low that your "compiler gets pwned".


问:
DB Schema design : single table with more columns vs multiple tables with fewer colomns
What would be better DB design for a social network website.
A single table with more columns and less rows or multiple table with fewer columns but more rows.

For example:
User can post an update on their wall or in a group.

Two DB designs that I could think of are:

1)
UserPosts: id, userId, post, datetime
UserGroupPost: id, groupId, userId, post, datetime

Potentail problem : Might require joins, which can (in future) be a slow query.

2)
Posts: id, userId, groupId, post, datetime
(where groupid would be null if user posts on their wall)

Potential Problem : Looping over large dataset could take a (long)time.

Where can I get better performance when data increases?
Is there any other(better) way?

答:
Any thing ("Entity") that can exist on its own, independently of anything else, should have its own table.

User: id, name, hashed_password, join_date, birth_date

Group: id, name

Relationships between things require generally require "linking" tables.

Post: id, user_id, group_id, post_date, post_title, post_content

The key to success is proper indexing of any field where you join between tables or on which you filter results.

Also, consider using a dummy (non-NULL) Group value for posts to a user's own "wall" - NULLs are often not included in indexes, which will make your queries for these posts run [far] slower.


问:
Javascript unit testing - mocks or fixtures?
Interested in some opnion...

I'm introducing unit testing of JS into a team, it'll largely be testing modules with many dom interactions and updates.

Traditionally I've always used mocks and spys when testing libraries such as jquery, but as this is a team new to unit tests I thought fixtures may help them to get up and running quicker.

Some concerns I have around the use of fixtures are:

Tests could become more like integration tests - which we already have

Lose the benefit of better written, strcutured, abstracted code that unit testing encourages.

Fixtures will slow speed of the tests

Maintenance of fixtures could become a hidden overhead.

But really interested to hear others opinion.

Thanks in advance

答:
Indeed, such fixtures are not a good way to run unit tests. The goal of unit tests is to test a very specific (and often very small) part of the code in isolation from the remaining code and the environment. By making those tests rely on the particular state of the web page, you lose the “unit” aspect of your tests, meaning that you'll rather have system and integration tests instead.

You're also right about the speed aspect of the tests. DOM is known for being terribly slow, so if your tests rely heavily on DOM, don't expect to run thousands of them in a second.

You're equally right that maintenance of fixtures may be a difficult task. In essence, if the HTML structure of your web application changes, you have to reflect that in possibly every fixture. If fixtures are written by hand, you'll waste a lot of time doing that. If fixtures are generated, you may end up wasting a lot of time tuning the generator itself.

The benefit of your approach becomes noticeable when the choice is between testing at least something, or not testing anything at all. If the project is under time pressure, fixtures may be a good choice to introduce your team to automated testing.

If the project is small enough, such tests may be the only thing you need: adding unit testing won't bring too much in long term and will impact the project in short term.

If the project is large but there is no time to develop a full suite of unit tests, start by system testing with fixtures. Once you have enough branch coverage, you may focus on new code, code with the least coverage and code with the most bugs to add unit tests, class by class.

An important benefit is that if your code base is not well designed for unit tests, adding them now will require refactoring, which, in turn, may generate regressions. If you already have enough system tests using fixtures, your team may be more comfortable doing refactoring when adding unit tests later, knowing that they have system tests to detect at least some regressions.


问:
Merits of Namepsaces/Packages
Some programming languages (e.g. Java and C++) have language features called "packages" or "namespaces".  How useful is it really to have namespaces?  It is possible to mark functions and classes as belonging to some particular library without using such a language feature, like the SDL does (e.g. SDL_BlitSurface()).  Are namespaces not helpful enough to be worth having?  Are they useful in libraries but not in applications?  Are they useful everywhere except for in small projects?  Thoughts?

答: Aren't name prefixes the same thing as namespacing, except that it's done in a way that is less useful and more difficult to read/parse? Doesn't the question answer itself?

Title: Merits of Namepsaces/Packages


答:
It depends.

This piece of makefile could delete your home directory :

```<code>all:
    rm -rf ~
</code>```

So, if you need to use a tool (like cmake or makefile system), then it is not safe. It just depends how malicious the coder is.

On the other side, compilers are programmed by people, therefore they got bugs. So, maybe it could be possible that someone found a way to execute malicious code during the compilation.

As suggested in the comments, if you want to be sure that no funny things is being done to your machine, use a virtual machine.

Body:
It depends.

This piece of makefile could delete your home directory :

all:
    rm -rf ~

So, if you need to use a tool (like cmake or makefile system), then it is not safe. It just depends how malicious the coder is.

On the other side, compilers are programmed by people, therefore they got bugs. So, maybe it could be possible that someone found a way to execute malicious code during the compilation.

As suggested in the comments, if you want to be sure that no funny things is being done to your machine, use a virtual machine.


答:
TL:DR; Your code is already correct and "clean".

I see a lot of people waffling around the answer but everyone is missing the forest through the trees.  Let's do the full computer science and mathematical analysis to completely understand this question.

First, we note that we have 3 variables, each with 3 states: <, =, or >. The total number of permutations is 3^3 = 27 states, which I'll assign an unique number, denoted P#, for each state. This P# number is a factorial number system.

Enumerating all the permutations we have:

```<code>a ? b | a ? c | b ? c |P#| State
------+-------+-------+--+------------
a < b | a < c | b < c | 0| C
a = b | a < c | b < c | 1| C
a > b | a < c | b < c | 2| C
a < b | a = c | b < c | 3| impossible a<b b<a
a = b | a = c | b < c | 4| impossible a<a
a > b | a = c | b < c | 5| A=C > B
a < b | a > c | b < c | 6| impossible a<c a>c
a = b | a > c | b < c | 7| impossible a<c a>c
a > b | a > c | b < c | 8| A
a < b | a < c | b = c | 9| B=C > A
a = b | a < c | b = c |10| impossible a<a
a > b | a < c | b = c |11| impossible a<c a>c
a < b | a = c | b = c |12| impossible a<a
a = b | a = c | b = c |13| A=B=C
a > b | a = c | b = c |14| impossible a>a
a < b | a > c | b = c |15| impossible a<c a>c
a = b | a > c | b = c |16| impossible a>a
a > b | a > c | b = c |17| A
a < b | a < c | b > c |18| B
a = b | a < c | b > c |19| impossible b<c b>c
a > b | a < c | b > c |20| impossible a<c a>c
a < b | a = c | b > c |21| B
a = b | a = c | b > c |22| impossible a>a
a > b | a = c | b > c |23| impossible c>b b>c
a < b | a > c | b > c |24| B
a = b | a > c | b > c |25| A=B > C
a > b | a > c | b > c |26| A
</code>```

By inspection we see we have:

3 states where A is the max,

3 states where B is the max,

3 states where C is the max, and

4 states where either A=B, or B=C.

Let's write a program (see the footnote) to enumerate all these permutations with values for A, B, and C.  Stable sorting by P#:

```<code>a ?? b | a ?? c | b ?? c |P#| State
1 <  2 | 1 <  3 | 2 <  3 | 0| C
1 == 1 | 1 <  2 | 1 <  2 | 1| C
1 == 1 | 1 <  3 | 1 <  3 | 1| C
2 == 2 | 2 <  3 | 2 <  3 | 1| C
2  > 1 | 2 <  3 | 1 <  3 | 2| C
2  > 1 | 2 == 2 | 1 <  2 | 5| ??
3  > 1 | 3 == 3 | 1 <  3 | 5| ??
3  > 2 | 3 == 3 | 2 <  3 | 5| ??
3  > 1 | 3  > 2 | 1 <  2 | 8| A
1 <  2 | 1 <  2 | 2 == 2 | 9| ??
1 <  3 | 1 <  3 | 3 == 3 | 9| ??
2 <  3 | 2 <  3 | 3 == 3 | 9| ??
1 == 1 | 1 == 1 | 1 == 1 |13| ??
2 == 2 | 2 == 2 | 2 == 2 |13| ??
3 == 3 | 3 == 3 | 3 == 3 |13| ??
2  > 1 | 2  > 1 | 1 == 1 |17| A
3  > 1 | 3  > 1 | 1 == 1 |17| A
3  > 2 | 3  > 2 | 2 == 2 |17| A
1 <  3 | 1 <  2 | 3  > 2 |18| B
1 <  2 | 1 == 1 | 2  > 1 |21| B
1 <  3 | 1 == 1 | 3  > 1 |21| B
2 <  3 | 2 == 2 | 3  > 2 |21| B
2 <  3 | 2  > 1 | 3  > 1 |24| B
2 == 2 | 2  > 1 | 2  > 1 |25| ??
3 == 3 | 3  > 1 | 3  > 1 |25| ??
3 == 3 | 3  > 2 | 3  > 2 |25| ??
3  > 2 | 3  > 1 | 2  > 1 |26| A
</code>```

In case you were wondering how I knew which P# states were impossible, now you know. :-)

The minimum number of comparisons to determine the order is:

Log2(27) = Log(27)/Log(2) = ~4.75 = 5 comparisons

i.e. coredump gave the correct 5 minimal number of comparisons.  I would format his code as:

```<code>status_t index_of_max_3(a,b,c)
{
    if (a > b) {
        if (a == c) return DONT_KNOW; // max a or c
        if (a >  c) return MOSTLY_A ;
        else        return MOSTLY_C ;
    } else {
        if (a == b) return DONT_KNOW; // max a or b
        if (b >  c) return MOSTLY_B ;
        else        return MOSTLY_C ;
    }
}
</code>```

For your problem we don't care about testing for equality so we can omit 2 tests.

It doesn't matter how clean/bad the code is if it gets the wrong answer so this is a good sign that you are handling all the cases correctly!

Next, as for simplicity, people keep trying to "improve" the answer,
where they think improving means "optimizing" the number of comparisons,
but that isn't strictly what you are asking.  You confused everyone where you asked
"I feel there might be a better" but didn't define what 'better' means. Less comparisons? Less code? Optimal comparisons?

Now since you are asking about code readability (given correctness) I would only make one change to your code for readability: Align the first test with the others.

```<code>        if      (a > b && a > c)
            status = MOSTLY_A;
        else if (b > a && b > c)
            status = MOSTLY_B;
        else if (c > a && c > b)
            status = MOSTLY_C;
        else
            status = DONT_KNOW; // a=b or b=c, we don't care
</code>```

Personally I would write it the following way but this may be too unorthodox for your coding standards:

```<code>        if      (a > b && a > c) status = MOSTLY_A ;
        else if (b > a && b > c) status = MOSTLY_B ;
        else if (c > a && c > b) status = MOSTLY_C ;
        else /*  a==b  || b ==c*/status = DONT_KNOW; // a=b or b=c, we don't care
</code>```

Footnote: Here is the C++ code to generate the permutations:

```<code>#include <stdio.h>

char txt[]  = "< == > ";
enum cmp      { LESS, EQUAL, GREATER };
int  val[3] = { 1, 2, 3 };

enum state    { DONT_KNOW, MOSTLY_A, MOSTLY_B, MOSTLY_C };
char descr[]= "??A B C ";

cmp Compare( int x, int y ) {
    if( x < y ) return LESS;
    if( x > y ) return GREATER;
    /*  x==y */ return EQUAL;
}

int main() {
    int i, j, k;
    int a, b, c;

    printf( "a ?? b | a ?? c | b ?? c |P#| State\n" );
    for( i = 0; i < 3; i++ ) {
        a = val[ i ];
        for( j = 0; j < 3; j++ ) {
            b = val[ j ];
            for( k = 0; k < 3; k++ ) {
                c = val[ k ];

                int cmpAB = Compare( a, b );
                int cmpAC = Compare( a, c );
                int cmpBC = Compare( b, c );
                int n     = (cmpBC * 9) + (cmpAC * 3) + cmpAB; // Reconstruct unique P#

                printf( "%d %c%c %d | %d %c%c %d | %d %c%c %d |%2d| "
                    , a, txt[cmpAB*2+0], txt[cmpAB*2+1], b
                    , a, txt[cmpAC*2+0], txt[cmpAC*2+1], c
                    , b, txt[cmpBC*2+0], txt[cmpBC*2+1], c
                    , n
                );

                int status;
                if      (a > b && a > c) status = MOSTLY_A;
                else if (b > a && b > c) status = MOSTLY_B;
                else if (c > a && c > b) status = MOSTLY_C;
                else /*  a ==b || b== c*/status = DONT_KNOW; // a=b, or b=c

                printf( "%c%c\n", descr[status*2+0], descr[status*2+1] );
            }
        }
    }
    return 0;
}
</code>```

Edits: Based on feedback, moved TL:DR to top, removed unsorted table, clarified 27, cleaned up code, described impossible states.

Title: Simple and clean way of comparing three numbers

Body:
I've got some code that has a sequence of ifs that work, but just feel messy. Basically, I want to choose the largest of three integers and set a status flag to say which was chosen. My current code looks like this:

```<code>a = countAs();
b = countBs();
c = countCs();

if (a > b && a > c)
    status = MOSTLY_A;
else if (b > a && b > c)
    status = MOSTLY_B;
else if (c > a && c > b)
    status = MOSTLY_C;
else
    status = DONT_KNOW;
</code>```

This pattern occurs a few times, and with long variable names it gets a little difficult to visually confirm that each if is correct. I feel there might be a better and clearer way to do this; can anyone suggest anything?

There are some potential duplicates, but they don't quite align with this question.

In the suggested duplicate:   Approaches to checking multiple conditions?  all of the suggested solutions seem equally clumsy as the original code, so they do not provide a better solution.

And this post Elegant ways to handle if(if else) else deals only with nesting levels and asymmetry, which is not the problem here.

Body:
TL:DR; Your code is already correct and "clean".

I see a lot of people waffling around the answer but everyone is missing the forest through the trees.  Let's do the full computer science and mathematical analysis to completely understand this question.

First, we note that we have 3 variables, each with 3 states: <, =, or >. The total number of permutations is 3^3 = 27 states, which I'll assign an unique number, denoted P#, for each state. This P# number is a factorial number system.

Enumerating all the permutations we have:

a ? b | a ? c | b ? c |P#| State
------+-------+-------+--+------------
a < b | a < c | b < c | 0| C
a = b | a < c | b < c | 1| C
a > b | a < c | b < c | 2| C
a < b | a = c | b < c | 3| impossible a<b b<a
a = b | a = c | b < c | 4| impossible a<a
a > b | a = c | b < c | 5| A=C > B
a < b | a > c | b < c | 6| impossible a<c a>c
a = b | a > c | b < c | 7| impossible a<c a>c
a > b | a > c | b < c | 8| A
a < b | a < c | b = c | 9| B=C > A
a = b | a < c | b = c |10| impossible a<a
a > b | a < c | b = c |11| impossible a<c a>c
a < b | a = c | b = c |12| impossible a<a
a = b | a = c | b = c |13| A=B=C
a > b | a = c | b = c |14| impossible a>a
a < b | a > c | b = c |15| impossible a<c a>c
a = b | a > c | b = c |16| impossible a>a
a > b | a > c | b = c |17| A
a < b | a < c | b > c |18| B
a = b | a < c | b > c |19| impossible b<c b>c
a > b | a < c | b > c |20| impossible a<c a>c
a < b | a = c | b > c |21| B
a = b | a = c | b > c |22| impossible a>a
a > b | a = c | b > c |23| impossible c>b b>c
a < b | a > c | b > c |24| B
a = b | a > c | b > c |25| A=B > C
a > b | a > c | b > c |26| A

By inspection we see we have:

3 states where A is the max,

3 states where B is the max,

3 states where C is the max, and

4 states where either A=B, or B=C.

Let's write a program (see the footnote) to enumerate all these permutations with values for A, B, and C.  Stable sorting by P#:

a ?? b | a ?? c | b ?? c |P#| State
1 <  2 | 1 <  3 | 2 <  3 | 0| C
1 == 1 | 1 <  2 | 1 <  2 | 1| C
1 == 1 | 1 <  3 | 1 <  3 | 1| C
2 == 2 | 2 <  3 | 2 <  3 | 1| C
2  > 1 | 2 <  3 | 1 <  3 | 2| C
2  > 1 | 2 == 2 | 1 <  2 | 5| ??
3  > 1 | 3 == 3 | 1 <  3 | 5| ??
3  > 2 | 3 == 3 | 2 <  3 | 5| ??
3  > 1 | 3  > 2 | 1 <  2 | 8| A
1 <  2 | 1 <  2 | 2 == 2 | 9| ??
1 <  3 | 1 <  3 | 3 == 3 | 9| ??
2 <  3 | 2 <  3 | 3 == 3 | 9| ??
1 == 1 | 1 == 1 | 1 == 1 |13| ??
2 == 2 | 2 == 2 | 2 == 2 |13| ??
3 == 3 | 3 == 3 | 3 == 3 |13| ??
2  > 1 | 2  > 1 | 1 == 1 |17| A
3  > 1 | 3  > 1 | 1 == 1 |17| A
3  > 2 | 3  > 2 | 2 == 2 |17| A
1 <  3 | 1 <  2 | 3  > 2 |18| B
1 <  2 | 1 == 1 | 2  > 1 |21| B
1 <  3 | 1 == 1 | 3  > 1 |21| B
2 <  3 | 2 == 2 | 3  > 2 |21| B
2 <  3 | 2  > 1 | 3  > 1 |24| B
2 == 2 | 2  > 1 | 2  > 1 |25| ??
3 == 3 | 3  > 1 | 3  > 1 |25| ??
3 == 3 | 3  > 2 | 3  > 2 |25| ??
3  > 2 | 3  > 1 | 2  > 1 |26| A

In case you were wondering how I knew which P# states were impossible, now you know. :-)

The minimum number of comparisons to determine the order is:

Log2(27) = Log(27)/Log(2) = ~4.75 = 5 comparisons

i.e. coredump gave the correct 5 minimal number of comparisons.  I would format his code as:

status_t index_of_max_3(a,b,c)
{
    if (a > b) {
        if (a == c) return DONT_KNOW; // max a or c
        if (a >  c) return MOSTLY_A ;
        else        return MOSTLY_C ;
    } else {
        if (a == b) return DONT_KNOW; // max a or b
        if (b >  c) return MOSTLY_B ;
        else        return MOSTLY_C ;
    }
}

For your problem we don't care about testing for equality so we can omit 2 tests.

It doesn't matter how clean/bad the code is if it gets the wrong answer so this is a good sign that you are handling all the cases correctly!

Next, as for simplicity, people keep trying to "improve" the answer,
where they think improving means "optimizing" the number of comparisons,
but that isn't strictly what you are asking.  You confused everyone where you asked
"I feel there might be a better" but didn't define what 'better' means. Less comparisons? Less code? Optimal comparisons?

Now since you are asking about code readability (given correctness) I would only make one change to your code for readability: Align the first test with the others.

        if      (a > b && a > c)
            status = MOSTLY_A;
        else if (b > a && b > c)
            status = MOSTLY_B;
        else if (c > a && c > b)
            status = MOSTLY_C;
        else
            status = DONT_KNOW; // a=b or b=c, we don't care

Personally I would write it the following way but this may be too unorthodox for your coding standards:

        if      (a > b && a > c) status = MOSTLY_A ;
        else if (b > a && b > c) status = MOSTLY_B ;
        else if (c > a && c > b) status = MOSTLY_C ;
        else /*  a==b  || b ==c*/status = DONT_KNOW; // a=b or b=c, we don't care

Footnote: Here is the C++ code to generate the permutations:

#include <stdio.h>

char txt[]  = "< == > ";
enum cmp      { LESS, EQUAL, GREATER };
int  val[3] = { 1, 2, 3 };

enum state    { DONT_KNOW, MOSTLY_A, MOSTLY_B, MOSTLY_C };
char descr[]= "??A B C ";

cmp Compare( int x, int y ) {
    if( x < y ) return LESS;
    if( x > y ) return GREATER;
    /*  x==y */ return EQUAL;
}

int main() {
    int i, j, k;
    int a, b, c;

    printf( "a ?? b | a ?? c | b ?? c |P#| State\n" );
    for( i = 0; i < 3; i++ ) {
        a = val[ i ];
        for( j = 0; j < 3; j++ ) {
            b = val[ j ];
            for( k = 0; k < 3; k++ ) {
                c = val[ k ];

                int cmpAB = Compare( a, b );
                int cmpAC = Compare( a, c );
                int cmpBC = Compare( b, c );
                int n     = (cmpBC * 9) + (cmpAC * 3) + cmpAB; // Reconstruct unique P#

                printf( "%d %c%c %d | %d %c%c %d | %d %c%c %d |%2d| "
                    , a, txt[cmpAB*2+0], txt[cmpAB*2+1], b
                    , a, txt[cmpAC*2+0], txt[cmpAC*2+1], c
                    , b, txt[cmpBC*2+0], txt[cmpBC*2+1], c
                    , n
                );

                int status;
                if      (a > b && a > c) status = MOSTLY_A;
                else if (b > a && b > c) status = MOSTLY_B;
                else if (c > a && c > b) status = MOSTLY_C;
                else /*  a ==b || b== c*/status = DONT_KNOW; // a=b, or b=c

                printf( "%c%c\n", descr[status*2+0], descr[status*2+1] );
            }
        }
    }
    return 0;
}

Edits: Based on feedback, moved TL:DR to top, removed unsorted table, clarified 27, cleaned up code, described impossible states.


答:
Are compilers typically validated to ensure they won't pwn the user
  machine when compiling some clever piece of code?

In general they're too complex and often written using languages in which it's not practical to prove this property.

Possibly not with this specific intent, but the notion of fuzz testing compilers is at least known (LLVM can now fuzz-test itself). Tests intended to catch input that crashes the compiler due to compiler bugs will tend to also turn up exploitable flaws.

Naturally you'd have to look into whether the specific compiler you're interested in is tested or fuzz-tested to find potential crashes, and whether the bugs so found are actually fixed. Rule of thumb is that if there are crashes any worse than uncaught out of memory exceptions, then without investigating the details further you have to consider a serious possibility they could be leveraged into exploits.

How safe is it to compile a piece of code from a stranger?

Unfortunately, how long is a piece of string. In principle the email might exploit your mail client, or the source code might exploit your text editor or cppcheck, before it even reaches your compiler. Sebastian's suggestion in comments to use an online compiler is a pretty good one, but of course the code has to be in a form the compiler will accept.

Any language or compiler with facilities for compile-time execution of general code is of course highly suspect. C++ templates are functionally complete but don't have (intended) access to the system, so they're relatively low-risk. BЈовић mentions make as extremely high-risk (since it's executing the stranger's code, it's just that the code happens to be written in the make language, not in C++). If the compiler will run system then you're in the same boat. I used to work with an assembler that, if I remember rightly, could do arbitrary compile-time code execution. It was intended for computing look-up tables, but I don't think anything prevented you making system calls.

In practice, if the code looks OK to me and I think I understand it, then I'd consider it extremely low risk to compile it, far lower risk than say "browsing the internet with a locked-down browser". I do riskier things routinely on my general-purpose machine, but many of them I wouldn't do e.g. inside a virus lab or on a critical server. If the code is funny-looking or evidently obfuscated then I might not risk compiling it because, aside from the risk it could contain an exploit hidden in the unreadable garbage, it's rubbish code. Underhanded code is difficult but possible. Underhanded code that pwns the machine via a compiler exploit needs to contain a non-trivial executable payload, so is extremely difficult.

If you want to look into this further, try asking the folks who host online compilers. If it hasn't been done to them then (barring you coming to the attention of the NSA or equivalent) you can reasonably assume it won't be done to you. They put some effort into running their compiler in a proper sandbox, which might be more effort than you're willing to go to, but they might at least be able to tell you how often that sandbox saves them trouble.


问:
Managing International Programmers
My boss recently went back to our international office in his home country to interview some potential new employees, and we have decided to hire a few as programmers. They are fresh out of college and have very limited experience (similar to me when I first started working here). I am told they are able to read English, however I looked at the code they wrote as a part of the application process and all their variable names, method names, comments, etc are in Spanish. I am having doubts that they have any ability to write English. I hear they are learners though, so maybe they can learn over time as we give them small training projects.

I will be working with them closely, helping them learn good design principles and other things, and I will eventually get to the point where I am producing code with them.

Has anyone dealt with this sort of situation and had it end well? What kind of pitfalls should I look out for? What kinds of tools do you know of that can assist in international collaboration and training?

答:
Has anyone dealt with this sort of situation?

Yes, it is not uncommon in big companies and probably more so in Europe than in the U.S., because over here both worker mobility and culture heterogeneity are high.

Did it end well?

Yes, why not? You have to come to an agreement on what language is your lingua franca, and make sure that everyone understands no part of the code can be written in any other language. Some people tend to understand that comments, or local variables, are their personal territory. This is a bad habit, regardless of the international setting.

What kind of pitfalls should I look out for?

I think the worst problem you are going to face is that you have a compact group of people coming over from the same country, and not a single person or a set of individuals from different countries. Make sure that they work in different projects, at least in the beginning, because there is a very strong tendency to communicate with people in your native language if you can. It takes some time to get used to talking or writing to them in another language; but you get used to that, too.

As mentioned above, some people regard comments as their "personal notes", or local variables as their own "notation"... Understanding that this is not so is just another part of becoming a mature programmer.

Another subtle point is that working outside your mother language limits your vocabulary, and naming things is one of the hardest things in programming. Give your newcomers a dictionary of synonyms, and one or two tutorials on naming software entities.

What kinds of tools do you know of that can assist in international collaboration and training?

I was about to write "alcohol", but since I do not want to end with such a lack of seriousness, I will tell you that "humor" is probably the best tool you can have in bridging the communication gap. Make some jokes about you not understanding Spanish, and maybe how languages sound to foreigners. Only bring up the Spanish Inquisition if you are writing Python.

Title: Managing International Programmers


答:
Your problem is floating-point number formats. They're basically stored as Sign*Man*2^Exp. For 32 bits floating point types, there's only 9 bits of exponent available, and even 64 bits FP uses a mere 11 bits.

But once you take the log of that value, you're effectively user the far large magnitude field to store your original exponent.

There's also another alternative. Roll your own FP format, of the form 2^(-Exp/4294967296). operator+ is quite imprecise for this type, but operator* is just a mater of adding (integral) exponents and pow is a multiplication of exponents.

Title: Avoid numeric errors in Naive Bayes method

Body:
I am implementing the Naive Bayes method with Gaussian distribution.

The problem that I have is that the variance used on the Gaussian curve (calculated from a training set) is REALLY small. They are on the order of e-07. That means the whole equation,

```<code>(1/:math.sqrt(2*:math.pi*:math.sqrt(variance))) *
:math.exp(-0.5*(:math.pow(elem - mean, 2) / variance))
</code>```

results in really high values (such as 500, or even more). That becomes a problem later, when I multiply every probability p(x|C) together (it is a vector of 256 features).

I heard that is possible to use logarithms to avoid these kind of numbers. I searched on google but didn't find anything related to the subject. Does anyone know about that?


问:
As a student, how to determine areas of ignorance?
While attempting to make a list programming subjects/topics that were unclear to me, I was unable to come up with anything.

I know I can't be clear on everything. What steps can I take to get an accurate self-assessment of my knowledge and "know what I don't know"?

答:
Read. Read a lot.

The information that you need to know about programming is inevitably out there, all over the internet, so if you want to fill the gaps in your knowledge you need to have a sincere curiosity about the field. The key distinction is that you're not going to know what you don't know or need to know until you find it, so the only way to find it is to look for it.

When I was getting started in the field I was in awe at the breadth of material there was out there to learn, but I was incredibly ignorant. Luckily, I had the curiosity to do a lot of googling, question asking, and searching for classic books in the field. When I first started reading not everything made sense, but with time all of the puzzle pieces came together into a greater understanding.

Eventually, once you've read and understood enough, you will make the shift from 'what don't I know' to 'I want to know about [x]'.


答: I think that namespaces are a great idea. They help prevent naming conflicts by limiting the scope of a name. In Java packages, the suggested package naming convention is based on domain names, which should be unique, which help prevent naming conflicts over custom libraries. Overall, they make naming a bit more unique in the broad sense, while still allowing the programmer a good bit more freedom in naming his pieces without having to follow some obscure naming convention.

Title: Merits of Namepsaces/Packages

Body: Some programming languages (e.g. Java and C++) have language features called "packages" or "namespaces".  How useful is it really to have namespaces?  It is possible to mark functions and classes as belonging to some particular library without using such a language feature, like the SDL does (e.g. SDL_BlitSurface()).  Are namespaces not helpful enough to be worth having?  Are they useful in libraries but not in applications?  Are they useful everywhere except for in small projects?  Thoughts?


答:
We have to distinguish several cases:

A bug in the compiler. Like every complex program, a compiler might have bugs, and one of those bugs might be exploitable.

A Trojan Horse. The attacker may get you to execute some arbitrary code as part of the compilation process. A Makefile, a build.xml, a configure shell script etc. Technically, this is not due to compiling the attacker's code but rather setting up the compile environment.

Languages allowing arbitrary code to run at compile time. Scala's macro language is Scala, Common Lisp's macro language is Common Lisp, Template Haskell's macro language is Haskell. Scala also has compiler plugins, which are again arbitrary Scala code that runs at compile time. F# has type providers.

Languages which allow Turing-computation at compile time. Scala's and Haskell's type systems are Turing-complete, as are C++'s Templates. You can get the compiler to perform arbitrary Turing-computation at compile time, including but not limited to infinite loops. Note that Turing-complete only means that you can compute every Turing-computable function, it does not mean that you can access the filesystem or something like that. But, you can make a program that will take infinitely long to compile.

Very long compile times. For example, C#'s rules for overload resolution are so complex that you can encode any 3-SAT problem as C# overload resolution. 3-SAT is, of course, famously NP-complete. In other words, according to our current knowledge, it is impossible to find an efficient algorithm for overload resolution in C#. You can't make compilation take infinitely long, but it doesn't take a big program to make compilation take longer than the lifetime of the universe, which is practically the same thing.

#4. and #5. will at the most result in a denial of service. Practically, C++ and Scala compilers limit the amount of recursion you can do, so that it is not actually possible to write an infinite loop. In Scala, that's just an implementation constraint, but in C++, it's explicitly allowed by the spec, I believe.

#2. is technically out of scope of the question because the question was about compiling code not running it (OTOH, there's the deep philosophical question: if type-checking a Haskell program can perform arbitrary Turing-computation, is that compilation or running a program?)

#1. is unlikely. On the one hand, production compilers are very complex, so the likelihood of bugs is high. On the other hand, they are rigorously tested, after all, handling ill-formed input gracefully is part of the job description of a compiler. Even if they are not tested, they will be bombarded with ill-formed code anyway … just look at some StackOverflow questions for examples of what junk people throw at their compilers!

This leaves us with 3. Some compilers may limit the kind of access the compile time code has to the system, but for some of the use cases, having full access is unavoidable. The purpose of F#'s type providers, for example, is to "fake" synthetic types for data whose type system doesn't match F#'s, so that you can interact with, say, a web service that has a WSDL schema in a strongly-typed fashion. However, in order to do this, the type provider needs to have access to the WSDL schema resource either on the filesystem or on the web, so it needs to have filesystem and network access.

So, is it safe? Technically, no. Is it risky? Not really.


问:
Modern Interpretation of the Unix Philosophy of "Rule of Generation"
According to Wikipedia, Eric S. Raymond said that one of the 17 Rules of Unix is the "Rule of Generation", stating that:

Developers should avoid writing code by hand and instead write
  abstract high-level programs that generate code. This rule aims to
  reduce human errors and save time.

How is this rule to be interpreted in a modern context of languages that abstract away memory management (ex. Java's GC) or other low level bit-twiddling tasks?  Does this rule still apply?

答:
He doesn't mean little IDE utilities that create boilerplate for you, which you must modify.  He's referring to more comprehensive code generation that you shouldn't have to touch.  You make changes to the higher level and regenerate.

The canonical Unix example would be Yacc, which uses a high-level grammar to generate complex parsing code.  Other examples:

An SQL query.

A domain-specific language, like many web frameworks use for route handling.

A GUI builder.

The basic idea is to write in as high an abstraction level as possible, as close to the natural representation as possible.


问:
Communication between state machine and GUI
I am writing a finite state machine in C++, designed as a library.
Furthermore, I have a GUI implemented as a separate project which needs to update the user interface according to state changes happening in the library.

The way I implement the communication now, is that the GUI is calling a library function which returns a struct containing information about the state of the finite state machine (and other necessary information).

But I find this a rather ad-hoc solution and since it seems like a frequent situation, I am curious to know if there is a design pattern / text book way of handling this.

答:
GUI libraries (like for example Qt) are using some kind of subscriber-publisher design pattern, which is event based. That means, on an event, all subscribers are going to be notified.

So, on a state change, publish the event. Every object that subscribed to the event, is going to execute a callback.


答:
The simplest method is to pass a callback function to the state machine that gets called when a state changes (or other event happens).

Then when it gets called you can update the gui in that function (or forward the message to the gui thread if the state machine runs in a separate thread).

The signature would be something like void callback(State oldstate, State newstate, void* userData)

The userData pointer is supplied at the same time as the function pointer and provides a context for the (static) callback function. If you want you can also use a std::function instead and keep the function pointer+userData method as overload.

Title: Communication between state machine and GUI

Body:
I am writing a finite state machine in C++, designed as a library.
Furthermore, I have a GUI implemented as a separate project which needs to update the user interface according to state changes happening in the library.

The way I implement the communication now, is that the GUI is calling a library function which returns a struct containing information about the state of the finite state machine (and other necessary information).

But I find this a rather ad-hoc solution and since it seems like a frequent situation, I am curious to know if there is a design pattern / text book way of handling this.

ContentLicense: CC BY-SA 4.0


答:
Assume both A and B have a million members, and you have sorted A and B.

How many pairs can you form with A [0]? To find out, you add A [0] + B [0], A [0] + B [1], A [0] + B [2] etc. You stop when the result is too large, and then you know how many. Say A [0] + B [920178] is not too large, but A [0] + B [920179] is too large, then you can form 920179 pairs using A [0]. That method works because B is sorted.

How many pairs can you form with A [1]? Since A is sorted, A [0] <= A [1]. That means A [1] + B [920179] is too large. You search downward until you find for example that A [1] + B [920174] is not too large. This gives another 920175 pairs.

You repeat the same with A [2], A [3] up to A [999999]. So how long does this take? You examine a million values of A. You also examine at most a million values of B, because your search downward through B will end at B [0].

You'll have to be a bit careful at the ends of the arrays to avoid bugs in your code.

Title: Find the maximum number of pairs of numbers that are in a range, between two arrays

Body:
Lets say I have two arrays A and B

```<code>A = {1,2,3}
B = {12,11,67}
and have max sum value S = 10
</code>```

How many maximum number of unique pairs can be formed between the two arrays who's sum is less than or equal to S.

For e.g., the two possible values here are [1,11] [2,12] hence the answer is 2. If there are none, the answer is 0.

My solution was to sort both the arrays and then go do

```<code> if((Math.abs(A[i]-B[i]))<=S)
                 {
                 ans++;
             }
</code>```

Although it works for this case, clearly this is incorrect.


答:
I would go even further:

User: Id, Name, WallId

Post: Id, Content, Title, WallId etc...

Wall: WallId

Group: Id, Name, WallId...

Basically, post belongs to  a Wall. Wall can belong to  a user or  a group.

Title: DB Schema design : single table with more columns vs multiple tables with fewer colomns

Body:
What would be better DB design for a social network website.
A single table with more columns and less rows or multiple table with fewer columns but more rows.

For example:
User can post an update on their wall or in a group.

Two DB designs that I could think of are:

1)
UserPosts: id, userId, post, datetime
UserGroupPost: id, groupId, userId, post, datetime

Potentail problem : Might require joins, which can (in future) be a slow query.

2)
Posts: id, userId, groupId, post, datetime
(where groupid would be null if user posts on their wall)

Potential Problem : Looping over large dataset could take a (long)time.

Where can I get better performance when data increases?
Is there any other(better) way?


问:
How much should I break up my unit tests?
I recently learned about unit tests and TDD and have started going back to add unit tests to my code (and thank god, it's proven that some things I've written are much more broken than I thought).

That being said, I'm having a hard time figuring out how much (or little) should go into each test.  For example, consider a class I wrote with several methods.  Right now I do something like

```<code>class test_myclass(unittest.TestCase):

    def setUp(self):
        ...
    def test_func1(self):
        ...
    def test_func2(self):
        ...
    etc
    def tearDown(self):
        ...
</code>```

But what if each (or at least some) method can fail in a lot of different ways, or has a lot of edge cases?  Then I'm stuck doing something like

```<code>def test_func1(self):
    self.assertEqual(func1(working_input), expected_value)
    self.assertRaises(Some_error, func1, args)
    self.assertRaises(Some_other_error, func1, args)
    etc
</code>```

And it could get pretty hairy, and rather unclear where things are failing.  So I thought I might break it up more, and devote a class to each function (that has enough test cases to be worth it) but that seems like a lot of work, and more time than I should probably be spending on testing.

I also considered writing multiple tests for a given method, such as

```<code>def test_func1(self):
    self.assertEqual(func1(working_input), expected_val)
def test_func1_bad_input_1(self):
    self.assertRaises(error, func1, bad_args)
def test_func1_bad_input_2(self):
    self.assertRaises(error2, func1, bad_args_2)
...
</code>```

And this seems cleaner than a unit testing class per method, but still seems like it might be to little in any given test.

How much testing is too much?

While my example was given in python, I'm open to language agnostic answers

答:
Unit tests give you value, and they create work. You want the best possible value for work.

If you write ten tests each checking ten items, instead of 100 tests each checking one item you usually safe some work. You still have the same test coverage. So if your tests work, you are fine. If they fail, and you ignore it, you are also fine.

In the case where you have a failing test and are actually fixing it, you have some work figuring out which item failed, then some work to figure out why it failed, and some more work to fix it. I'd say that usually the saving that you have from knowing which of 100 items failed vs. which group of ten items failed is minimal. It is usually more than offset by the time saving that you have while writing the tests.