问:
How would you assess a programmer's Github profile?
Lots of people in the open source community say they strongly consider a candidate's Github profile when hiring.

I'm active on Github, with a few projects of my own and some contributions to others. But looking at my own profile as if I were an employer, I see a lot of noise: projects I cloned but never contributed to, etc. The projects and patches I'm proud of don't stand out.

If you assess people's Github profiles, how do you do it? And as a developer, should I do anything differently - for example, delete cloned repos I'm not actively working on?

答:
Be careful when you assess candidates based on a GitHub profile. GitHub is not a CV. There are many great engineers that don't have flashy profiles, because of many reasons: they might have worked for closed source companies, or they might spend more time on other activities such as family, hobbies, etc.

Even though a contribution to an open source project might be a plus for a candidate (as @marshally mentioned), you should evaluate and hire in the old-fashioned way, talking.

Some references that I've stumbled upon just after reading this thread:

GitHub is not your CV

Most active GitHub users, esp. these 2 comments from important contributors: 1, 2.


问:
Separation of logic from presentation results in repetition of code
Here's what I've been thinking.

Say you're making a multiplayer game. A good way to structure it is to have all your game logic on the server and have the clients only be responsible for transmitting input to the server, drawing the current state of the game and UI.
This usually leads to clean code and it also prevents client-side cheating.

Now say you have a unit in your game that fires a cannon with a certain cooldown. The reason it can't fire continuously is because it has to reload. This is represented by an animation. But the server also needs to be aware of the cooldown so you end up having to sync up the animation duration and the cooldown that the server understands. In this simple example you can just speed up or slow down the animation if you decide to change the cooldown, but there are definitely processes where it would be more reasonable to animate them and then have the game values depend on the actual animation.

Is there a smart way to avoid this? It seems that it puts a significant load on the programmer because he has to manually make sure that two decoupled pieces of code, that would probably be better of coupled, are in sync. If you didn't separate the presentation from logic you would just hook directly into the animation and have it trigger actions in the game.

答:
Now say you have a unit in your game that fires a cannon with a certain cooldown. The reason it can't fire continuously is because it has to reload. This is represented by an animation. But the server also needs to be aware of the cooldown so you end up having to sync up the animation duration and the cooldown that the server understands.

The server awareness is primary and the first concern.  The most important thing is that the right thing happens and only the server may decide that.  The only thing it should ever believe the client about is the user's input.  I know you know that but that has to be stated.

So, assuming your proposal is that the animator decides the timings and this information is passed to the server-side developer... you have simplified nothing and the code is still "duplicated".  The server application still has to enforce the cooldown.  The code still has to be written.  It may be worse code than it would otherwise have been and it certainly will be more fragile because it has been dictated by a graphic designer's imagination and not the internal mechanics of the game.  It is not simpler.

If the proposal were that the client application tells the server "I finished reloading, I'm firing again now" then you have handed your application over to the hackers.  You have created a game where the user can toss a coin and decide whether or not it came up heads, then demand money from the NPC gambler who has "lost" the bet.  Even if the user is not a cheat, remember that MMOs suffer from lag and that the client software also suffers from the load on the client computer (maybe some auto-disk-defrag task decided to start up).  It can neither send reliable timings back to you nor reliably show to the user what is happening now.  Which feeds into my next point...

Code duplication?  The server application decides what happens, based on a combination of what the user has requested to happen, what the game dictates will happen, what events and conditions are providing other inputs (NPC activity, other user activity etc) and what the application will allow from the product of all those.  The client just tries to present a plausible representation of what it has been told is happening, wrapped in a lot of glitter which has no existence in the actual game, having told the server what the user wanted to do (move forwards, swing a sword, change to secondary weapon, whatever).  These are completely different tasks.

But...

The game world "exists" in your servers.  The player is trying to "live" in that world from his or her home computer.  The player cannot do that (and will not want to play any more) if the representation of game events is not both plausible and consistent.  They can live with a game where sometimes things get too laggy and slowed down (as in a huge multi-player raid/battle) for them always to see that they have run out of ammo - if the game is reliable in managing those events.  They will not stay in a game where they may seem to have reloaded and be firing, only nothing is being shot.  They will not trust such a game to manage any event, server side or not.

So for your game to be acceptable, some code duplication is essential.  Client side developers/animators must know something about what is going on server-side, because they have to stay roughly in sync with it under very demanding conditions and make it believable and acceptable to the player.  You are trying to make the same world exist in two widely separate places and in two separate applications which absolutely should not share any code (for reasons of security as well as simple separation of concerns).    Try doing that without repeating anything.  Duplication of the essentials of the game is the whole point.

ContentLicense: CC BY-SA 3.0


问:
Forking EPL library. Can I change license?
There is library OpenCl.NET licensed under Eclipse Public License. I want to fork it to change some errors and add some functionality. </p>

<p>Is it possible to license my changes by Apache 2 license? </p>

答:
From the EPLv1.0

REQUIREMENTS

A Contributor may choose to distribute the Program in object code form
  under its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

```<code>i) effectively disclaims on behalf of all Contributors all
   warranties and conditions, express and implied, including
   warranties or conditions of title and non-infringement, and
   implied warranties or conditions of merchantability and fitness
   for a particular purpose;

ii) effectively excludes on behalf of all Contributors all
    liability for damages, including direct, indirect, special,
    incidental and consequential damages, such as lost profits;

iii) states that any provisions which differ from this Agreement
     are offered by that Contributor alone and not by any other
     party; and

iv) states that source code for the Program is available from such
    Contributor, and informs licensees how to obtain it in a
    reasonable manner on or through a medium customarily used for
    software exchange.
</code>```

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the
  Program.

Contributors may not remove or alter any copyright notices contained
  within the Program.

So a basic "I AM NOT A LAWYER" interpretation is that you can only distribute the source code under the EPL. Object code can be under a different license under certain conditions.

Body:
From the EPLv1.0

REQUIREMENTS

A Contributor may choose to distribute the Program in object code form
  under its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

i) effectively disclaims on behalf of all Contributors all
   warranties and conditions, express and implied, including
   warranties or conditions of title and non-infringement, and
   implied warranties or conditions of merchantability and fitness
   for a particular purpose;

ii) effectively excludes on behalf of all Contributors all
    liability for damages, including direct, indirect, special,
    incidental and consequential damages, such as lost profits;

iii) states that any provisions which differ from this Agreement
     are offered by that Contributor alone and not by any other
     party; and

iv) states that source code for the Program is available from such
    Contributor, and informs licensees how to obtain it in a
    reasonable manner on or through a medium customarily used for
    software exchange.

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the
  Program.

Contributors may not remove or alter any copyright notices contained
  within the Program.

So a basic "I AM NOT A LAWYER" interpretation is that you can only distribute the source code under the EPL. Object code can be under a different license under certain conditions.


答:
I am not a lawyer. You should get one, if you are concerned about possible legal issues.

The title of questions (‘Can I change license?’) does not match its body (‘Is it possible to license my changes by Apache v2 license?’).

Of course, you can not change the license. Even most permissive free software licenses, such as Expat and 2-clause BSD licenses¹, do not allow changing the license of original code – they only allow sub-licensing, i. e. basically covering it by another less permissive license in addition to original. Eclipse Public License v1.0, does not allow sub-licensing sources under different terms² (so it should be considered copyleft license); and even if it did, ASLv2 is more permissive; thus no, you cannot take OpenCl.NET, modify it, and redistribute it under Apache License.

As for whether it is possible to cover your changes by Apache [Software] License v2, this may be rephrased as ‘Is ASLv2 is compatible with EPLv1?’, and according to EPL FAQ the answer is yes. So yes, you can attach ASLv2 to your changes, and incorporate them into the original library. The result of as a whole might and should be considered as covered by EPL.

However, I do not understand, why you don’t just use the same license as original library does.

¹ Well, there is an ultimately permissive license – WTFPL :-), it do allow changing the license.

² § 3: When the Program is made available in source code form: a) it must be made available under this Agreement...

Title: Forking EPL library. Can I change license?

Body:
There is library OpenCl.NET licensed under Eclipse Public License. I want to fork it to change some errors and add some functionality. </p>

<p>Is it possible to license my changes by Apache 2 license? </p>


问:
Is using digital signatures and bytecode machines a viable technique to make reverse engineering hard?
If I have a private key with which I sign byte code, and a public key with which I can decipher the signed code to verify its authenticity, can I protect that byte code from being reverse engineered and modified as follows:

Built an abstract machine to interpret the byte code in plain text.

Apply code generation techniques to this to be able to generate a unique machine for each end user, paired with a public key for that user, in such a way that the byte code machine verifies the byte code as each instruction is executed. That is, the verifier is woven into the machine.

The bytecode interpreter itself is ofuscated in a non-reversible manner, using the petri-nets technique.

Sign the bytecode for each user by encrypting it with the a secret key, unique to the user but not accessible to them.

Now the bytecode can easily be decrypted by each user with their key, but they do not posses a copy of the plain text machine to run it.

If users modify the code, they cannot sign it to run on the machine that they do have, since they do not possess the secret key needed to do this.

Perhaps this technique is already widely known and in use?

Please note, this question is not about whether this makes reverse engineering absolutely impossible, as I understand that no technique is ever going to be perfect and there are good reasons for that. I want to know whether this would be a practical deterrent and viable technique, have such techniques already been explored/discredited or is this considered a reasonably good one, relative to other protection techniques.

答: No. There is nothing in your scheme that prevents a user from reverse engineering the bytecode interpreter and either (1) removing the verification steps or (2) changing the public key which must be encoded within it somehow to one they know the equivalent private key of.</p>


问:
How to distribute copyrighted resources with and open source project?
I would like to create an open source GPLv3 project that will work with other resources that are under different types of copyright (e.g. free to use, but must not sell). Because of this, I can't include the 3rd party resources in the main project's open source repository.

So I tought I would keep the core project separated under GPLv3, then have a private project that include the core and the 3rd party resources and create a "compiled" release that would be released under a more restrictive license that statisfy the 3rd party licenses. This way the goat has enough to eat and the cabbage also remains.

Can I do it this way? If not, how should I handle the situation?

答:
Assuming you are the copyright holder for all the code, then yes you can do this.   But as I understand things, no other entity will be able to compliantly create a derived work and distribute it because of the incompatibility of the licenses for the code and the "resources".   This problem doesn't apply to you since you're the owner of the code and hence not bound by the GPL3 license.

My recommendation would be to either find alternate resources which have a GPL3 compatible license, or release your code under a license which is compatible with the resources, so that your licensees can release modified works.

Try http://choosealicense.com/ for help with choosing another license.


问:
What are the skills you look for when hiring a fresher/newbie for developement?
I really want to ask this questions to my fellow developers here in Programmers.SE because i am hiring freshers for my company.. Even though i know some basic questions that can be asked to a fresher during interview and i want to know,

What are the skills you look for when hiring a fresher/newbie for developement?

答:
In principle, it’s simple. You’re looking for people who are

Smart, and

Get things done.

The Guerrilla Guide to Interviewing by Joel Spolsky

ContentLicense: CC BY-SA 2.5


问:
Usage of "bugfix" to refer to UI changes in branch names
If a user interface has an undesired look (elements not having padding or margins when it would be appropriate, etc.) and I implement a correction in a new (named) source control branch, would it be appropriate to name the branch as a bugfix or group it with other bugfix branches (and if not, what would be the most logical word[s] for grouping)? The cause isn't exactly a bug, as it isn't due to an error in code, stylesheets, layout files, etc., but the fix doesn't really seem to count as a new feature or enhancement either.</p>

答:
Wikipedia describes a software bug as "A software bug is an error, flaw, failure, or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways."

As an undesired look can be classified as an incorrect result or unintended behaviour of the UI, a change to correct that look would certainly be a bugfix.

Another way to look at it is that the software contains a bug if it does not work as specified.

If those UI elements were specified to have no padding and no margins (and that can be traced back to a desire from the client), then your change isn't a bugfix because the look was 'as specified'. At best you have implemented a change request and at worst your change is incorrect and undesired.

For naming your branch, there is no harm in naming it as a bugfix. If it makes a difference for the development process that your team uses, you could double-check with your team lead/product owner/project manager if this fix was the result of a change request by the client or if it should be treated as a bugfix.


问:
Number of strings containing a specific substring
I've seen numerous questions (and answers) concerning the number of binary strings (e.g "10010" containing some binary substring (e.g "00"). I'd like to know if there is a way to generalize this:

Given a length n and a string s (may contain any letters A...Z), how many different strings of length n, that contain the substring s at least once, are there?

These kinds of questions are often solvable with combinatorics, but I'd like to find a dynamic-programming solution (and so I posted this question here instead of mathexchange).

Personally, I'm running on cold steam here. Of course, I tried some combinatorial methods:

```<code>n = 5
s = CAR
? = unknown character

all possibilities:

CAR??
?CAR?
??CAR
</code>```

This basically boils down to 26^0*26^2 + 26^1*26^1 + 26^2*26^0 = 3 * 26^2 = 2028 possibilities, which I assume is correct. Consider however the following case:

```<code>n = 7
s = CAR
? = unknown character

all possibilities:

CAR????
?CAR???
??CAR??
???CAR?
????CAR
</code>```

What's the problem? Well, there's 3 positions that can produce duplicate results:

```<code>CARCAR?
CAR?CAR
?CARCAR
</code>```

Now the number of possible strings is

(2 * 26^7) + (2 * 26^1 * 26^6) + (2 * 26^2 * 26^5) + (2 * 26^3 * 26^4) - (3 * 26)

I can't generalize this.

Did I catch anyone's interest? Any help is appreciated.

答:
Acknowledging @Hirle's solution, I still figured I'd post my own.

I approached this from a little different direction. After some thinking, the simplest program of all held the key:

deterministic finite automaton. This could be solved with a dfa that searched for occurences of a string, as with it I can compute
an adjacency matrix that I can later use. I decided to skip the trivialities and just copied some code off the net for the
deterministic version of Knuth–Morris–Pratt algorithm (the original one if nondeterministic, which doesn't serve our purposes).

The below code originates from here, with little modifications:

public static int[][] dfa;

// create the DFA from a String
public static void kmp(String pat) {

    // build DFA from pattern
    int m = pat.length();
    dfa = new int[26][m];
    dfa[pat.charAt(0) - 'A'][0] = 1;
    for (int X = 0, j = 1; j < m; j++) {
        for (int c = 0; c < 26; c++)
            dfa[c][j] = dfa[c][X];          // Copy mismatch cases.

        dfa[pat.charAt(j) - 'A'][j] = j+1;  // Set match case.
        X = dfa[pat.charAt(j) - 'A'][X];    // Update restart state.
    }
}
```

<p>For the pattern <code>ABC</code> this generates the following 2D-matrix, or dfa, if you will:</p>

```[1, 1, 1]
[0, 2, 0]
[0, 0, 3]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
```

<p>Here, for example, the first row means that if the character seen is `A', then depending on our current <em>state</em> we go to the state indicated by the row.</p>

<p>Let's say the state we currently are in is the initial state (state 0). If we now saw the character 'A', the next state would be told to us by the first row's first element,
which is 1. So now our state is 1. Let's say we, again, saw the character 'A'. Our state would remain 1, as the first row's second element is also 1. Alright, now say we saw
the character 'B'. Our state would proceed to 2, since in the B-row's (the second row's) second element is 2.</p>

<p>In essence, our state would be 3 only if we saw the characters <code>ABC</code> in succession. The rows D-Z are all zeroes, since if we ever saw a character other than A-C, we must start
the search from the beginning (which is A, in this case).</p>

<p>To generalize, the matrix element <code>[0][1]</code> tells us the state we should go to, if the character we saw was <code>A</code> and we were in the state 1. Similarly the matrix element
<code>[6][6]</code> told us our next state if the character we saw was <code>G</code>, and we were in the state 6 (in the above matrix we of course don't have the state 6, since we built it with a string of length 3).</p>

<p>Anyway, now we have all we need to build the adjacency matrix. Without further ado, here's my code for that:</p>

<pre class="lang-java prettyprint-override"><code>String s = "ABC"; // The string we built our dfa with, e.g the string we are "searching"

paths = new long[s.length() + 1][s.length() + 1];
for (int k = 0; k < 26; k++)
    for (int i = 0; i < dfa[0].length; i++)
        paths[i][dfa[k][i]]++;

paths[paths.length - 1][paths.length - 1] = 26;
</code>```

So if we were building the adjacency matrix from a dfa that was built with the string "ABC", the adjacency matrix would look like this:

```<code>[25, 1, 0, 0]
[24, 1, 1, 0]
[24, 1, 0, 1]
[0 , 0, 0, 26]
</code>```

Here paths[i][j] would tell us how many ways there are to get to the state j from the state i. For example, there are 25 ways to get to state 0 from state 0, because there is only
one way to get to some other state from state 0. Also, there are 26 ways to result in the last state, if we are in the last state.

If we had built everything up so far with the string "AA", the adjacency matrix would look like this:

```<code>[25, 1, 0]
[25, 0, 1]
[0, 0, 26]
</code>```

So, what now? We have our oh-so-mighty adjacency matrix that tells us cool stuff, what to do with it? Graph theory comes into play.

Referencing Wolfram Alpha:

the (u,v)th element of the kth power of the adjacency matrix of G gives the number of paths of length k between vertices u and v.

So what it is saying is, that if we raise our adjacency matrix into, say, 3rd power, then the element paths[0][k] tells us how many paths of length 3
there are from state 0 to state k.

I'll prep a little more for this: If we have a string S, and with that string we can result in the last state of the dfa, then we consider S to be OK.
So what we want to know to get the answer to the original problem, is how many OK strings there are in bigger strings of length n.

This is why we raise the adjacency matrix into the nth power. Now the element paths[0][k], where k is the length of the string we are searching, should tell us how many OK strings there are in a bigger string of length n, which just
so happens to be the answer to our problem.

My code to raise a matrix into nth power:

public static long[][] matrixToPower(long[][] a, int p) {
    long[][] b = a;
    for (int n = 1; n < p; n++)
        a = matrixMultiplication(a, b);
    return a;
}

public static long[][] matrixMultiplication(long[][] m1, long[][] m2) {
    int len = m1.length;
    long[][] mResult = new long[len][len];
    for(int i = 0; i < len; i++) {
        for(int j = 0; j < len; j++) {
            for(int k = 0; k < len; k++) {
                mResult[i][j] += (m1[i][k] * m2[k][j]) % M;
                mResult[i][j] %= M;
            }
        }
    }
    return mResult;
}
```

<p>I'm taking a modulo of size <code>10^9 + 7</code> to get reliable answers for big input.</p>

<p>Full code:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.*;

public class Program {

    public static final int M = 1000000007;

    public static int[][] dfa;
    public static long[][] paths;

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String s = sc.next();

        kmp(s); // generate dfa

        paths = new long[s.length() + 1][s.length() + 1];
        for (int k = 0; k < 26; k++)
            for (int i = 0; i < dfa[0].length; i++)
                paths[i][dfa[k][i]]++;
        paths[paths.length - 1][paths.length - 1] = 26;

        paths = matrixToPower(paths, n);

        System.out.println(paths[0][s.length()]);
    }

    public static long[][] matrixToPower(long[][] a, int p) {
        long[][] b = a;
        for (int n = 1; n < p; n++)
            a = matrixMultiplication(a, b);
        return a;
    }

    public static long[][] matrixMultiplication(long[][] m1, long[][] m2) {
        int len = m1.length;
        long[][] mResult = new long[len][len];
        for(int i = 0; i < len; i++) {
            for(int j = 0; j < len; j++) {
                for(int k = 0; k < len; k++) {
                    mResult[i][j] += (m1[i][k] * m2[k][j]) % M;
                    mResult[i][j] %= M;
                }
            }
        }
        return mResult;
    }

    // create the DFA from a String
    public static void kmp(String pat) {
        // build DFA from pattern
        int m = pat.length();
        dfa = new int[26][m];
        dfa[pat.charAt(0) - 'A'][0] = 1;
        for (int X = 0, j = 1; j < m; j++) {
            for (int c = 0; c < 26; c++)
                dfa[c][j] = dfa[c][X];         // Copy mismatch cases.
            dfa[pat.charAt(j) - 'A'][j] = j+1; // Set match case.
            X = dfa[pat.charAt(j) - 'A'][X];   // Update restart state.
        }
    }

}
</code>```

Body:
Acknowledging @Hirle's solution, I still figured I'd post my own.

I approached this from a little different direction. After some thinking, the simplest program of all held the key:

deterministic finite automaton. This could be solved with a dfa that searched for occurences of a string, as with it I can compute
an adjacency matrix that I can later use. I decided to skip the trivialities and just copied some code off the net for the
deterministic version of Knuth–Morris–Pratt algorithm (the original one if nondeterministic, which doesn't serve our purposes).

The below code originates from here, with little modifications:

public static int[][] dfa;

// create the DFA from a String
public static void kmp(String pat) {

    // build DFA from pattern
    int m = pat.length();
    dfa = new int[26][m];
    dfa[pat.charAt(0) - 'A'][0] = 1;
    for (int X = 0, j = 1; j < m; j++) {
        for (int c = 0; c < 26; c++)
            dfa[c][j] = dfa[c][X];          // Copy mismatch cases.

        dfa[pat.charAt(j) - 'A'][j] = j+1;  // Set match case.
        X = dfa[pat.charAt(j) - 'A'][X];    // Update restart state.
    }
}

For the pattern ABC this generates the following 2D-matrix, or dfa, if you will:

[1, 1, 1]
[0, 2, 0]
[0, 0, 3]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Here, for example, the first row means that if the character seen is `A', then depending on our current state we go to the state indicated by the row.

Let's say the state we currently are in is the initial state (state 0). If we now saw the character 'A', the next state would be told to us by the first row's first element,
which is 1. So now our state is 1. Let's say we, again, saw the character 'A'. Our state would remain 1, as the first row's second element is also 1. Alright, now say we saw
the character 'B'. Our state would proceed to 2, since in the B-row's (the second row's) second element is 2.

In essence, our state would be 3 only if we saw the characters ABC in succession. The rows D-Z are all zeroes, since if we ever saw a character other than A-C, we must start
the search from the beginning (which is A, in this case).

To generalize, the matrix element [0][1] tells us the state we should go to, if the character we saw was A and we were in the state 1. Similarly the matrix element
[6][6] told us our next state if the character we saw was G, and we were in the state 6 (in the above matrix we of course don't have the state 6, since we built it with a string of length 3).

Anyway, now we have all we need to build the adjacency matrix. Without further ado, here's my code for that:

String s = "ABC"; // The string we built our dfa with, e.g the string we are "searching"

paths = new long[s.length() + 1][s.length() + 1];
for (int k = 0; k < 26; k++)
    for (int i = 0; i < dfa[0].length; i++)
        paths[i][dfa[k][i]]++;

paths[paths.length - 1][paths.length - 1] = 26;

So if we were building the adjacency matrix from a dfa that was built with the string "ABC", the adjacency matrix would look like this:

[25, 1, 0, 0]
[24, 1, 1, 0]
[24, 1, 0, 1]
[0 , 0, 0, 26]

Here paths[i][j] would tell us how many ways there are to get to the state j from the state i. For example, there are 25 ways to get to state 0 from state 0, because there is only
one way to get to some other state from state 0. Also, there are 26 ways to result in the last state, if we are in the last state.

If we had built everything up so far with the string "AA", the adjacency matrix would look like this:

[25, 1, 0]
[25, 0, 1]
[0, 0, 26]

So, what now? We have our oh-so-mighty adjacency matrix that tells us cool stuff, what to do with it? Graph theory comes into play.

Referencing Wolfram Alpha:

the (u,v)th element of the kth power of the adjacency matrix of G gives the number of paths of length k between vertices u and v.

So what it is saying is, that if we raise our adjacency matrix into, say, 3rd power, then the element paths[0][k] tells us how many paths of length 3
there are from state 0 to state k.

I'll prep a little more for this: If we have a string S, and with that string we can result in the last state of the dfa, then we consider S to be OK.
So what we want to know to get the answer to the original problem, is how many OK strings there are in bigger strings of length n.

This is why we raise the adjacency matrix into the nth power. Now the element paths[0][k], where k is the length of the string we are searching, should tell us how many OK strings there are in a bigger string of length n, which just
so happens to be the answer to our problem.

My code to raise a matrix into nth power:

public static long[][] matrixToPower(long[][] a, int p) {
    long[][] b = a;
    for (int n = 1; n < p; n++)
        a = matrixMultiplication(a, b);
    return a;
}

public static long[][] matrixMultiplication(long[][] m1, long[][] m2) {
    int len = m1.length;
    long[][] mResult = new long[len][len];
    for(int i = 0; i < len; i++) {
        for(int j = 0; j < len; j++) {
            for(int k = 0; k < len; k++) {
                mResult[i][j] += (m1[i][k] * m2[k][j]) % M;
                mResult[i][j] %= M;
            }
        }
    }
    return mResult;
}

I'm taking a modulo of size 10^9 + 7 to get reliable answers for big input.

Full code:

import java.util.*;

public class Program {

    public static final int M = 1000000007;

    public static int[][] dfa;
    public static long[][] paths;

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String s = sc.next();

        kmp(s); // generate dfa

        paths = new long[s.length() + 1][s.length() + 1];
        for (int k = 0; k < 26; k++)
            for (int i = 0; i < dfa[0].length; i++)
                paths[i][dfa[k][i]]++;
        paths[paths.length - 1][paths.length - 1] = 26;

        paths = matrixToPower(paths, n);

        System.out.println(paths[0][s.length()]);
    }

    public static long[][] matrixToPower(long[][] a, int p) {
        long[][] b = a;
        for (int n = 1; n < p; n++)
            a = matrixMultiplication(a, b);
        return a;
    }

    public static long[][] matrixMultiplication(long[][] m1, long[][] m2) {
        int len = m1.length;
        long[][] mResult = new long[len][len];
        for(int i = 0; i < len; i++) {
            for(int j = 0; j < len; j++) {
                for(int k = 0; k < len; k++) {
                    mResult[i][j] += (m1[i][k] * m2[k][j]) % M;
                    mResult[i][j] %= M;
                }
            }
        }
        return mResult;
    }

    // create the DFA from a String
    public static void kmp(String pat) {
        // build DFA from pattern
        int m = pat.length();
        dfa = new int[26][m];
        dfa[pat.charAt(0) - 'A'][0] = 1;
        for (int X = 0, j = 1; j < m; j++) {
            for (int c = 0; c < 26; c++)
                dfa[c][j] = dfa[c][X];         // Copy mismatch cases.
            dfa[pat.charAt(j) - 'A'][j] = j+1; // Set match case.
            X = dfa[pat.charAt(j) - 'A'][X];   // Update restart state.
        }
    }

}


问:
Which design (pattern) would be suitable to abstract logging platforms?
I need to create a simple system to abstract logging platforms. The idea is that I'd like to be able to exchange or activate a logging platform (nlog, log4net, enterprise library) via some configuration (this shouldn't be a problem). I know that I would need a wrapper for each platform that I want to support that would load the necessary dll's and create the loggers.

I was thinking of creating an abstract class or an interface providing the most common methods like Log, Debug, Trace, etc.:

```<code>interface ILogger
{
    void Log(...);
    void Debug(...);
    // etc.
}

class NLogPlatform : ILogger
{
    // create nlog, load config etc.
}

class Log4NetPlatform : ILogger
{
    // create log4net, load config etc.
}

class LoggerFactory
{
    public static CreateLogger(...)
    {
        // read settings and create a logger.
    }
}
</code>```

At first I thought of a log-provider but then I found that provider is not a pattern at all so I looked at .NET Design Patterns but nothing really seems to be suitable here. Did I miss something or is there just no pattern for it?

I haven't really started yet because this time I'd rather go in the right direction from the beginning then refactor several tools later.

Could you tell me what I should take into consideration when designing such a system and whether there is a pattern for this?

答:
Congratulations, you have (re-)discovered the Object Adapter Pattern. You have one target interface (here: ILogger), and various adapter classes NLogPlatform, Log4NetPlatform, …. Each adapter class conforms to the target interface, and proxies all calls to the adaptee object which it contains as a member.

If you want to make the use of this pattern clearer, I would call the adapter classes NLogAdapter etc..

The usage of a factory to inject the correct log adapter is entirely orthogonal to this, and is about the Dependency Inversion principle.


问:
why are the evaluation strategies call-by-value etc. only discussed in the context of function calling?
I am referring to various discussions on the differences and nuances in the semantics of pass-by-value, pass-by-reference, e.g. in SO or in the Wikipedia article on the subject.

My question is why do these articles and conversations always discuss pass-by-value, pass-by-reference, etc. solely in the context of parameter passing and function calls and not in the context of assignments?

E.g. assuming the following:

```<code>A a1 = new A();
A a2 = a1;
</code>```

... why is it taken for granted that the assigned object is not copied by value?

I am not asking why it would be a questionable language design decision to make the semantics of the assignment  copy the object "by value" -  I am asking whether and under what terminology language specifications explicitly spell this out or under what heading language design theory treats such decisions.

答:
My question is why do these articles and conversations always discuss pass-by-value, pass-by-reference, etc. solely in the context of parameter passing and function calls and not in the context of assignments?

As Doval mentions in the comments, the primary reason is that assignment is often modeled as a function call (and can thus be ignored).

why is it taken for granted that the assigned object is not copied by value?

You mean like in C, C++ and a pile of other languages? These days, the most common reason is that copying non-trivial objects is not an atomic operation. Since it's not an atomic operation, it makes it a lot more difficult to make concurrent programs safely, which is already plenty difficult.

Also, because most programmers often don't want value semantics for their objects.

I am asking whether and under what terminology language specifications explicitly spell this out or under what heading language design theory treats such decisions.

The common terms are reference/value types and reference/value semantics (as mentioned in the comments).


答:
This has nothing to do with design patterns...

This is a solved problem, that has been solved over and over since .Net was invented.

Just use Commons.Logging it's a small configurable liberality that does exactly what you asked:
https://github.com/net-commons/common-logging

Title: Which design (pattern) would be suitable to abstract logging platforms?

Body:
I need to create a simple system to abstract logging platforms. The idea is that I'd like to be able to exchange or activate a logging platform (nlog, log4net, enterprise library) via some configuration (this shouldn't be a problem). I know that I would need a wrapper for each platform that I want to support that would load the necessary dll's and create the loggers.

I was thinking of creating an abstract class or an interface providing the most common methods like Log, Debug, Trace, etc.:

```<code>interface ILogger
{
    void Log(...);
    void Debug(...);
    // etc.
}

class NLogPlatform : ILogger
{
    // create nlog, load config etc.
}

class Log4NetPlatform : ILogger
{
    // create log4net, load config etc.
}

class LoggerFactory
{
    public static CreateLogger(...)
    {
        // read settings and create a logger.
    }
}
</code>```

At first I thought of a log-provider but then I found that provider is not a pattern at all so I looked at .NET Design Patterns but nothing really seems to be suitable here. Did I miss something or is there just no pattern for it?

I haven't really started yet because this time I'd rather go in the right direction from the beginning then refactor several tools later.

Could you tell me what I should take into consideration when designing such a system and whether there is a pattern for this?


问:
How should I contribute to a (mostly) abandoned GitHub project?
I've recently been trying to get into open source collaboration in GitHub and have run into a situation for which I am curious what is the preferred way to proceed.

About a month ago, I found a project on GitHub for a library that I had already been using for a while and in which I had found (and fixed) a few bugs.

As an initial foray into GitHub collaboration, I found the repo that seemed to have the highest volume of recent activity, fixed one bug, added unit tests, pushed up to GitHub, and made a pull request. Within a few hours, the maintainer of the repo that I forked had accepted the PR and merged in a few other PRs from other people that had been waiting as well.

Spurred on by this, I fixed three more bugs that I had found, each in a separate branch of my own repo, and filed an issue and pull request for each one separately.

That was just over a month ago, and the pull requests have been sitting there, untouched, ever since. The user whose repo I had forked doesn't seem to be very active, having only made 7 total contributions on GitHub in the past year, and that repo hasn't had any commits since that first pull request I made.

So my question:

How does one proceed in this situation? Ideally, I would like to avoid creating fragmentation of the library by going off and making a whole bunch of changes in my own repo that are not merged into the parent repo. Nonetheless, I would like to continue making bug fixes and adding features, but if I merge everything into my master branch and base all new fixes off of that branch, then if the maintainer of the repo that I forked ever does come back, I won't be able to split all of the changes into separate pull requests for each feature/bug fix (I've read that pull requests should generally be one pull request per feature or bug fix).

Should I keep one branch that is in step with the original repo, base all of my new branches off of that one, and then keep all the commits merged in my master branch? It seems like that would leave me with a whole ton of branches and an increasingly burdensome task every time I need to merge new changes into my master branch.

What is the typical way that one would approach a situation like this? It seems to be fairly common that a project will just become abandoned with the original contributors not around to review new pull requests. Is this a situation where somebody should just take up the helm and run with it? It seems like it would create fragmentation if the original contributors ever come back and want to work on the project again.

答:
If the owner of the original repo is not found anywhere and absent for a considerable, I would publish my own repository as a different version of the project.

With this, you take over the lead of development of the library, and don't leave it to die in a corner without being updated ever again. If the original owner ever closes the repo, the world still can use the forked version.


问:
Two user inputs that alter each other
I have a user interface with two numeric input boxes, send amount and receive amount. The values are in different currencies and are related by an exchange rate. That is, receive amount should always be send amount * exchange rate. But the user is allowed to click into either input box and modify the value, which causes the other value to be updated.

I've got a simple system to observe changes to either value and update the other one. I've had problems with infinite loops of the values updating each other because they're floats and multiplying then dividing by the exchange rate doesn't always create precisely the same value. So I added a simple flag to ignore updates while the updater itself is running.

But now I'm adding more functionality when the user updates an amount field, requiring other objects to listen to the fields. As a result some of those objects end up changing one of the amount fields, which sets off an infinite loop.

I've always felt like this is a fragile modelling of the problem, but I haven't thought of anything better. Is there any established pattern or approach to modelling two values that update each other?

答:
The right way to implement state and state change notifications is epitomized by the following setter method pseudocode:

```<code>method setValue( T newValue )
{
    if( newValue equals existingValue )
        return;
    existingValue = newValue;
    issue state change notification;
}
</code>```

This is known to work, and to work perfectly.  No infinite loops, no oscillations, no unnecessary notifications, no problems whatsoever.

Until one day someone decides to use floats.

Your problem is not with the very well established concept of state change notifications and the observer pattern, your problem is with the fact that you have been using a crappy data type for the job.

You tried to overcome the malfunctions caused by the imprecision inherent in floats with an approach which, although not outright wrong, was not really the correct approach for the problem at hand: you added a flag to ignore updates while the updater itself is running.

So, here are some approaches for solving your problem directly, instead of letting it be and trying to work around it:

Use proper equality comparisons for your floats: if( abs( float1 - float2 ) < epsilon ) where epsilon is a very small number like 0.00000001, depending on the desired precision.  For more information, see this: What's wrong with using == to compare floats in Java?

Use a "decimal" or "BigDecimal" data type instead of float. If you are dealing with currency values, you definitely should be doing this. For more information, see this: Why not use Double or Float to represent currency?

Title: Two user inputs that alter each other

Body:
The right way to implement state and state change notifications is epitomized by the following setter method pseudocode:

method setValue( T newValue )
{
    if( newValue equals existingValue )
        return;
    existingValue = newValue;
    issue state change notification;
}

This is known to work, and to work perfectly.  No infinite loops, no oscillations, no unnecessary notifications, no problems whatsoever.

Until one day someone decides to use floats.

Your problem is not with the very well established concept of state change notifications and the observer pattern, your problem is with the fact that you have been using a crappy data type for the job.

You tried to overcome the malfunctions caused by the imprecision inherent in floats with an approach which, although not outright wrong, was not really the correct approach for the problem at hand: you added a flag to ignore updates while the updater itself is running.

So, here are some approaches for solving your problem directly, instead of letting it be and trying to work around it:

Use proper equality comparisons for your floats: if( abs( float1 - float2 ) < epsilon ) where epsilon is a very small number like 0.00000001, depending on the desired precision.  For more information, see this: What's wrong with using == to compare floats in Java?

Use a "decimal" or "BigDecimal" data type instead of float. If you are dealing with currency values, you definitely should be doing this. For more information, see this: Why not use Double or Float to represent currency?


答:
There's a nice video from Apple's WWDC about this subject. Solution is simple:

Stored somewhere is the truth. The truth is not a number, it is a pair (number, currency). If a user enters a number into a Yen field, the truth is changed to X Yen. When a dollar field is notified, it doesn't change the truth to dollars. It displays the amount as best as it can, but it doesn't change the truth doing that. Only when the user enters a number, the truth is changed.

When the question was asked, there was the assumption that there are two truths, related by a formula, and that is where the trouble starts. One truth, not two.

Title: Two user inputs that alter each other

Body:
I have a user interface with two numeric input boxes, send amount and receive amount. The values are in different currencies and are related by an exchange rate. That is, receive amount should always be send amount * exchange rate. But the user is allowed to click into either input box and modify the value, which causes the other value to be updated.

I've got a simple system to observe changes to either value and update the other one. I've had problems with infinite loops of the values updating each other because they're floats and multiplying then dividing by the exchange rate doesn't always create precisely the same value. So I added a simple flag to ignore updates while the updater itself is running.

But now I'm adding more functionality when the user updates an amount field, requiring other objects to listen to the fields. As a result some of those objects end up changing one of the amount fields, which sets off an infinite loop.

I've always felt like this is a fragile modelling of the problem, but I haven't thought of anything better. Is there any established pattern or approach to modelling two values that update each other?


问:
Best approach to implement an update operation of a container object?
I have an Invoice object wich may contain several FacturedServices objects stord as a list.

In may interface, the user can edit an Invoice object, delete add or edit its FacturedServices list.

Whe the user hit the save button, the updates made to  Invoice object should be passed to the database as well.

The problem is the FacturedServices list will contain heterogenous data, because some of its elements are new, others changed and some of them have been deleted from the list.

What is the best way to implement hte update of the Invoice object in the database ?

I was thinking to add a dirty property on every FacturedService object, whenever it is changed, or set the property to "new" when its newely created and then do some if else in my controller :\

If you think my question should be rephrased, please do it

EDIT :
Say I have an object Invoice I
, It has 3 FacturedServices FS1, FS2, FS3

In the interface, the user edited FS1, deleted FS2, and added FS4 to the list

now the list contains edited FS1, unchanged FS3 and newly created FS4.

in my databse, I have an InvoiceTable and a FactureServicesTable whith a referencial inetgrety to the invoice id.

my problem is in my controller there must be a way to know which FS is new which one is updated and which one was deleted, so I can execute the correct SQL commands depending on the situation.

I know this is not something new, in every desktop application at some point there should be something similar to my problem. so what is the best way to do this.

答:
I would add a duplicate() method to invoice, so that the edited invoice is always a copy of the original.

If the user cancels editing, the duplicate gets discarded and nothing else happens.

If the user submits their changes, then I would compare the edited invoice against the original invoice to figure out what fields should be updated on the database, and I would also walk the respective lists of features to see which features have been added, which heve been modified, and which have been deleted.

Bonus:

An optional implementation of the comparison function which does not do any saving to the database can also be used to calculate at any given moment the enabled state of the 'ok', 'apply', and 'revert' buttons of the invoice editing form, as well as the text of the (always enabled) 'cancel' button.

When the edited invoice is identical to the original, the 'ok', 'apply' and 'revert' buttons should be disabled, while the text of the 'cancel' button should be "close".

When the edited invoice differs from the original, the 'ok', 'apply' and 'revert' buttons should be enabled, while the text of the 'cancel' button should be "cancel".


问:
number of strings, when each character must occur even times
I've been bashing my skull at this problem for some time now, and its really starting to frustrate me. The problem is:

I have a set of characters, A, B, C, and D. I have to tell in how many ways a string can be built from those characters, when the length is n and each character must occur even times.

For example, the answer for n = 2 is 4:

```<code>AA
BB
CC
DD
</code>```

The answer for n = 4 is 40. Some of those valid strings are:

```<code>AAAA
AABB
CACA
DAAD
BCCB
</code>```

I'm stuck at coming up with a logic. I feel like there could be a DP solution for this. Brute-forcing my way through this is out of the question: the number of solutions rapidly grow into huge numbers.

I've tried drawing all kinds of ideas on paper, to no avail. Almost all of those ideas I had to discard as their complexity was too big. The solution should be efficient for n = 10^4.

One of my ideas was to never keep track of the actual strings, but only whether each character has appeared even or odd times. I couldn't come up with a way to apply this logic.

Can anyone help me?

Body:
I tried to come up with a solution but failed and asked the same question on Mathematics.StackExchange.
Thanks to Rus May, here is a solution, in Common Lisp:

(defun solve (n)
  (if (evenp n)
      (/ (+ (expt 4 n) (* 4 (expt 2 n))) 8)
      0))

This always return 0 for odd values of n. For n = 500, here is the output with SBCL:

* (time (solve 500))

    Evaluation took:
      0.000 seconds of real time
      0.000000 seconds of total run time (0.000000 user, 0.000000 system)
      100.00% CPU
      51,100 processor cycles
      0 bytes consed

    1339385758982834151185531311325002263201756014631917009304687985462938813906170153116497973519619822659493341146941433531483931607115392554498072196838958545795769042788035468026048125208904713757765805163872455056995809556627183222337328039422584942896842901774597806462162357229520744881314972303360


问:
Why does this API include a static "kind" parameter in the request and response?
I am looking at the Google QPX Express API and noticed that each group of parameters includes a kind parameter that is set to a specific string. For example, on the request:

{
  "request": {
    "passengers": {
      "kind": "qpxexpress#passengerCounts",
      "adultCount": integer,
      "childCount": integer,
      "infantInLapCount": integer,
      "infantInSeatCount": integer,
      "seniorCount": integer
    },
    "slice": [
      {
        "kind": "qpxexpress#sliceInput",
        "origin": string,
        "destination": string,
        "date": string,
        "maxStops": integer,
        "maxConnectionDuration": integer,
        "preferredCabin": string,
        "permittedDepartureTime": {
          "kind": "qpxexpress#timeOfDayRange",
          "earliestTime": string,
          "latestTime": string
...
```

<p>The response includes a <code>kind</code> as well:</p>

<pre class="lang-js prettyprint-override"><code>{
  "kind": "qpxExpress#tripsSearch",
  "trips": {
    "kind": "qpxexpress#tripOptions",
    "requestId": string,
    "data": {
      "kind": "qpxexpress#data",
      "airport": [
        {
          "kind": "qpxexpress#airportData",
          "code": string,
          "city": string,
          "name": string
...
</code>```

What's the point of this parameter? Is this type of thing important to include in a well-designed API?

答:
Within the request and response you send it does not immediately make sense, but I'll give a simpler example. Imagine we'll have a pizza-ordering system, that allows us to order either pizza's (with extra toppings) or soft-drinks (potentially super-sized). To implement our service, we could format it like this:

```<code>{
    drinks: [{ brand: 'pipsi', size: 'large'}, { brand: 'cako loca', size: 'small' }],
    pizzas: [{ name: 'peperoni', toppings: 'mozarella'}]
}
</code>```

however, this quickly becomes cumbersome when we have many kinds of pizza's, drinks, desserts, etc. etc. Instead, we want to give some class to our little API. We could classify each of these in two different kinds: 'PizzaData' and 'SoftDrinkData'.

Now the parts of our order can be ordered in any order, and we even have the option to add versions of our API to specific subparts. It's also easier to break our message apart and send it to separate places and have those places figure out how to handle it. Lets see how it looks like now:

```<code>[
   { kind: 'SoftDrinkData', brand: 'pipsi', size: 'large' },
   { kind: 'SoftDrinkData', brand: 'cako loca', size: 'small' },
   { kind: 'PizzaData', name: 'peperoni', toppings: 'mozarella' }
]
</code>```

If our data-processors would introduce a new Pizza-type (say, you can specify the shape), you can add an extra version:

```<code>[ { kind: 'PizzaData@v2.0', name: 'Quatro Stagioni',
    toppings: 'salami', shape: 'triangular' } ]
</code>```

Old systems would now start to complain because they don't know how to handle 'PizzaData@v2.0'. That would be good, since you don't want the customer to get a round pizza. He ordered a triangular one after all. However, all other data can still be processed, so we can intermingle new and old systems together and we don't have a 'big bang'-moment when a new version of the API comes out.

Most JSON-libraries map the JSON data to instances of classes of an object-oriented language. The library needs to know which class to map to, so adding this extra data helps the library to map it to the right class, instead of relying on the location within the JSON tree.

Body:
Within the request and response you send it does not immediately make sense, but I'll give a simpler example. Imagine we'll have a pizza-ordering system, that allows us to order either pizza's (with extra toppings) or soft-drinks (potentially super-sized). To implement our service, we could format it like this:

{
    drinks: [{ brand: 'pipsi', size: 'large'}, { brand: 'cako loca', size: 'small' }],
    pizzas: [{ name: 'peperoni', toppings: 'mozarella'}]
}

however, this quickly becomes cumbersome when we have many kinds of pizza's, drinks, desserts, etc. etc. Instead, we want to give some class to our little API. We could classify each of these in two different kinds: 'PizzaData' and 'SoftDrinkData'.

Now the parts of our order can be ordered in any order, and we even have the option to add versions of our API to specific subparts. It's also easier to break our message apart and send it to separate places and have those places figure out how to handle it. Lets see how it looks like now:

[
   { kind: 'SoftDrinkData', brand: 'pipsi', size: 'large' },
   { kind: 'SoftDrinkData', brand: 'cako loca', size: 'small' },
   { kind: 'PizzaData', name: 'peperoni', toppings: 'mozarella' }
]

If our data-processors would introduce a new Pizza-type (say, you can specify the shape), you can add an extra version:

[ { kind: 'PizzaData@v2.0', name: 'Quatro Stagioni',
    toppings: 'salami', shape: 'triangular' } ]

Old systems would now start to complain because they don't know how to handle 'PizzaData@v2.0'. That would be good, since you don't want the customer to get a round pizza. He ordered a triangular one after all. However, all other data can still be processed, so we can intermingle new and old systems together and we don't have a 'big bang'-moment when a new version of the API comes out.

Most JSON-libraries map the JSON data to instances of classes of an object-oriented language. The library needs to know which class to map to, so adding this extra data helps the library to map it to the right class, instead of relying on the location within the JSON tree.


答:
I haven't had this situation yet, but that's what I would try:

Try contacting the owner

Maybe they really lost interest, but are willing to transfer the project to somebody else, in particular someone who has already shown considerate commitment.

But perhaps they are just occupied  with something else (work, vacations, illness, other projects) and didn't have time to handle your PR, but plan to do so later.

Or maybe they have really stopped work on the project permanently for whatever reason.

Without asking, you won't find it out.

Get in touch with the community

Surely there are other people who have contributed to, or at least used the project. Check who has forked the project (even if they haven't made any change, they might still be interested in seeing this project thriving); check who has reported issues, or commented upon them. Maybe there's also a community outside GitHub, e.g a mailing list, forum, or StackOverflow members.

I'm you eventually really take over the project, you might want their support. And they need  to know where the new master repository is.

Continue to make good pull requests

This shows both the owner and the community that you are serious about it, and let's them judge your contributions.

Title: How should I contribute to a (mostly) abandoned GitHub project?

Body:
I've recently been trying to get into open source collaboration in GitHub and have run into a situation for which I am curious what is the preferred way to proceed.

About a month ago, I found a project on GitHub for a library that I had already been using for a while and in which I had found (and fixed) a few bugs.

As an initial foray into GitHub collaboration, I found the repo that seemed to have the highest volume of recent activity, fixed one bug, added unit tests, pushed up to GitHub, and made a pull request. Within a few hours, the maintainer of the repo that I forked had accepted the PR and merged in a few other PRs from other people that had been waiting as well.

Spurred on by this, I fixed three more bugs that I had found, each in a separate branch of my own repo, and filed an issue and pull request for each one separately.

That was just over a month ago, and the pull requests have been sitting there, untouched, ever since. The user whose repo I had forked doesn't seem to be very active, having only made 7 total contributions on GitHub in the past year, and that repo hasn't had any commits since that first pull request I made.

So my question:

How does one proceed in this situation? Ideally, I would like to avoid creating fragmentation of the library by going off and making a whole bunch of changes in my own repo that are not merged into the parent repo. Nonetheless, I would like to continue making bug fixes and adding features, but if I merge everything into my master branch and base all new fixes off of that branch, then if the maintainer of the repo that I forked ever does come back, I won't be able to split all of the changes into separate pull requests for each feature/bug fix (I've read that pull requests should generally be one pull request per feature or bug fix).

Should I keep one branch that is in step with the original repo, base all of my new branches off of that one, and then keep all the commits merged in my master branch? It seems like that would leave me with a whole ton of branches and an increasingly burdensome task every time I need to merge new changes into my master branch.

What is the typical way that one would approach a situation like this? It seems to be fairly common that a project will just become abandoned with the original contributors not around to review new pull requests. Is this a situation where somebody should just take up the helm and run with it? It seems like it would create fragmentation if the original contributors ever come back and want to work on the project again.


问:
Do algorithms depend on computer architectures?
I read somewhere (forgot which book it is) that algorithms are independent of computer architectures. Some even say algorithms are themselves computation (machines?)?

On the other hand, books on parallel programming have chapters on parallel algorithms. It seems like parallel algorithms depend on parallel architectures?

I think I miss some big pictures? Thanks.

答:
Algorithms are the series of steps taken to solve a particular problem. The recipe for solving the problem, if you will. "Programs" do the same things, of course; we use "algorithm" to suggest the "generalized" or "generally applicable" recipes that are independent of specific machine designs, programming languages, and such.

Algorithms are meant to be general, but they can still depend on some features being present. "Concurrent algorithms," for example, might depend on you having some mechanism for different programs to run concurrently. "Distributed algorithms" can depend on you having more than one system in a cooperating group, and a network or other communication scheme between them. Similarly, "parallel algorithms" are often those designed to run when you have multiple processing units--potentially many, many processing units, and the sort of communication facilities that are common when you have large arrays of processing units. You may be able to run a "parallel algorithm" even when you have only one computer or one CPU--but it's not terribly interesting in the way having traffic engineers isn't very useful unless you also have roads.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
Copy the Smartest Guys

In the case of programming languages, copy the style of the developer of the language.

For example I code C exactly as is done in K&R.

Then when anybody tries to start a boring coding style conversation, I can tell them "bring that up with Dennis Ritche and let me know what he says."


问:
Writing High Quality Software Proposals
I've been reading over some proposals for software projects recently and I'm a little concerned by what I've seen. Often I feel that proposals have been rushed and/or poorly thought out.

It's very possible that proposals don't need to look like a basket of fruit, but if your pitching for work or seeking approval for funding, there has to be some guidelines available for what constitutes a "decent" proposal.

I was wondering if anyone was aware of good guidelines for writing software proposals or could possibly point me at books/websites etc?

答:
I was searching for the answer on this question a year ago. Frankly speaking, there is a lot of information about it in the internet. Not everything makes sense unfortunately. :(

I made some research and requested from 20+ software development companies for the project I proposed to implement. I collected their proposals and reviewed them carefully. And I'd say the following sections must be included into a good project proposal.

Nice Front page

Project description with system architecture and other pictures

Work scope breakdown into tasks and sub-tasks with man-hours estimation of each one

Delivery schedule

Budget calculation and payment terms

Marketing information like portfolio samples and references

The most important for certain is #3. So important that I'll probably even write an  article about it a bit later.

But remember that the more detailed dividing out the work scope is done, then the more correct estimation could be provided and the better impression it gives to the customer when he reads the proposal.

We also tried to find good software to automatically generate proposals for software projects and maybe some basic CRM.
We reviewed sw proposal, proposal pad, and a few others. I don't really want to advertise anyone of them so you can decide yourself which best suits your needs. We have been using such software and generally it makes our life easier. Our staff doesn't even need to think which sections should be included since the software has predefined fields which suit our needs.

Title: Writing High Quality Software Proposals


答:
"It seems like parallel algorithms depend on parallel architectures?"

In my opinion the answer is simply: no.
General I only get the properties

parallelism

word size (implicit resource limits)

when thinking of hardware architecture.

Referring to parallelism you can have any parallel algorithm be batch computed and any parallel arch to work serial so the algorithm does not depend on that. Word size might be an issue to numeric stability but not to the algorithm itself. Resource limits like 64bit can only describe 2^64 different numbers could be a problem, but anyway elements are limited.

Of course there might be some algorithms which are depending on some extended instruction sets, but at least everything can be described with basic math.

For example with quantum computing some Big-O values may change and then I would say that

"algorithms are independent of computer architectures"

is not true anymore.

Title: Do algorithms depend on computer architectures?

Body:
I read somewhere (forgot which book it is) that algorithms are independent of computer architectures. Some even say algorithms are themselves computation (machines?)?

On the other hand, books on parallel programming have chapters on parallel algorithms. It seems like parallel algorithms depend on parallel architectures?

I think I miss some big pictures? Thanks.


问:
Are utility classes with nothing but static members an anti-pattern in C++?
The question Where should I put functions that are not related to a class has sparked some debate over whether it makes sense in C++ to combine utility functions in a class or just have them exist as free functions in a namespace.

I come from a C# background where the latter option does not exist and thus naturally trend toward using static classes in the little C++ code I write. The highest voted answer on that question as well as several comments however say that free functions are to be preferred, even suggesting static classes were an anti-pattern. Why is that so in C++? At least on the surface, static methods on a class seem indistinguishable from free functions in a namespace. Why thus the preference for the latter?

Would things be different, if the collection of utility functions needed some shared data, e.g. a cache one could store in a private static field?

答:
Much of the discourse on the topic here makes sense, though there is something very fundamental about C++ that makes namespaces and classes/structs very different.

Static classes (classes where all members are static, and the class will never be instantiated) are themselves objects. They are not simply a namespace to contain functions.

Template meta-programming allows us to use a static class as a compile-time object.

Consider this:

```<code>template<typename allocator_type> class allocator
{
public:
    inline static void* allocate(size_t size)
    {
        return allocator_type::template allocate(size);
    }
    inline static void release(void* p)
    {
        allocator_type::template release(p);
    }
};
</code>```

To use it we need functions contained inside a class. A namespace will not work here. Consider:

```<code>class mallocator
{
    inline static void* allocate(size_t size)
    {
        return std::malloc(size);
    }
    inline static void release(void* p)
    {
        return std::free(p);
    }
};
</code>```

Now to use it:

```<code>using my_allocator = allocator<mallocator>;

void* p = my_allocator::allocate(1024);
...
my_allocator::release(p);
</code>```

So long as a new allocator exposes an allocate and release function that is compatible, switching to a new allocator is easy.

This can not be achieved with namespaces.

Do you always need functions to be part of a class? No.

Is using a static class an anti-pattern? It depends on the context.

Would things be different, if the collection of utility functions
  needed some shared data, e.g. a cache one could store in a private
  static field?

In that case what you're trying to achieve is likely to be best served through object-oriented programming.

Body:
Much of the discourse on the topic here makes sense, though there is something very fundamental about C++ that makes namespaces and classes/structs very different.

Static classes (classes where all members are static, and the class will never be instantiated) are themselves objects. They are not simply a namespace to contain functions.

Template meta-programming allows us to use a static class as a compile-time object.

Consider this:

template<typename allocator_type> class allocator
{
public:
    inline static void* allocate(size_t size)
    {
        return allocator_type::template allocate(size);
    }
    inline static void release(void* p)
    {
        allocator_type::template release(p);
    }
};

To use it we need functions contained inside a class. A namespace will not work here. Consider:

class mallocator
{
    inline static void* allocate(size_t size)
    {
        return std::malloc(size);
    }
    inline static void release(void* p)
    {
        return std::free(p);
    }
};

Now to use it:

using my_allocator = allocator<mallocator>;

void* p = my_allocator::allocate(1024);
...
my_allocator::release(p);

So long as a new allocator exposes an allocate and release function that is compatible, switching to a new allocator is easy.

This can not be achieved with namespaces.

Do you always need functions to be part of a class? No.

Is using a static class an anti-pattern? It depends on the context.

Would things be different, if the collection of utility functions
  needed some shared data, e.g. a cache one could store in a private
  static field?

In that case what you're trying to achieve is likely to be best served through object-oriented programming.


答:
In theory, algorithms are entirely independent of architecture. You can always emulate a parallel architecture on a single-issue timesliced system. You can reason about algorithms without an architecture at all. Knuth's book uses a fictional architecture.

In practice there are algorithms that attempt to achieve better runtime for the same "O" complexity by optimizing the use of cache hardware and synchronisation primitives.


答:
Algorithms are independent of computer architecture. That's because algorithms define a series of processes that solves a problem. Regardless of architectures, sorting algorithms will always sort. It wouldn't suddenly render 3D drawings on some architectures.

If you think about it, this is actually intuitive. Google Chrome (which is merely a collection of algorithms) is a web browser when compiled for any architecture. It wouldn't suddenly become a device driver on some architectures.

But the speed with which algorithms runs depends on architectures. And some algorithms work faster than others depending on architectures.

If you think about it, this is also actually intuitive. Given an algorithm, it's always possible for the hardware designer to design an architecture that specifically speeds up that algorithm. That's one reason why there are things like 3D accelerated graphics cards and bitcoin miner accelerators.

When people talk about parallel algorithms, they're talking about a family of algorithms that can work faster on parallel architectures. There are plenty of algorithms that aren't improved by parallel architectures. So identifying new algorithms for the same problem that work well in parallel is an active area of research.

But those algorithms still do the same things. Architectures don't change what they do.


问:
Is throwing an exception an anti-pattern here?
I just had a discussion over a design choice after a code review. I wonder what your opinions are.

There's this Preferences class, which is a bucket for key-value pairs. Null values are legal (that's important). We expect that certain values may not be saved yet, and we want to handle these cases automatically by initializing them with predefined default value when requested.

The discussed solution used following pattern (NOTE: this is not the actual code, obviously - it's simplified for illustrative purposes):

```<code>public class Preferences {
    // null values are legal
    private Map<String, String> valuesFromDatabase;

    private static Map<String, String> defaultValues;

    class KeyNotFoundException extends Exception {
    }

    public String getByKey(String key) {
        try {
            return getValueByKey(key);
        } catch (KeyNotFoundException e) {
            String defaultValue = defaultValues.get(key);
            valuesFromDatabase.put(key, defaultvalue);
            return defaultValue;
        }
    }

    private String getValueByKey(String key) throws KeyNotFoundException {
        if (valuesFromDatabase.containsKey(key)) {
            return valuesFromDatabase.get(key);
        } else {
            throw new KeyNotFoundException();
        }
    }
}
</code>```

It was criticized as an anti-pattern - abusing exceptions to control the flow. KeyNotFoundException - brought to life for that one use case only - is never going to be seen out of the scope of this class.

It's essentially two methods playing fetch with it merely to communicate something to each other.

The key not being present in the database isn't something alarming, or exceptional - we expect this to occur whenever a new preference setting is added, hence the mechanism that gracefully initializes it with a default value if needed.

The counterargument was that getValueByKey - the private method - as defined right now has no natural way of informing the public method about both the value, and whether the key was there. (If it wasn't, it has to be added so that the value can be updated).

Returning null would be ambiguous, since null is a perfectly legal value, so there's no telling whether it meant that the key wasn't there, or if there was a null.

getValueByKey would have to return some sort of a Tuple<Boolean, String>, the bool set to true if the key is already there, so that we can distinguish between (true, null) and (false, null). (An out parameter could be used in C#, but that's Java).

Is this a nicer alternative? Yes, you'd have to define some single-use class to the effect of Tuple<Boolean, String>, but then we're getting rid of KeyNotFoundException, so that kind of balances out. We're also avoiding the overhead of handling an exception, although it's not significant in practical terms - there are no performance considerations to speak of, it's a client app and it's not like user preferences will be retrieved millions of times per second.

A variation of this approach could use Guava's Optional<String> (Guava is already used throughout the project) instead of some custom Tuple<Boolean, String>, and then we can differentiate between Optional.<String>absent() and "proper" null. It still feels hackish, though, for reasons that are easy to see - introducing two levels of "nullness" seem to abuse the concept that stood behind creating Optionals in the first place.

Another option would be to explicitly check whether the key exists (add a boolean containsKey(String key) method and call getValueByKey only if we have already asserted that it exists).

Finally, one could also inline the private method, but the actual getByKey is somewhat more complex than my code sample, thus inlining would make it look quite nasty.

I may be splitting hairs here, but I'm curious what you would bet on to be closest to best practice in this case. I didn't find an answer in Oracle's or Google's style guides.

Is using exceptions like in the code sample an anti-pattern, or is it acceptable given that alternatives aren't very clean, either? If it is, under what circumstances would it be fine? And vice versa?

答:
Optional is the correct solution.  However, if you prefer, there is an alternative which has less of a "two nulls" feel, consider a sentinel.

Define a private static string keyNotFoundSentinel, with a value new String("").*

Now the private method can return keyNotFoundSentinel rather than throw new KeyNotFoundException().  The public method can check for that value

```<code>String rval = getValueByKey(key);
if (rval == keyNotFoundSentinel) { // reference equality, not string.equals
    ... // generate default value
} else {
    return rval;
}
</code>```

In reality, null is a special case of a sentinel.  It is a sentinel value defined by the language, with a few special behaviors (i.e. well defined behavior if you call a method on null).  It just happens to be so useful to have a sentinel like that that nearly ever language uses it.

*  We intentionally use new String("") rather than merely "" to prevent Java from "interning" the string, which would give it the same reference as any other empty string.  Because did this extra step, we are guaranteed that the String referred to by keyNotFoundSentinel is a unique instance, which we need to ensure it can never appear in the map itself.

Body:
Optional is the correct solution.  However, if you prefer, there is an alternative which has less of a "two nulls" feel, consider a sentinel.

Define a private static string keyNotFoundSentinel, with a value new String("").*

Now the private method can return keyNotFoundSentinel rather than throw new KeyNotFoundException().  The public method can check for that value

String rval = getValueByKey(key);
if (rval == keyNotFoundSentinel) { // reference equality, not string.equals
    ... // generate default value
} else {
    return rval;
}

In reality, null is a special case of a sentinel.  It is a sentinel value defined by the language, with a few special behaviors (i.e. well defined behavior if you call a method on null).  It just happens to be so useful to have a sentinel like that that nearly ever language uses it.

*  We intentionally use new String("") rather than merely "" to prevent Java from "interning" the string, which would give it the same reference as any other empty string.  Because did this extra step, we are guaranteed that the String referred to by keyNotFoundSentinel is a unique instance, which we need to ensure it can never appear in the map itself.


答:
Algorithms doesn't depend on computer architecture, however the efficiency of running any particular algorithm does depend on the architecture. Any Turing Complete machines can emulate any other Turing Complete machines, although some machines would be better at one thing than others.

What we mean by concurrent algorithms is that the algorithm plays well or can take advantage of concurrency in the machine, maybe because it requires less locking that otherwise would have been required by algorithms that aren't specifically designed for the concurrent machine or maybe because the algorithm makes use of divide and conquer effectively to use the full power of the machine. Running the algorithm in a non concurrent machine would still be possible but may not be as efficient or it may require additional locking to perform correctly.

There are also algorithms that are designed to take advantage of the quirk of a particular architecture, like cache-friendly algorithms, which optimises caching. These algorithms may be less efficient in machines that doesn't cache the way the algorithm assumes.


答:
Yes and no. It depends on the constraints you want to meet and the preconditions needed to run your algorithm.

Ideally, an algorithm is an abstract recipe that defines step-by-step how to do something. Algorithms was defined like so with the goal of reproducibility, and later automatization. Algorithms originates from lambda-calcul, so you can easily see why they are made in such a way. This definition is the usual one, but modern algorithms can be non-sequential (not step-by-step, like concurrent algorithms, or logical ones like the ones using unification), non-linear (stochastic algorithms) or just plainly weird (quantum algorithms), but I'll pass that.

Thus, ideally, an algorithm should be as abstract as possible without accounting any hardware.

But, as with any system, you must define some axioms, not only to get a coherent system, but also to gain time. For instance, most algorithms presume, at the very least implicitly, that they are defined on a Von-Neumann machine. If that was not the case, they would need to explicitly define each parts of the system they need to be run on (since this is required to reproduce the recipe, this a kind of precondition). Also, often algorithms relies on common commands such as write() without defining them fully.

Another reason why algorithms are not so abstract from hardware architecture, is when you need to meet some constraints.

Let's say you are working on embedded systems, then probably you can't rely on the same amount of resources you have on workstations. One of the most restrained resources is probably memory. However, most algorithms tend to optimize the time complexity (speed of execution on CPU), not the memory complexity (amount of memory necessary to work on the data). For these systems, memory optimized algorithms have been devised where non memory optimized algorithms would just fail or run a lot slower. In fact, embedded systems are not the sole target of memory efficient algorithms: for example, there are cache-oblivious algorithms that adapts their processing to efficiently use the CPU cache. Another example: some machine learning algorithms for big data are tailored for incremental learning or out-of-core computing to process huge amount of data far bigger than memory available on any computer, etc.

There are also algorithms that do not optimize a specific part of the computer, but a standard that is dependent on hardware architecture. For example, numerical data that need precision are stored inside float or double, which are by nature limited due to hardware limits. The problem is that complex computations can lead to rounding, and the more calculations you do over rounded numbers, the more you will drift off. This is called a catastrophic interference. Some applications need a critical precision, even at the cost of some worst complexity. For this type of applications, algorithms that optimize their calculation to reduce or remove catastrophic interference were made.

Thus, designing an algorithm can also be a trade-off between abstraction and constraints.

In the end, we can say that an algorithm is as abstract as its target is, and as its preconditional (architecture) needs. The more specific target your algorithm aims, the more it will probably rely on the hardware architecture.

Some related keywords that may interest you:

Locality of Reference

Loop optimization

Loop nest optimization

Scalable locality


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: Lack of high quality coffee.</p>

Title: What can slow a developer down?

Body: Lack of high quality coffee.


问:
What to do when time estimation goes wrong?
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

答:
This is a common problem :)

One of the more simple approaches is to add a buffer to any estimation you do, as unforseen problems always occur. The size of the buffer depends on the size of the team and the uncertainty of the technology and problem itself.

Bigger teams have more people who might get sick and less people that know "everything".

New technologies are always riskier than the ones you already know.

And when you see that you won't be finished on the estimated date, communicate early with the stakeholders.
Maybe you can re-prioritize stuff or delay certain features after speaking with the customer/stakeholder.


问:
What is the customary way of sharing a code snippet to illustrate a reported bug on GitHub?
I reported a bug on GitHub, now I'm asked for files, but there's no way to attach them to the raised issue (e.g. on Launchpad you can attach file to a bug report, but on GitHub there's only option to attach pictures).

I've read the issues section of the GitHub FAQ, but didn't find anything sufficiently illuminating. It seems like a novice user is implicitly directed by the site somewhere, but where?

Should I just create a repository and put all the requested snippets and output files there? Or should I just email the files to the project's maintainer? What I'm asking here boils down to this: what people do usually?

答:
Many projects hosted on github have some infrastructure for testing, i.e. some input files and expected output (e.g. fish-shell has a tests/ directory) You could patch the software (i.e. fork it then make a pull request) to add an additional test case illustrating the bug.

You should also contact some of the main authors, they probably will be happy to get a bug report .... And you could report some issue (see this example)

At last, if you find a bug and are able to correct it, you fork the repo, patch it, and make a pull request.


问:
Should private functions be held to the same standards as public functions?
If I'm building private utility functions, should they be held to the same rigorous standards in terms of handling invalid data as public functions?

Example:If I'm writing code to calculate the length of a linked list, and the list being passed is one created by my own code, should it be checked for loops if my code does not create linked lists with loops in the 1st place?

答: Write the minimum amount of code to do the job properly. In your example I'd say don't bother, if there is no way (without code modifications) that it make loops then don't bother accounting for it. You'll end up writing less code which you can expand on later, rather than too much code which could potentially get confusing later on.</p>


答:
You shouldn't confuse an algorithm in general with mathematical or computing algorithms. If you mean computing algorithms, yes, they are independent from the machine architecture.

Definition of algorithm from Wikipedia:

In mathematics and computer science, an algorithm is a self-contained step-by-step set of operations to be performed. Algorithms exist that perform calculation, data processing, and automated reasoning.

This definition is used to refer some closed computation or data processing tasks. In the other words, computations which can abstractly be run on Turing Machine. However, recently there is a concept in mathematics named Interactive computation that involves input/output communication with the external world during computation.

In a general definition, the algorithm is just a recipe (sequence of instructions). I think you can't think of an algorithm without knowing the instruction set or operations which you can use; Mathematical operations are about calculation, then an algorithm which includes an step named 'heat up the oven' is not a mathematical algorithm but you can give it to a chef, because he knows how to execute it.

Then, you can create a machine which can do X, Y, Z.... each of these could be used in your algorithm as an instruction. But if they are all about closed computation (in fact, non-interactive deterministic digital small-step computations), then one can prove that your machine is equivalent to Turing Machine. But if you target other type of computations (continues values or interactive computation [however I am not sure if they are really another type of computation]) or even none-computing tasks, you can think of machines which can perform them.

This question and answer is also interesting to get a broader perspective on algorithms.


答:
Naturally, private methods have just as much to gain as public methods do, from checking to make sure that every single bit of their input is correct. Generally, no programmer would ever be asking themselves the question of whether more checks are better than fewer checks, (duh!) if it was not for performance concerns.

Now, when it comes to checking for invalid stuff there are two types of checks that you can perform:

Production-time checks, (in short, runtime checks) which happen both on development and on production environments. (Out there on the field.)

Development-time-only assertions, (in short, assertions) which happen only in development environments and are skipped on production environments.

Assertions have the mind-bogglingly useful characteristic of not incurring any performance penalty on production environments, so they can be used very liberally.  Go ahead and assert everything you can, it does not affect performance. On the contrary, asserting everything is good for robustness, it is good for debugging, it is good for documentation, it is good for keeping the state complexity of your program down; in short, it is the best thing since sliced bread.  So:

The question you should always be asking

is not "should I assert this?"

but "is there anything I forgot to assert?"

So, in a well designed system, both private methods and public methods check everything there is to check, the only difference being the following:

All (well, almost all) of the checks performed by private methods are assertions.

Many of the checks performed by public methods are runtime checks, (not assertions,) if the public interface of the object demands so. Generally, these checks are for things that may conceivably happen under normal usage and they are not necessarily bugs.

For example, if you are coding a File class, then a failure to open the file is generally not a bug, so it should be checked against and generate an exception even on production. On the other hand, if someone passes your public file-open method a null filename, that is a bug in the caller's code, so the check for a null filename can be an assertion.

And generally, every single thing which gets checked with a runtime check in a public method can also be checked again in a private method, but this time with an assertion, since all input ought to have already been validated by the public methods, so anything bad reaching a private method means you have a bug in your code.

So, in general:

Nothing should ever go unchecked, either in public or in private methods.

Assertions are free, so use them liberally.

DISCLAIMER: Since this is an interview question, please bear in mind that the above may, and may not, be what the interviewer would like to hear from you.  In such cases it is best to prefix your answer with a disclaimer like "Well, I would of course follow whatever discipline is generally used in the house, but if it was completely up to me, then I would ..."

Title: Should private functions be held to the same standards as public functions?

Body:
If I'm building private utility functions, should they be held to the same rigorous standards in terms of handling invalid data as public functions?

Example:If I'm writing code to calculate the length of a linked list, and the list being passed is one created by my own code, should it be checked for loops if my code does not create linked lists with loops in the 1st place?


答:
YES.  Private methods should be held to the same standards as public ones.

Recall that there is a Bell Curve.

Recall that about 50% of programmers are below average.  By definition.

Assume that you will NOT be the only person who ever works on your code.

Assume that at least one of the people who works on your code will be someone who should not be allowed access to even Dartmouth BASIC on a standalone minicomputer.

Now, are you STILL sure there will never be any loops in your lists?

I didn't think so.


答:
If you are pointing to specific lines in the code base, you can use line links to deep-link into the code. (You should pick a specific commit and not just point to master as those links might become outdated if the code changes.)

If you just want to put up some sample code that you created, that is a perfect use for Github Gists. These can even be cloned and updated like a regular repo, but are much more lightweight.

If you have code that can be demonstrated in a browser, use JSFiddle or similar to create something people can see and interact with.

Bonus: If you are trying to demonstrate performance issues in JavaScript, you can use jsPerf to write an example test.

Title: What is the customary way of sharing a code snippet to illustrate a reported bug on GitHub?

Body:
I reported a bug on GitHub, now I'm asked for files, but there's no way to attach them to the raised issue (e.g. on Launchpad you can attach file to a bug report, but on GitHub there's only option to attach pictures).

I've read the issues section of the GitHub FAQ, but didn't find anything sufficiently illuminating. It seems like a novice user is implicitly directed by the site somewhere, but where?

Should I just create a repository and put all the requested snippets and output files there? Or should I just email the files to the project's maintainer? What I'm asking here boils down to this: what people do usually?


答:
Yes.

A private, internal function is called by some other function (or is dead code).

While a private function is not part of a public interface for a class, namespace, or module, it still can produce useful work for functions that are part of the public interface. While not exposed directly, it does contribute to the public interface transitively.

Private functions need to be tested, documented, and coded to the same standards as public functions. The only standard I would be lax on is documentation: there should be a quick note about what the function does, pre and post conditions, but there is no need to go into as much detail as with public documentation because a private/internal function does not need to be understood by developers outside your team.