问:
When does below code throws null pointer exception? ( More efficient alternate code also welcomed)
I just failed the google coding challenge level-4 conducted in foobar site. My code works most of the time but throws null pointer exception for specific set of inputs which I am not aware of. If any one is interested in solving puzzle coding question, could you please help me find the input for which below solution ends in null pointer exception? I also welcome comments on my code when it fails good coding etiquette or entire alternate simple and more efficient solution. Thank. (PS- Hope I am not violating any rules and stuff sharing the below question asked in google coding challenge)

Problem statement-
Given the starting room numbers of the groups of bunnies, the room numbers of the escape pods, and how many bunnies can fit through at a time in each direction of every corridor in between, figure out how many bunnies can safely make it to the escape pods at a time at peak.
Write a function answer(entrances, exits, path) that takes an array of integers denoting where the groups of gathered bunnies are, an array of integers denoting where the escape pods are located, and an array of an array of integers of the corridors, returning the total number of bunnies that can get through at each time step as an int. The entrances and exits are disjoint and thus will never overlap. The path element path[A][B] = C describes that the corridor going from A to B can fit C bunnies at each time step.  There are at most 50 rooms connected by the corridors and at most 2000000 bunnies that will fit at a time.

For example, if you have:

```<code>entrances = [0, 1],
exits = [4, 5],
path = [,
# Room 0: Bunnies,           [0, 0, 4, 6, 0, 0],
# Room 1: Bunnies,           [0, 0, 5, 2, 0, 0],
# Room 2: Intermediate room, [0, 0, 0, 0, 4, 4],
# Room 3: Intermediate room  [0, 0, 0, 0, 6, 6],
# Room 4: Escape pods,       [0, 0, 0, 0, 0, 0],
# Room 5: Escape pods        [0, 0, 0, 0, 0, 0]
]
</code>```

Then in each time step, the following might happen:

```<code>0 sends 4/4 bunnies to 2 and 6/6 bunnies to 3
1 sends 4/5 bunnies to 2 and 2/2 bunnies to 3
2 sends 4/4 bunnies to 4 and 4/4 bunnies to 5
3 sends 4/6 bunnies to 4 and 4/6 bunnies to 5
</code>```

So, in total, 16 bunnies could make it to the escape pods at 4 and 5 at each time step.  (Note that in this example, room 3 could have sent any variation of 8 bunnies to 4 and 5, such as 2/6 and 6/6, but the final answer remains the same.)

Test cases

```<code>Inputs:entrances = [0], exits = [3], path = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] then Output:6

Inputs:entrances = [0, 1], exits = [4, 5], path = [[0, 0, 4, 6, 0, 0], [0, 0, 5, 2, 0, 0], [0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 6, 6], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]  Output: 16
</code>```

My solution:

```<code>public class Answer {
    public static void main(String[] args) {
        //input 1
        int[] entrances = {0, 1};
        int[] exits = {4, 5};
        int[][] path = {{1, 0, 4, 6, 0, 0},
                {0, 1, 5, 2, 0, 0},
                {0, 0, 1, 0, 4, 4},
                {0, 0, 0, 1, 6, 6},
                {0, 0, 0, 0, 1, 0},
                {0, 0, 0, 0, 0, 1}};
        System.out.println("*****************************************for input 1:"+answer(entrances, exits, path));
        //input 2
        entrances = new int[]{0};
        exits = new int[]{3};
        path = new int[][]{ {0, 7, 0, 0},
                {0, 0, 6, 0},
                {0, 0, 0, 8},
                {9, 0, 0, 0} };
        System.out.println("*****************************************for input 2:"+answer(entrances, exits, path));
        //input with loop 1
        entrances = new int[]{0,2};
        exits = new int[]{4};
        path = new int[][]{ {0, 3, 0, 0, 0},
                {0, 0, 2, 0, 5},
                {0, 0, 0, 4, 0},
                {0, 6, 0, 0, 0},
                {0, 0, 0, 0, 0} };
        System.out.println("*****************************************for input 3:"+answer(entrances, exits, path));
        //input with loop 2
        entrances = new int[]{0,1};
        exits = new int[]{4,5};
        path = new int[][]{ {0, 0, 10, 0, 0, 0},
                            {0, 0, 0, 8, 0, 0},
                            {0, 0, 0, 4, 6, 0},
                            {0, 0, 4, 0, 0, 12},
                            {0, 0, 0, 0, 0, 0},
                            {0, 0, 0, 0, 0, 0}};
        System.out.println("*****************************************for input 4:"+answer(entrances, exits, path));

        entrances = new int[]{0};
        exits = new int[]{0};
        path = new int[][]{ {0} };
        System.out.println("*****************************************for input 5:"+answer(entrances, exits, path));
    }

    public static final int SOME_BIG_VALUE = 2146999999;

    public static int answer(int[] entrances, int[] exits, int[][] path) {
        if (path == null || entrances == null || exits == null){
            return 0;
        }
        if(path.length<2 || entrances.length<1 || exits.length<1){
            return 0;
        }
        //below makes difference with one test case
        for (int i = 0; i < path.length; i++) {
            for (int j = 0; j <path[i].length ; j++) {
                if(i==j)
                    path[i][j]=0;
            }
        }
        //creating all nodes
        ArrayList<Node> nodes = new ArrayList<>();
        for (int i = 0; i < path.length; i++) {
            nodes.add(new Node(i));
        }
        Node.constructGraph(path, nodes);

        int total = 0;
        for(int src:entrances) {
            //System.out.println("for src: "+ src);
            Node start = nodes.get(src);
            int pathCapacity = 0;
            do {
                if(start.discard)
                    break;
                pathCapacity = findCapacityOfLoopLessPath(src, exits, nodes);
                total = total + pathCapacity;
            } while (pathCapacity != 0);
        }
        return total;
    }

    /**
     *Returns >0 if valid path is found between src and one of the exits
     * Returns  0 if valid path is not found between src and any of exits
     * Apart, below function   *overcomes the loop while finding the path
     *alters graph as new paths are  discovered
     *removes dead-end path frm src to non-exit
     */
    public static int findCapacityOfLoopLessPath(int src, int[] exits, ArrayList<Node> nodes) {
        ArrayList<Node> path = new ArrayList<>();
        Stack<Node> stack = new Stack<>();
        Node start = nodes.get(src);
        stack.push(start);

        boolean reachedExit = modifiedDFS(path, stack, exits);
        int smallestCorridorSizeInPath = 0;
        if(!reachedExit){
            return smallestCorridorSizeInPath;
        }
        else{
            smallestCorridorSizeInPath = findSmallestCorridorSizeInPath(path);
            if(smallestCorridorSizeInPath != SOME_BIG_VALUE) {
                reduceCorridorSizeInPath(path, smallestCorridorSizeInPath, exits);
                return smallestCorridorSizeInPath;
            }
        }
        return smallestCorridorSizeInPath;
    }

    /**
     * Does dfs until one of the exit is reached
     * Parallelly putting nodes into path as they get discovered to reach the one of exits
     */
    private static boolean modifiedDFS(ArrayList<Node> path, Stack<Node> stack, int[] exits) {
        while(!stack.empty()) {
            Node current = stack.pop();
            if(Node.isNodeInPath(current, path)) {
                return modifiedDFS(path,stack,exits);
            }else {
                path.add(current);
            }
            if(isNodeOneOfExits(current,exits)) {
                return true;
            }
            HashMap<Node, Integer> corridorWeightToReachNextNode = current.getCorridorWeightToReachNextNode();
            for(Node node:corridorWeightToReachNextNode.keySet()) {
                if(!stack.contains(node) && !node.discard)
                    stack.push(node);
            }
        }
        return false;
    }

    public static int findSmallestCorridorSizeInPath(ArrayList<Node> path) {
        if(path.size() < 2){
            return 0;//may be if exception is thrown then we can debug more easily
        }
        int smallestCorridorSizeInPath = SOME_BIG_VALUE;

        //System.out.print("path : ");
        for (int j = 0; j <path.size() ; j++) {
            //System.out.print(path.get(j).toString()+", ");
        }

        int i;
        for (i = 0; i < path.size()-1; i++) {
            Node currentNode = path.get(i);
            Node nextNode = path.get(i+1);
            HashMap<Node, Integer> corridorWeightToReachNextNode = currentNode.getCorridorWeightToReachNextNode();
            if(corridorWeightToReachNextNode.get(nextNode)<smallestCorridorSizeInPath) {
                smallestCorridorSizeInPath = corridorWeightToReachNextNode.get(nextNode);
            }
        }
        //System.out.println("shortest corridor size in the path:" + smallestCorridorSizeInPath);
        return smallestCorridorSizeInPath;
    }

    /**
     * reduce corridor size of each in path by smallestCorridorSizeInPath
     * Removes the corresponding path with that smallest size from the graph
     * by removing respective node with smallestCorridorSizeInPath from  corridorWeightToReachNextNode
     * Also, makes node.discard = true if node's nextNode list is empty
     */
    public static void reduceCorridorSizeInPath(ArrayList<Node> path, int smallestCorridorSizeInPath, int[] exits) {
        if(path == null || exits == null){
            return;
        }
        if(path.size()<2 && exits.length==0)
            return;
        for (int i = 0; i < path.size()-1 ; i++) {
            Node currentNode = path.get(i);
            Node nextNode = path.get(i+1);
            if(currentNode==null || nextNode==null){
                return;
            }
            HashMap<Node, Integer> corridorWeightToReachNextNode = currentNode.getCorridorWeightToReachNextNode();
            if(corridorWeightToReachNextNode==null || corridorWeightToReachNextNode.size()==0) {
                return;
            }
            if(corridorWeightToReachNextNode.get(nextNode)==null) {
                return;
            }
            int currentCorridorSize = 0;
            currentCorridorSize = corridorWeightToReachNextNode.get(nextNode);
            if(currentCorridorSize==0 || currentCorridorSize == SOME_BIG_VALUE){
                return;
            }

            corridorWeightToReachNextNode.put(nextNode, (currentCorridorSize-smallestCorridorSizeInPath));
            if(currentCorridorSize == smallestCorridorSizeInPath) {
                corridorWeightToReachNextNode.remove(nextNode);
                if(corridorWeightToReachNextNode.size()==0 && !isNodeOneOfExits(currentNode,exits)) {
                    currentNode.discard = true;
                    //System.out.println("discarded node:"+ currentNode.toString());
                }
            }
        }
    }

    public static boolean isNodeOneOfExits(Node node, int[] exits) {
        for (int i = 0; i < exits.length; i++) {
            if(node.getIndex() == exits[i])
                return true;
        }
        return false;
    }}

    class Node {
    int index;
    HashMap<Node, Integer> corridorWeightToReachNextNode = null;
    Boolean discard = false;
    public Node(int index) {
        this.index = index;
        corridorWeightToReachNextNode = new HashMap<>();
    }
    public int getIndex() {
        return index;
    }

    public HashMap<Node, Integer> getCorridorWeightToReachNextNode() {
        return corridorWeightToReachNextNode;
    }

    public static Node constructGraph(int[][] matrix, List<Node> nodes) {
        for(int i = 0; i < matrix.length; i++) {
            Node currentNode = nodes.get(i);
            for(int j=0; j<matrix[i].length; j++) {
                if(matrix[i][j] != 0) {
                    Node nextNode = nodes.get(j);
                    currentNode.corridorWeightToReachNextNode.put(nextNode,matrix[i][j]);
                }
            }
        }
        return nodes.get(0);
    }

    @Override
    public boolean equals(Object obj) {
        Node node = (Node)obj;
        if(node.index == this.index)
            return true;
        return false;
    }
    @Override
    public int hashCode() {
        return index % 2;
    }

    @Override
    public String toString() {
        return Integer.toString(this.index);
    }

    public static boolean isNodeInPath(Node n, ArrayList<Node> path) {
        if(path == null || n == null) {
            return false;
        }
        boolean alreadyInPath = false;
        for( Node nodeInPath : path) {
            if(nodeInPath.equals(n))
                return true;
        }
        return false;
    }
}
</code>```

答:
Your problem: The path you construct contains nodes with no exit.

Following example (found by random sampling):

```<code>entrances = {0};
exits = {3};
path = {{0, 17, 6, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 9},
        {16, 0, 0, 0}};
</code>```

Visualization (created with graphonline.ru)

Your code starts at the (only) entry-node. It adds all childs to the path in encounter order. Then it explores each child and adds their childs to the path. In the end, before evaluation, this gives the path 0->1->2->3 which is clearly wrong. The only true path is 0->2->3 as indicated in the graphic.

During evaluation of the path you query Node 1s adjacency vector for Node 2. This is where your NullPointerException happens.

The code I used to generate random samples (generates 1000 samples with reproducible results and one entry/exit node)

```<code>// My random samples
Random random = new Random(0L);

int pathSize = 4;

for (int i = 0; i < 1000; i++) {
    entrances = new int[]{0};
    //Arrays.setAll(entrances, j -> random.nextInt(0+1));

    exits = new int[]{pathSize - 1};
    //Arrays.setAll(exits, j -> random.nextInt(pathSize));

    path = new int[pathSize][pathSize];
    Arrays.setAll(path, j -> IntStream.generate(() -> random.nextInt(20)).limit(pathSize).toArray());

    for (int j = 0; j < path.length; j++) {
        path[j][j] = 0;
    }

    for (int j = 0; j < path.length; j++) {
        for (int k = 0; k < path[j].length; k++) {
            path[j][k] = random.nextDouble() < 0.75 ? 0 : path[j][k];
        }
    }

    try {
        answer(entrances, exits, path);
    } catch (Exception e) {
        System.err.println("[" + String.format("%02d", i) + "] Threw an exception for inputs " + Arrays.toString(entrances) + ", " + Arrays.toString(exits) + ", " + Arrays.deepToString(path));
        e.printStackTrace();
    }
}
</code>```

Now, some random code-review:

```<code>//below makes difference with one test case
for (int i = 0; i < path.length; i++) {
    for (int j = 0; j < path[i].length; j++) {
        if (i == j)
            path[i][j] = 0;
    }
}
</code>```

From what I can see, path is always a square-array. If that holds true, you can remove the inner loop.

You have SOME_BIG_VALUE. Why not use Integer.MAX_VALUE? You can't get any bigger than that.

Body:
I just failed the google coding challenge level-4 conducted in foobar site. My code works most of the time but throws null pointer exception for specific set of inputs which I am not aware of. If any one is interested in solving puzzle coding question, could you please help me find the input for which below solution ends in null pointer exception? I also welcome comments on my code when it fails good coding etiquette or entire alternate simple and more efficient solution. Thank. (PS- Hope I am not violating any rules and stuff sharing the below question asked in google coding challenge)

Problem statement-
Given the starting room numbers of the groups of bunnies, the room numbers of the escape pods, and how many bunnies can fit through at a time in each direction of every corridor in between, figure out how many bunnies can safely make it to the escape pods at a time at peak.
Write a function answer(entrances, exits, path) that takes an array of integers denoting where the groups of gathered bunnies are, an array of integers denoting where the escape pods are located, and an array of an array of integers of the corridors, returning the total number of bunnies that can get through at each time step as an int. The entrances and exits are disjoint and thus will never overlap. The path element path[A][B] = C describes that the corridor going from A to B can fit C bunnies at each time step.  There are at most 50 rooms connected by the corridors and at most 2000000 bunnies that will fit at a time.

For example, if you have:

entrances = [0, 1],
exits = [4, 5],
path = [,
# Room 0: Bunnies,           [0, 0, 4, 6, 0, 0],
# Room 1: Bunnies,           [0, 0, 5, 2, 0, 0],
# Room 2: Intermediate room, [0, 0, 0, 0, 4, 4],
# Room 3: Intermediate room  [0, 0, 0, 0, 6, 6],
# Room 4: Escape pods,       [0, 0, 0, 0, 0, 0],
# Room 5: Escape pods        [0, 0, 0, 0, 0, 0]
]

Then in each time step, the following might happen:

0 sends 4/4 bunnies to 2 and 6/6 bunnies to 3
1 sends 4/5 bunnies to 2 and 2/2 bunnies to 3
2 sends 4/4 bunnies to 4 and 4/4 bunnies to 5
3 sends 4/6 bunnies to 4 and 4/6 bunnies to 5

So, in total, 16 bunnies could make it to the escape pods at 4 and 5 at each time step.  (Note that in this example, room 3 could have sent any variation of 8 bunnies to 4 and 5, such as 2/6 and 6/6, but the final answer remains the same.)

Test cases

Inputs:entrances = [0], exits = [3], path = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] then Output:6

Inputs:entrances = [0, 1], exits = [4, 5], path = [[0, 0, 4, 6, 0, 0], [0, 0, 5, 2, 0, 0], [0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 6, 6], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]  Output: 16

My solution:

public class Answer {
    public static void main(String[] args) {
        //input 1
        int[] entrances = {0, 1};
        int[] exits = {4, 5};
        int[][] path = {{1, 0, 4, 6, 0, 0},
                {0, 1, 5, 2, 0, 0},
                {0, 0, 1, 0, 4, 4},
                {0, 0, 0, 1, 6, 6},
                {0, 0, 0, 0, 1, 0},
                {0, 0, 0, 0, 0, 1}};
        System.out.println("*****************************************for input 1:"+answer(entrances, exits, path));
        //input 2
        entrances = new int[]{0};
        exits = new int[]{3};
        path = new int[][]{ {0, 7, 0, 0},
                {0, 0, 6, 0},
                {0, 0, 0, 8},
                {9, 0, 0, 0} };
        System.out.println("*****************************************for input 2:"+answer(entrances, exits, path));
        //input with loop 1
        entrances = new int[]{0,2};
        exits = new int[]{4};
        path = new int[][]{ {0, 3, 0, 0, 0},
                {0, 0, 2, 0, 5},
                {0, 0, 0, 4, 0},
                {0, 6, 0, 0, 0},
                {0, 0, 0, 0, 0} };
        System.out.println("*****************************************for input 3:"+answer(entrances, exits, path));
        //input with loop 2
        entrances = new int[]{0,1};
        exits = new int[]{4,5};
        path = new int[][]{ {0, 0, 10, 0, 0, 0},
                            {0, 0, 0, 8, 0, 0},
                            {0, 0, 0, 4, 6, 0},
                            {0, 0, 4, 0, 0, 12},
                            {0, 0, 0, 0, 0, 0},
                            {0, 0, 0, 0, 0, 0}};
        System.out.println("*****************************************for input 4:"+answer(entrances, exits, path));

        entrances = new int[]{0};
        exits = new int[]{0};
        path = new int[][]{ {0} };
        System.out.println("*****************************************for input 5:"+answer(entrances, exits, path));
    }

    public static final int SOME_BIG_VALUE = 2146999999;

    public static int answer(int[] entrances, int[] exits, int[][] path) {
        if (path == null || entrances == null || exits == null){
            return 0;
        }
        if(path.length<2 || entrances.length<1 || exits.length<1){
            return 0;
        }
        //below makes difference with one test case
        for (int i = 0; i < path.length; i++) {
            for (int j = 0; j <path[i].length ; j++) {
                if(i==j)
                    path[i][j]=0;
            }
        }
        //creating all nodes
        ArrayList<Node> nodes = new ArrayList<>();
        for (int i = 0; i < path.length; i++) {
            nodes.add(new Node(i));
        }
        Node.constructGraph(path, nodes);

        int total = 0;
        for(int src:entrances) {
            //System.out.println("for src: "+ src);
            Node start = nodes.get(src);
            int pathCapacity = 0;
            do {
                if(start.discard)
                    break;
                pathCapacity = findCapacityOfLoopLessPath(src, exits, nodes);
                total = total + pathCapacity;
            } while (pathCapacity != 0);
        }
        return total;
    }

    /**
     *Returns >0 if valid path is found between src and one of the exits
     * Returns  0 if valid path is not found between src and any of exits
     * Apart, below function   *overcomes the loop while finding the path
     *alters graph as new paths are  discovered
     *removes dead-end path frm src to non-exit
     */
    public static int findCapacityOfLoopLessPath(int src, int[] exits, ArrayList<Node> nodes) {
        ArrayList<Node> path = new ArrayList<>();
        Stack<Node> stack = new Stack<>();
        Node start = nodes.get(src);
        stack.push(start);

        boolean reachedExit = modifiedDFS(path, stack, exits);
        int smallestCorridorSizeInPath = 0;
        if(!reachedExit){
            return smallestCorridorSizeInPath;
        }
        else{
            smallestCorridorSizeInPath = findSmallestCorridorSizeInPath(path);
            if(smallestCorridorSizeInPath != SOME_BIG_VALUE) {
                reduceCorridorSizeInPath(path, smallestCorridorSizeInPath, exits);
                return smallestCorridorSizeInPath;
            }
        }
        return smallestCorridorSizeInPath;
    }

    /**
     * Does dfs until one of the exit is reached
     * Parallelly putting nodes into path as they get discovered to reach the one of exits
     */
    private static boolean modifiedDFS(ArrayList<Node> path, Stack<Node> stack, int[] exits) {
        while(!stack.empty()) {
            Node current = stack.pop();
            if(Node.isNodeInPath(current, path)) {
                return modifiedDFS(path,stack,exits);
            }else {
                path.add(current);
            }
            if(isNodeOneOfExits(current,exits)) {
                return true;
            }
            HashMap<Node, Integer> corridorWeightToReachNextNode = current.getCorridorWeightToReachNextNode();
            for(Node node:corridorWeightToReachNextNode.keySet()) {
                if(!stack.contains(node) && !node.discard)
                    stack.push(node);
            }
        }
        return false;
    }

    public static int findSmallestCorridorSizeInPath(ArrayList<Node> path) {
        if(path.size() < 2){
            return 0;//may be if exception is thrown then we can debug more easily
        }
        int smallestCorridorSizeInPath = SOME_BIG_VALUE;

        //System.out.print("path : ");
        for (int j = 0; j <path.size() ; j++) {
            //System.out.print(path.get(j).toString()+", ");
        }

        int i;
        for (i = 0; i < path.size()-1; i++) {
            Node currentNode = path.get(i);
            Node nextNode = path.get(i+1);
            HashMap<Node, Integer> corridorWeightToReachNextNode = currentNode.getCorridorWeightToReachNextNode();
            if(corridorWeightToReachNextNode.get(nextNode)<smallestCorridorSizeInPath) {
                smallestCorridorSizeInPath = corridorWeightToReachNextNode.get(nextNode);
            }
        }
        //System.out.println("shortest corridor size in the path:" + smallestCorridorSizeInPath);
        return smallestCorridorSizeInPath;
    }

    /**
     * reduce corridor size of each in path by smallestCorridorSizeInPath
     * Removes the corresponding path with that smallest size from the graph
     * by removing respective node with smallestCorridorSizeInPath from  corridorWeightToReachNextNode
     * Also, makes node.discard = true if node's nextNode list is empty
     */
    public static void reduceCorridorSizeInPath(ArrayList<Node> path, int smallestCorridorSizeInPath, int[] exits) {
        if(path == null || exits == null){
            return;
        }
        if(path.size()<2 && exits.length==0)
            return;
        for (int i = 0; i < path.size()-1 ; i++) {
            Node currentNode = path.get(i);
            Node nextNode = path.get(i+1);
            if(currentNode==null || nextNode==null){
                return;
            }
            HashMap<Node, Integer> corridorWeightToReachNextNode = currentNode.getCorridorWeightToReachNextNode();
            if(corridorWeightToReachNextNode==null || corridorWeightToReachNextNode.size()==0) {
                return;
            }
            if(corridorWeightToReachNextNode.get(nextNode)==null) {
                return;
            }
            int currentCorridorSize = 0;
            currentCorridorSize = corridorWeightToReachNextNode.get(nextNode);
            if(currentCorridorSize==0 || currentCorridorSize == SOME_BIG_VALUE){
                return;
            }

            corridorWeightToReachNextNode.put(nextNode, (currentCorridorSize-smallestCorridorSizeInPath));
            if(currentCorridorSize == smallestCorridorSizeInPath) {
                corridorWeightToReachNextNode.remove(nextNode);
                if(corridorWeightToReachNextNode.size()==0 && !isNodeOneOfExits(currentNode,exits)) {
                    currentNode.discard = true;
                    //System.out.println("discarded node:"+ currentNode.toString());
                }
            }
        }
    }

    public static boolean isNodeOneOfExits(Node node, int[] exits) {
        for (int i = 0; i < exits.length; i++) {
            if(node.getIndex() == exits[i])
                return true;
        }
        return false;
    }}

    class Node {
    int index;
    HashMap<Node, Integer> corridorWeightToReachNextNode = null;
    Boolean discard = false;
    public Node(int index) {
        this.index = index;
        corridorWeightToReachNextNode = new HashMap<>();
    }
    public int getIndex() {
        return index;
    }

    public HashMap<Node, Integer> getCorridorWeightToReachNextNode() {
        return corridorWeightToReachNextNode;
    }

    public static Node constructGraph(int[][] matrix, List<Node> nodes) {
        for(int i = 0; i < matrix.length; i++) {
            Node currentNode = nodes.get(i);
            for(int j=0; j<matrix[i].length; j++) {
                if(matrix[i][j] != 0) {
                    Node nextNode = nodes.get(j);
                    currentNode.corridorWeightToReachNextNode.put(nextNode,matrix[i][j]);
                }
            }
        }
        return nodes.get(0);
    }

    @Override
    public boolean equals(Object obj) {
        Node node = (Node)obj;
        if(node.index == this.index)
            return true;
        return false;
    }
    @Override
    public int hashCode() {
        return index % 2;
    }

    @Override
    public String toString() {
        return Integer.toString(this.index);
    }

    public static boolean isNodeInPath(Node n, ArrayList<Node> path) {
        if(path == null || n == null) {
            return false;
        }
        boolean alreadyInPath = false;
        for( Node nodeInPath : path) {
            if(nodeInPath.equals(n))
                return true;
        }
        return false;
    }
}

Body:
Your problem: The path you construct contains nodes with no exit.

Following example (found by random sampling):

entrances = {0};
exits = {3};
path = {{0, 17, 6, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 9},
        {16, 0, 0, 0}};

Visualization (created with graphonline.ru)

Your code starts at the (only) entry-node. It adds all childs to the path in encounter order. Then it explores each child and adds their childs to the path. In the end, before evaluation, this gives the path 0->1->2->3 which is clearly wrong. The only true path is 0->2->3 as indicated in the graphic.

During evaluation of the path you query Node 1s adjacency vector for Node 2. This is where your NullPointerException happens.

The code I used to generate random samples (generates 1000 samples with reproducible results and one entry/exit node)

// My random samples
Random random = new Random(0L);

int pathSize = 4;

for (int i = 0; i < 1000; i++) {
    entrances = new int[]{0};
    //Arrays.setAll(entrances, j -> random.nextInt(0+1));

    exits = new int[]{pathSize - 1};
    //Arrays.setAll(exits, j -> random.nextInt(pathSize));

    path = new int[pathSize][pathSize];
    Arrays.setAll(path, j -> IntStream.generate(() -> random.nextInt(20)).limit(pathSize).toArray());

    for (int j = 0; j < path.length; j++) {
        path[j][j] = 0;
    }

    for (int j = 0; j < path.length; j++) {
        for (int k = 0; k < path[j].length; k++) {
            path[j][k] = random.nextDouble() < 0.75 ? 0 : path[j][k];
        }
    }

    try {
        answer(entrances, exits, path);
    } catch (Exception e) {
        System.err.println("[" + String.format("%02d", i) + "] Threw an exception for inputs " + Arrays.toString(entrances) + ", " + Arrays.toString(exits) + ", " + Arrays.deepToString(path));
        e.printStackTrace();
    }
}

Now, some random code-review:

//below makes difference with one test case
for (int i = 0; i < path.length; i++) {
    for (int j = 0; j < path[i].length; j++) {
        if (i == j)
            path[i][j] = 0;
    }
}

From what I can see, path is always a square-array. If that holds true, you can remove the inner loop.

You have SOME_BIG_VALUE. Why not use Integer.MAX_VALUE? You can't get any bigger than that.


来源: stackexchange

问:
WSO2 api manager error 404 - File or directory not found
When I try to execute my api through API Console in WSO2 api manager , I received error "404 - File or directory not found".

My API is working fine when I run it through the Postmen tool.
Could you please help me to identify above issue.
Here with attached some screenshots.

答:
You need to copy the gateway URL in the API console and access it from the browser. Then go to advanced add exception.

This will add the server certificate to the browser trust store and console will work afterward.

ContentLicense: CC BY-SA 3.0


问:
Why we need to pass "$event" in ng-click?
I know we can perform click events like ng-click="clickMe()" in angular.But I just gone through some examples.In that $event is passed into that like this ng-click="clickMe()" .
Why we need to pass $event?
What is the difference between ng-click="clickMe()" and ng-click="clickMe($event)" ?
Please anyone explain.

答:
What I've found in angular docs

$event

Directives like ngClick and ngFocus expose a $event object
  within the scope of that expression. The object is an instance of a
  jQuery Event Object when jQuery is present or a similar jqLite object.

with this object you have various properties and functions that can help you to manage event handling.

for example:

```<code>event.stopPropagation()
</code>```

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Body:
What I've found in angular docs

$event

Directives like ngClick and ngFocus expose a $event object
  within the scope of that expression. The object is an instance of a
  jQuery Event Object when jQuery is present or a similar jqLite object.

with this object you have various properties and functions that can help you to manage event handling.

for example:

event.stopPropagation()

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.


问:
solr 6.5 with nutch 1.12
Successfully connected nutch 1.12 with solr 6.5 and crawled the un-authenticated sites. While attempting to crawl authenticated sites, I cant proceed with it. Can anyone please help to overcome it.

error:

```<code>java.lang.RuntimeException: java.lang.IllegalArgumentException: No form exists: user-login
    at org.apache.nutch.protocol.httpclient.Http.resolveCredentials(Http.java:485)
    at org.apache.nutch.protocol.httpclient.Http.getResponse(Http.java:180)
    at org.apache.nutch.protocol.http.api.HttpBase.getProtocolOutput(HttpBase.java:261)
    at org.apache.nutch.fetcher.FetcherThread.run(FetcherThread.java:295)
Caused by: java.lang.IllegalArgumentException: No form exists: user-login
    at org.apache.nutch.protocol.httpclient.HttpFormAuthentication.getLoginFormParams(HttpFormAuthentication.java:183)
    at org.apache.nutch.protocol.httpclient.HttpFormAuthentication.login(HttpFormAuthentication.java:95)
    at org.apache.nutch.protocol.httpclient.Http.resolveCredentials(Http.java:483)
</code>```

httpclient-auth.xml:

```<code> <auth-configuration>
    <credentials authMethod="formAuth"
            loginUrl="<url>"
            loginFormId="user-login"
            loginRedirect="true">
    <loginPostData>
      <field name="name"
          value="*<name>*"/>
      <field name="pass"
          value="*<password>*"/>
      <field name="op"
          value="Log in"/>
    </loginPostData>
   </credentials>
</auth-configuration>
</code>```

searched few links but couldn't solved.

Thanks.

答:
How do you identify the form that needs to be submitted? In the httpclient-auth.xml file you put the following:

```<code>loginFormId="user-login"
</code>```

So the plugin it's trying to find the login form by id, meaning that the form must have the user-login id, change this value to the proper id of the form login in the webpage that you're trying to crawl.

Title: solr 6.5 with nutch 1.12

Body:
Successfully connected nutch 1.12 with solr 6.5 and crawled the un-authenticated sites. While attempting to crawl authenticated sites, I cant proceed with it. Can anyone please help to overcome it.

error:

java.lang.RuntimeException: java.lang.IllegalArgumentException: No form exists: user-login
    at org.apache.nutch.protocol.httpclient.Http.resolveCredentials(Http.java:485)
    at org.apache.nutch.protocol.httpclient.Http.getResponse(Http.java:180)
    at org.apache.nutch.protocol.http.api.HttpBase.getProtocolOutput(HttpBase.java:261)
    at org.apache.nutch.fetcher.FetcherThread.run(FetcherThread.java:295)
Caused by: java.lang.IllegalArgumentException: No form exists: user-login
    at org.apache.nutch.protocol.httpclient.HttpFormAuthentication.getLoginFormParams(HttpFormAuthentication.java:183)
    at org.apache.nutch.protocol.httpclient.HttpFormAuthentication.login(HttpFormAuthentication.java:95)
    at org.apache.nutch.protocol.httpclient.Http.resolveCredentials(Http.java:483)

httpclient-auth.xml:

 <auth-configuration>
    <credentials authMethod="formAuth"
            loginUrl="<url>"
            loginFormId="user-login"
            loginRedirect="true">
    <loginPostData>
      <field name="name"
          value="*<name>*"/>
      <field name="pass"
          value="*<password>*"/>
      <field name="op"
          value="Log in"/>
    </loginPostData>
   </credentials>
</auth-configuration>

searched few links but couldn't solved.

Thanks.

Body:
How do you identify the form that needs to be submitted? In the httpclient-auth.xml file you put the following:

loginFormId="user-login"

So the plugin it's trying to find the login form by id, meaning that the form must have the user-login id, change this value to the proper id of the form login in the webpage that you're trying to crawl.


问:
shape intrinsic function in fortran
I am playing around with the shape() intrinsic function in fortran:

```<code>program test

    integer, dimension(5,3) :: A
    integer, dimension(2) :: ShapeA

    ShapeA = shape(A)
    print *, ShapeA(1)
    print *, ShapeA(2)
end program test
</code>```

I understand the shape function returns a 2 element vector containing the length and width of array A. In the above code, the output of shape(A) is passed to the predefined variable ShapeA. Then the contents of ShapeA are printed out, namely 5 and 3.

I would like to find a way to refer to the contents of the output of shape(A) without having to assign it to an intermediate variable ShapeA.

This would be similar to the matlab size function which enables looping constructs like this:

```<code>A =  [1 2 3 5 4; 2 3 5 4 5]

for i = 1:size(A,2)
    A(2,i)
end
</code>```

Which means the user need not assign another variable like so:

```<code>A =  [1 2 3 5 4; 2 3 5 4 5]
sizeA = size(A,2)

for i = 1:sizeA
    A(2,i)
end
</code>```

In fortran it is necessary to both declare the variable, assign it a value using size statement then include that variable in the loop. I would like to remove the first two steps and see if it can be done like in matlab. Any ideas? Thanks.

答:
From the fortran manual page for shape there is a link to SIZE, specifically (emphasis mine)

Description:

Determine the extent of ARRAY along a specified dimension DIM, or the total number of elements in ARRAY if DIM is absent.

```<code>program test

    integer, dimension(5,3) :: A

    print *, size(A,1)
    print *, size(A,2)
end program test
</code>```

Title: shape intrinsic function in fortran

Body:
I am playing around with the shape() intrinsic function in fortran:

program test

    integer, dimension(5,3) :: A
    integer, dimension(2) :: ShapeA

    ShapeA = shape(A)
    print *, ShapeA(1)
    print *, ShapeA(2)
end program test

I understand the shape function returns a 2 element vector containing the length and width of array A. In the above code, the output of shape(A) is passed to the predefined variable ShapeA. Then the contents of ShapeA are printed out, namely 5 and 3.

I would like to find a way to refer to the contents of the output of shape(A) without having to assign it to an intermediate variable ShapeA.

This would be similar to the matlab size function which enables looping constructs like this:

A =  [1 2 3 5 4; 2 3 5 4 5]

for i = 1:size(A,2)
    A(2,i)
end

Which means the user need not assign another variable like so:

A =  [1 2 3 5 4; 2 3 5 4 5]
sizeA = size(A,2)

for i = 1:sizeA
    A(2,i)
end

In fortran it is necessary to both declare the variable, assign it a value using size statement then include that variable in the loop. I would like to remove the first two steps and see if it can be done like in matlab. Any ideas? Thanks.

Body:
From the fortran manual page for shape there is a link to SIZE, specifically (emphasis mine)

Description:

Determine the extent of ARRAY along a specified dimension DIM, or the total number of elements in ARRAY if DIM is absent.

program test

    integer, dimension(5,3) :: A

    print *, size(A,1)
    print *, size(A,2)
end program test


问:
Installing data science packages to vanilla python
How to download necessary python packages for data analysis (e.g. pandas,scipy,numpy etc) and machine learning packages (sci-kit learn for starter, tensorflow for deeplearning if possible etc) without using github or anaconda?

Our client has permitted us to install python 3.6 and above (32-bit) in our terminals for data analysis and machine learning projects but we cannot access github due to security restrictions and also cannot download anaconda bundle.

Please provide suitable weblinks and instructions.

答:
as suggested by @DavidG, the following solution worked:

Download the whl file
use cmd window and go to the download folder and then install like below:
``` <code>
C:\Users\XXXXXXXX>cd C:\Users\XXXXXXXX\Documents\Python Packages
C:\Users\XXXXXXXX\Documents\Python Packages>pip install numpy-1.13.0+mkl-cp36-cp36m-win32.whl
Processing c:\users\XXXXXXXX\documents\python packages\numpy-1.13.0+mkl-cp36-cp
36m-win32.whl
Installing collected packages: numpy
  Found existing installation: numpy 1.13.0
    Uninstalling numpy-1.13.0:
      Successfully uninstalled numpy-1.13.0
Successfully installed numpy-1.13.0+mkl</p>

<p>C:\Users\XXXXXXXX\Documents\Python Packages>pip install scipy-0.19.1-cp36-cp36m
-win32.whl
Processing c:\users\XXXXXXXX\documents\python packages\scipy-0.19.1-cp36-cp36m-
win32.whl
Requirement already satisfied: numpy>=1.8.2 in c:\users\XXXXXXXX\appdata\local\
programs\python\python36-32\lib\site-packages (from scipy==0.19.1)
Installing collected packages: scipy
Successfully installed scipy-0.19.1</p>

<p>C:\Users\XXXXXXXX\Documents\Python Packages>
```

Body:
as suggested by @DavidG, the following solution worked:

Download the whl file
use cmd window and go to the download folder and then install like below:

C:\Users\XXXXXXXX>cd C:\Users\XXXXXXXX\Documents\Python Packages
C:\Users\XXXXXXXX\Documents\Python Packages>pip install numpy-1.13.0+mkl-cp36-cp36m-win32.whl
Processing c:\users\XXXXXXXX\documents\python packages\numpy-1.13.0+mkl-cp36-cp
36m-win32.whl
Installing collected packages: numpy
  Found existing installation: numpy 1.13.0
    Uninstalling numpy-1.13.0:
      Successfully uninstalled numpy-1.13.0
Successfully installed numpy-1.13.0+mkl

C:\Users\XXXXXXXX\Documents\Python Packages>pip install scipy-0.19.1-cp36-cp36m
-win32.whl
Processing c:\users\XXXXXXXX\documents\python packages\scipy-0.19.1-cp36-cp36m-
win32.whl
Requirement already satisfied: numpy>=1.8.2 in c:\users\XXXXXXXX\appdata\local\
programs\python\python36-32\lib\site-packages (from scipy==0.19.1)
Installing collected packages: scipy
Successfully installed scipy-0.19.1

C:\Users\XXXXXXXX\Documents\Python Packages>


问:
Java Swing close ONLY one application
Hi all:
I have a Java Swing App. There is a button allow user to create open up a new window of the application. I use System.Exit(0) when user decides to close the application, however when I press "Close" button, both Application windows closed.

```<code>public static void main(String[] args)
{
 ghMain = new GreenHouseMain();
}
</code>```

Above is how I initialize the first application, then use the same code to create new GreenHouseMain Object to open second application window.

So my question is how do I close only one application window which the close button I pressed from?

Thanks all

答: I assume that both windows are JFrames.  If so, it is better to have the second window be a JDialog, modal or non-modal depending on your requirements.  If you need both windows open and want to be able to let the user select which to close, then perhaps both need to be dialogs, though I'm not 100% sure based on the information you've presented. If these suggestions don't solve your problem, then please provide us with more details on your exact requirements.</p>

ContentLicense: CC BY-SA 2.5

Title: Java Swing close ONLY one application

Body:
Hi all:
I have a Java Swing App. There is a button allow user to create open up a new window of the application. I use System.Exit(0) when user decides to close the application, however when I press "Close" button, both Application windows closed.

public static void main(String[] args)
{
 ghMain = new GreenHouseMain();
}

Above is how I initialize the first application, then use the same code to create new GreenHouseMain Object to open second application window.

So my question is how do I close only one application window which the close button I pressed from?

Thanks all


问:
node-sass-middleware is not doing anything
I'm trying to use node-sass-middleware but it is not creating a .css of my .scss file.

My file structure (simplified) is

```<code>- node-modules
- public
     |- common
     |     |-sass
     |     |     |-style.scss
     |     |-css
- server.js
</code>```

and the code in server.js has

```<code>var cssLoc =  __dirname + "\\public\\common\\css";
var cssDest =  __dirname + "\\public\\common";
console.log(cssLoc);
console.log(cssDest);
app.use(sass({
    src: cssLoc,
    dest: cssDest,
    debug: true,
    outputStyle: 'compressed'
}));

app.use(express.static(__dirname + '/public'));
</code>```

I have no idea why this isn't working. It is very frustrating.

答:
Using the original example with the following directory structure:

```<code>- node-modules
- public
     |- common
     |     |-sass
     |     |     |-style.scss
     |     |-css
- server.js
</code>```

In server.js where you are calling the node-sass-middleware it looks like you have the src and dest properties set incorrectly. For example,

```<code>var cssLoc =  __dirname + "\\public\\common\\css";
</code>```

which is being used to populate the src property should be the path to your *.scss file but instead is pointing to your CSS destination directory. Similarly, the dest property,

```<code>var cssDest =  __dirname + "\\public\\common";
</code>```

is not pointing to the CSS directory but its parent.

In the sass-node-middleware block you have debug: true set so you should be able to view the paths used in your console from where your launched the application to verify whether they are correct or not:

```<code>app.use(sass({
    src: cssLoc,
    dest: cssDest,
    debug: true,
    outputStyle: 'compressed'
}));
</code>```

This could be refactored to:

```<code>app.use(sass({
    src: path.join(__dirname, 'public', 'common', 'sass'),
    dest: path.join(__dirname, 'public', 'common', 'css'),
    debug: true,
    outputStyle: 'compressed'
}));
</code>```

That should get your SASS compiled into CSS but as the previous answer by SirRodge mentioned you still have your path to resolve for the the get request of the CSS. If you are using the express.static built-in middleware, app.use(express.static(path.join(__dirname, 'public'))); to serve files from a directory named public and in your HTML you are referencing the CSS by say /common/css/style.css then you need to add the prefix property to the middleware:

```<code>app.use(sass({
    src: path.join(__dirname, 'public', 'common', 'sass'),
    dest: path.join(__dirname, 'public', 'common', 'css'),
    debug: true,
    outputStyle: 'compressed',
    prefix: '/common/css'
}));
</code>```

Body:
I'm trying to use node-sass-middleware but it is not creating a .css of my .scss file.

My file structure (simplified) is

- node-modules
- public
     |- common
     |     |-sass
     |     |     |-style.scss
     |     |-css
- server.js

and the code in server.js has

var cssLoc =  __dirname + "\\public\\common\\css";
var cssDest =  __dirname + "\\public\\common";
console.log(cssLoc);
console.log(cssDest);
app.use(sass({
    src: cssLoc,
    dest: cssDest,
    debug: true,
    outputStyle: 'compressed'
}));

app.use(express.static(__dirname + '/public'));

I have no idea why this isn't working. It is very frustrating.

Body:
Using the original example with the following directory structure:

- node-modules
- public
     |- common
     |     |-sass
     |     |     |-style.scss
     |     |-css
- server.js

In server.js where you are calling the node-sass-middleware it looks like you have the src and dest properties set incorrectly. For example,

var cssLoc =  __dirname + "\\public\\common\\css";

which is being used to populate the src property should be the path to your *.scss file but instead is pointing to your CSS destination directory. Similarly, the dest property,

var cssDest =  __dirname + "\\public\\common";

is not pointing to the CSS directory but its parent.

In the sass-node-middleware block you have debug: true set so you should be able to view the paths used in your console from where your launched the application to verify whether they are correct or not:

app.use(sass({
    src: cssLoc,
    dest: cssDest,
    debug: true,
    outputStyle: 'compressed'
}));

This could be refactored to:

app.use(sass({
    src: path.join(__dirname, 'public', 'common', 'sass'),
    dest: path.join(__dirname, 'public', 'common', 'css'),
    debug: true,
    outputStyle: 'compressed'
}));

That should get your SASS compiled into CSS but as the previous answer by SirRodge mentioned you still have your path to resolve for the the get request of the CSS. If you are using the express.static built-in middleware, app.use(express.static(path.join(__dirname, 'public'))); to serve files from a directory named public and in your HTML you are referencing the CSS by say /common/css/style.css then you need to add the prefix property to the middleware:

app.use(sass({
    src: path.join(__dirname, 'public', 'common', 'sass'),
    dest: path.join(__dirname, 'public', 'common', 'css'),
    debug: true,
    outputStyle: 'compressed',
    prefix: '/common/css'
}));


问:
define/create map from constructor
You can create an Object like this

```<code>var o = {
  9 : 'dh',
  test : 'wee'
};
</code>```

How to create a map? (I want to keep the key order)

```<code>var m = new Map({
  9 : 'dh',
  test : 'wee'
});
</code>```

答:
The constructor takes an iterable of key-value pairs, expressed two-element arrays:

```<code>var myMap = new Map([['key1', 'value1'], ['key2', 'value2']]);
</code>```

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Relation_with_Array_objects

Title: define/create map from constructor

Body:
You can create an Object like this

var o = {
  9 : 'dh',
  test : 'wee'
};

How to create a map? (I want to keep the key order)

var m = new Map({
  9 : 'dh',
  test : 'wee'
});

Body:
The constructor takes an iterable of key-value pairs, expressed two-element arrays:

var myMap = new Map([['key1', 'value1'], ['key2', 'value2']]);

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Relation_with_Array_objects


问:
Github issues integration with android studio
I already have Github set up in Android studio.

I can commit, push and everything else.

What I can't figure out is how do create and manage Github issues with Android studio?

答:
That's pretty easy to do.

Integrate Github (not git) server

Tools -> Tasks & Contexts -> Configure Servers

Add a github server (not gitlab) an set your repo stuff there

Work on issues

Once done, you can create, work on, close issues

Tools -> Tasks & Contexts -> Switch task (or Alt+Shift+T on windows)

You can open, mark as resolved, create branch for the issue.
If you want it closed you can include closes #123 in your commit message which will close it (this doesn't have to be from within android studio, github recognizes it as a command).


问:
how to call function inside a function with setTimeout
I am trying to call a function with setTimeout() inside another function and I keep getting this error:

hi is not defined

This is the code.

```<code>hello("hi");
function hello(a)
{
    hi(a);
    function hi(b)
    {
        console.log(b);
        c = setTimeout('hi("' + b + '")', 50)
    }
}
</code>```

One "hi" is being logged, but then it just stops. I believe problem is in this part: c = setTimeout('hi("' + b + '")', 50)

Is there a fix without changing function inside function structure?

答:
You can pass arguments to function as third argument to setTimeout.

hello("hi");
function hello(a)
{
    hi(a);
    function hi(b)
    {
        console.log(b);
        c = setTimeout(hi, 50,b)
    }
}```

Body:
I am trying to call a function with setTimeout() inside another function and I keep getting this error:

hi is not defined

This is the code.

hello("hi");
function hello(a)
{
    hi(a);
    function hi(b)
    {
        console.log(b);
        c = setTimeout('hi("' + b + '")', 50)
    }
}

One "hi" is being logged, but then it just stops. I believe problem is in this part: c = setTimeout('hi("' + b + '")', 50)

Is there a fix without changing function inside function structure?


问:
Pushing without committing
I have a git repo and I just pushed it to a server. Then I setup a post-receive hook on the server. I want to check it works. I have to commit again just to see if it works? I would really like to just force a push while I'm trying to get this set up rather than keep making commits that have no real value. Its not working, and I just don't get it.</p>

```<code>$ git push --force origin master
Everything up-to-date
</code>```

答:
There's a little dirty trick you can use:

```<code>git stash save && git push --force origin "stash@{0}:master" && git stash pop
</code>```

This does 3 things:

Stash current uncommitted changes.
Stashing creates a new commit, but on a separate ref. It will not dirty your history. Additionally, it clears the working directory from the changes. See step 3.

Push the stashed code

Pop the stash - clearing the stash and placing all the files back in your working directory.

This will effectively push all files to the remote without creating a local commit.

Title: Pushing without committing

Body:
I have a git repo and I just pushed it to a server. Then I setup a post-receive hook on the server. I want to check it works. I have to commit again just to see if it works? I would really like to just force a push while I'm trying to get this set up rather than keep making commits that have no real value. Its not working, and I just don't get it.

$ git push --force origin master
Everything up-to-date

Body:
There's a little dirty trick you can use:

git stash save && git push --force origin "stash@{0}:master" && git stash pop

This does 3 things:

Stash current uncommitted changes.
Stashing creates a new commit, but on a separate ref. It will not dirty your history. Additionally, it clears the working directory from the changes. See step 3.

Push the stashed code

Pop the stash - clearing the stash and placing all the files back in your working directory.

This will effectively push all files to the remote without creating a local commit.


问:
How to implement a system wide text replacement in windows programmatically?
I have a small VB .Net application that, among other things, attempts to substitute system wide typed text by the user(hotstrings concept). To achieve that, I have deployed 'ahk2exe' and 'AutoHotkeySC.bin' with my application and did the following:

When a user assignes a new 'hotstring':

Kill 'hotstring' exe script file if running

Append new hotstring to the script file (if non exist then create a new one)

Convert edited/new script file to exe (using ahk2exe)

Run the newly converted script exe
(somewhere there I also check if the hotstring has been already assigned)

However, I am not totally satisfied with this method for the following two main reasons:

The extra resources deployed with the application.

Lag: The time it takes for the system to kill the process and then restart it takes a minimum of 5 seconds on my fast computer and more on other computers. That amount of time is much more than the time it takes the user to assign the hotstring, minimize/close the window and then test his/her new hotstring. When the user does so initially with no success they will think the process failed. So this method is not very good for user experience.

So, I am looking for a different method or implementation. May be using keyboard hooks? Or maybe adding a .dll library that achieves the same. Are there any resources you know about that might help (free or commercial)? What is the best way to achieve my desired goal?

Many thanks for your help.

答:
Implementing what Autohotkey does would be a pretty non trivial task.

But I'm pretty sure that AHK supports an "autoreload" option for scripts

googling "autohotkey auto reload" turned up several pages discussing that very concept. IF that worked, all you'd have to do is update the script file and that's it, AHK should automatically reload the script.


答:
c = setTimeout( () => hi(b), 50 ) should work.

Edit (thanks to @evolutionxbox in the comments)

c = setTimeout( hi, 50, b ) looks even better.

You're getting this error :

hi is not defined

at line 4 : hi(a)

The execution is not even making it to the timeout part. The timeout itself won't produce an error, but won't do anything either, because 'hi("' + b + '")' is a string, not a function.

Title: how to call function inside a function with setTimeout


问:
Loop Through Column to find Match - VBA
I'm trying to create a VBA Command that goes through many cases in order to find a commission fee percentage. Starting off, I need to compare a ID to a list of Special IDs (Using one Integer, loop through a column of 30 integers). I also need to check to see if the 'komisija' value is greater than 40, which would then simply return 40.</p>

```<code>Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double

Set kSheet = ThisWorkbook.Sheets("komisijas")

'Set variables equal to the cell data
  klienta_nr = Range("A2").Value
  ISIN = Range("E2").Value
  Cena = Range("H2").Value
  Skaits = Range("I2").Value

'First, have case for non-special klients
If Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A40")) Then
      If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
        Komisija = (Cena * Skaits) * 0.003
        End If
      If Right(klienta_nr, 1) = 7 Then
        Komisija = (Cena * Skaits) * 0.01
        End If
      If Komisija > 40 Then
        Range("K2").Value = Komisija
        End If
      Range("K2").Value = Komisija
End If

Range("K2").Value = Komisija
</code>```

答:
If i understood right you must do this:

```<code>for each k in range("komisijas")
 If klienta_nr = k.value Then
   If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
     Komisija = (Cena * Skaits) * 0.003
   If Right(klienta_nr, 1) = 7 Then
     Komisija = (Cena * Skaits) * 0.01
   End If
   If Komisija > 40 Then
     Range("D4").Value = 40
   End If
     Range("D4").Value = Komisija
 End If
next
</code>```

This code is not tested.

Title: Loop Through Column to find Match - VBA

Body:
I'm trying to create a VBA Command that goes through many cases in order to find a commission fee percentage. Starting off, I need to compare a ID to a list of Special IDs (Using one Integer, loop through a column of 30 integers). I also need to check to see if the 'komisija' value is greater than 40, which would then simply return 40.

Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double

Set kSheet = ThisWorkbook.Sheets("komisijas")

'Set variables equal to the cell data
  klienta_nr = Range("A2").Value
  ISIN = Range("E2").Value
  Cena = Range("H2").Value
  Skaits = Range("I2").Value

'First, have case for non-special klients
If Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A40")) Then
      If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
        Komisija = (Cena * Skaits) * 0.003
        End If
      If Right(klienta_nr, 1) = 7 Then
        Komisija = (Cena * Skaits) * 0.01
        End If
      If Komisija > 40 Then
        Range("K2").Value = Komisija
        End If
      Range("K2").Value = Komisija
End If

Range("K2").Value = Komisija

Body:
If i understood right you must do this:

for each k in range("komisijas")
 If klienta_nr = k.value Then
   If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
     Komisija = (Cena * Skaits) * 0.003
   If Right(klienta_nr, 1) = 7 Then
     Komisija = (Cena * Skaits) * 0.01
   End If
   If Komisija > 40 Then
     Range("D4").Value = 40
   End If
     Range("D4").Value = Komisija
 End If
next

This code is not tested.


问:
json array index duplication
I am creating a json array and obtain data from an arraylist.
My problem is that when I save the data in my json it only saves the last data of the arraylist to each index.

This is my code:

```<code> JSONArray ItemsRequiredobArr=new JSONArray();

            JSONObject ItemsRequiredob=new JSONObject();

            for(int ii=0;ii<StocklistAdapter.listItemN.size();ii++){

                ItemsRequiredob.put("ItemID",StocklistAdapter.itemIdN.get(ii));
                ItemsRequiredob.put("StockCode",StocklistAdapter.listItemN.get(ii));
                Toast.makeText(this, "StockCode"+StocklistAdapter.listItemN.get(ii), Toast.LENGTH_SHORT).show();
                ItemsRequiredob.put("Description",StocklistAdapter.listAddressN.get(ii));
                ItemsRequiredob.put("Quantity",StocklistAdapter.QuaN.get(ii));

                ItemsRequiredobArr.put(ItemsRequiredob);

                        /*Toast.makeText(mContext, "i"+i+" "+listAddressN.get(i), Toast.LENGTH_SHORT).show();*/
                    Log.e("d", ItemsRequiredob.get("ItemID").toString());

            }
            ob.put("ItemsRequired",ItemsRequiredobArr);
</code>```

this is my array from above

```<code>[{"ItemsRequired":[{"ItemID":"3224","StockCode":"10030","Description":"Complete - 3 section mattress\r\n\r\nPolyeurethane velcro grips","Quantity":"0"},{"ItemID":"3224","StockCode":"10030","Description":"Complete - 3 section mattress\r\n\r\nPolyeurethane velcro grips","Quantity":"0"}]
</code>```

As you can see both index have the same data but arraylist contains different data on index 0 and 1.
Please help me out since I am a beginner.

答:
Your ItemsRequiredob object created one time and you are setting the value every time so it's talking the last item for every object, so Put ItemsRequiredob inside for loop like this, it will work fine

```<code>            for(int ii=0;ii<StocklistAdapter.listItemN.size();ii++){
JSONObject ItemsRequiredob=new JSONObject();

                ItemsRequiredob.put("ItemID",StocklistAdapter.itemIdN.get(ii));
                ItemsRequiredob.put("StockCode",StocklistAdapter.listItemN.get(ii));
                Toast.makeText(this, "StockCode"+StocklistAdapter.listItemN.get(ii), Toast.LENGTH_SHORT).show();
                ItemsRequiredob.put("Description",StocklistAdapter.listAddressN.get(ii));
                ItemsRequiredob.put("Quantity",StocklistAdapter.QuaN.get(ii));

                ItemsRequiredobArr.put(ItemsRequiredob);

                        /*Toast.makeText(mContext, "i"+i+" "+listAddressN.get(i), Toast.LENGTH_SHORT).show();*/
                    Log.e("d", ItemsRequiredob.get("ItemID").toString());

            }
</code>```

Title: json array index duplication

Body:
I am creating a json array and obtain data from an arraylist.
My problem is that when I save the data in my json it only saves the last data of the arraylist to each index.

This is my code:

 JSONArray ItemsRequiredobArr=new JSONArray();

            JSONObject ItemsRequiredob=new JSONObject();

            for(int ii=0;ii<StocklistAdapter.listItemN.size();ii++){

                ItemsRequiredob.put("ItemID",StocklistAdapter.itemIdN.get(ii));
                ItemsRequiredob.put("StockCode",StocklistAdapter.listItemN.get(ii));
                Toast.makeText(this, "StockCode"+StocklistAdapter.listItemN.get(ii), Toast.LENGTH_SHORT).show();
                ItemsRequiredob.put("Description",StocklistAdapter.listAddressN.get(ii));
                ItemsRequiredob.put("Quantity",StocklistAdapter.QuaN.get(ii));

                ItemsRequiredobArr.put(ItemsRequiredob);

                        /*Toast.makeText(mContext, "i"+i+" "+listAddressN.get(i), Toast.LENGTH_SHORT).show();*/
                    Log.e("d", ItemsRequiredob.get("ItemID").toString());

            }
            ob.put("ItemsRequired",ItemsRequiredobArr);

this is my array from above

[{"ItemsRequired":[{"ItemID":"3224","StockCode":"10030","Description":"Complete - 3 section mattress\r\n\r\nPolyeurethane velcro grips","Quantity":"0"},{"ItemID":"3224","StockCode":"10030","Description":"Complete - 3 section mattress\r\n\r\nPolyeurethane velcro grips","Quantity":"0"}]

As you can see both index have the same data but arraylist contains different data on index 0 and 1.
Please help me out since I am a beginner.

Body:
Your ItemsRequiredob object created one time and you are setting the value every time so it's talking the last item for every object, so Put ItemsRequiredob inside for loop like this, it will work fine

            for(int ii=0;ii<StocklistAdapter.listItemN.size();ii++){
JSONObject ItemsRequiredob=new JSONObject();

                ItemsRequiredob.put("ItemID",StocklistAdapter.itemIdN.get(ii));
                ItemsRequiredob.put("StockCode",StocklistAdapter.listItemN.get(ii));
                Toast.makeText(this, "StockCode"+StocklistAdapter.listItemN.get(ii), Toast.LENGTH_SHORT).show();
                ItemsRequiredob.put("Description",StocklistAdapter.listAddressN.get(ii));
                ItemsRequiredob.put("Quantity",StocklistAdapter.QuaN.get(ii));

                ItemsRequiredobArr.put(ItemsRequiredob);

                        /*Toast.makeText(mContext, "i"+i+" "+listAddressN.get(i), Toast.LENGTH_SHORT).show();*/
                    Log.e("d", ItemsRequiredob.get("ItemID").toString());

            }


问:
Composer: "Content-length mismatch" & "http://packagist.org could not be fully loaded..."
When I try to create a new laravel project with "laravel new project"
I got this  error:

```<code>Content-Length mismatch
http://packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date
</code>```

When I do "composer update" or "composer install doctrine/dbal", I got the error too.
And my composer is too slow.

答:
I get this error when I'm in China. This is what works for me:

Turn on a Chinese VPN

Run composer config -g repo.packagist composer https://packagist.phpcomposer.com

Update your composer

Body:
When I try to create a new laravel project with "laravel new project"
I got this  error:

Content-Length mismatch
http://packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date

When I do "composer update" or "composer install doctrine/dbal", I got the error too.
And my composer is too slow.


问:
parse json with ant
I have an ant build script that needs to pull files down from a web server.  I can use the "get" task to pull these files down one by one.  However, I'd like to be able to get a list of these files first and then iterate over the list with "get" to download the files.  The webserver will report the list of files in json format, but I'm not sure how to parse json with ant.

Are there any ant plugins that allow for json parsing?

答:
I used Dave's suggestion above and it worked out pretty well. Here's what I came up with:

(Note, I ripped this out of my actual build file and tried to remove anything specific and just leave the example parts, so forgive me if it's missing anything or whatever, but it should give you an idea of how this works).

```<code><?xml version="1.0"?>

<project name="jsonExample" default="all">
<target name="all" depends="example" />

<target name="example">

<!-- This uses Rhino - an Open Source implementation of JavaScript written in Java -
     to parse JSON. -->
<script language="javascript"> <![CDATA[

    importClass(java.io.File);
    importClass(java.io.FileReader);
    importClass(java.io.BufferedReader);
    importClass(java.io.FileWriter);
    importClass(java.io.BufferedWriter);

    var file = new File("/path/to/myJSON.js");
    fr = new FileReader(file);
    br = new BufferedReader(fr);

    // Read the file we just retrieved from the webservice that contains JSON.
    var json = br.readLine();

    // Evaluate the serialized JSON
    var struct = eval("(" + json + ")");

    // Get the data from
    var value = struct.data.VALUE;

    echo = example.createTask("echo");
    echo.setMessage("Value = " + value);
    echo.perform();

    ]]>
</script>
</target>
</code>```

Title: parse json with ant

Body:
I used Dave's suggestion above and it worked out pretty well. Here's what I came up with:

(Note, I ripped this out of my actual build file and tried to remove anything specific and just leave the example parts, so forgive me if it's missing anything or whatever, but it should give you an idea of how this works).

<?xml version="1.0"?>

<project name="jsonExample" default="all">
<target name="all" depends="example" />

<target name="example">

<!-- This uses Rhino - an Open Source implementation of JavaScript written in Java -
     to parse JSON. -->
<script language="javascript"> <![CDATA[

    importClass(java.io.File);
    importClass(java.io.FileReader);
    importClass(java.io.BufferedReader);
    importClass(java.io.FileWriter);
    importClass(java.io.BufferedWriter);

    var file = new File("/path/to/myJSON.js");
    fr = new FileReader(file);
    br = new BufferedReader(fr);

    // Read the file we just retrieved from the webservice that contains JSON.
    var json = br.readLine();

    // Evaluate the serialized JSON
    var struct = eval("(" + json + ")");

    // Get the data from
    var value = struct.data.VALUE;

    echo = example.createTask("echo");
    echo.setMessage("Value = " + value);
    echo.perform();

    ]]>
</script>
</target>


问:
Why am I getting Proxy returns "HTTP/1.1 407 authenticationrequired"?
I am using nginx, gunicorn, django for backend. I have created apis in django, and these apis works fine for me from postman and even from my python code. But when I try to access the api from proxy server it gives me 'Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 authenticationrequired."'

Here are my nginx settings :

```<code>server {
    listen 80;
    server_name mywebsite.in;
    return 301 https://$host$request_uri;
}

server {
    listen 80;
    server_name www.mywebsite.in;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl ;
    server_name mywebsite.in ;
    ssl_certificate /root/mywebsite.in.crt;
    ssl_certificate_key /root/mywebsite.in.key;

    #FOR SERVING HTML PAGES
    root /root/front/mywebsite ;
    index index.html index.php;

    location /py/ {

        include proxy_params;
        proxy_set_header X-Forwarded-Protocol https ;
        proxy_ssl_session_reuse off;
        # proxy_ssl_certificate /root/mywebsite.in.crt;
        # proxy_ssl_certificate_key /root/mywebsite.in.key;
        # proxy_ssl_client_certificate /root/intermediate.crt;
        # proxy_ssl_verify off;

        proxy_pass http://localhost:8000/ ;
    }

    location /blog/ {
    proxy_pass https://mywebsitein.blogspot.in/;
    }

    location /upload {
    #  auth_basic                 "Restricted Upload";
    #  auth_basic_user_file       basic.htpasswd;
    limit_except POST          { deny all; }

    client_body_temp_path      /tmp/$request_body_file;
    client_body_in_file_only   on;
    client_body_buffer_size    128K;
    client_max_body_size       1000M;

    proxy_pass_request_headers on;
    proxy_set_header           X-FILE $request_body_file;
    proxy_set_body             off;
    proxy_redirect             off;
    proxy_pass                 http://localhost:8000/file;
    }
}
</code>```

Here is my nginx.conf

```<code>user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    proxy_read_timeout 1200;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;
    expires 1h;
    add_header Cache-Control no-cache;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon application/javascript;
}
</code>```

My API Is of the form https://www.mywebsite.in/py/api/main

Please help me out, where I am going wrong.

答:
Set config as below for /py

```<code>location /py {

        port_in_redirect off;
        proxy_redirect  off;
        proxy_set_header  Host  $http_host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

        proxy_pass http://localhost:8000;
    }
</code>```

Body:
I am using nginx, gunicorn, django for backend. I have created apis in django, and these apis works fine for me from postman and even from my python code. But when I try to access the api from proxy server it gives me 'Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 authenticationrequired."'

Here are my nginx settings :

server {
    listen 80;
    server_name mywebsite.in;
    return 301 https://$host$request_uri;
}

server {
    listen 80;
    server_name www.mywebsite.in;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl ;
    server_name mywebsite.in ;
    ssl_certificate /root/mywebsite.in.crt;
    ssl_certificate_key /root/mywebsite.in.key;

    #FOR SERVING HTML PAGES
    root /root/front/mywebsite ;
    index index.html index.php;

    location /py/ {

        include proxy_params;
        proxy_set_header X-Forwarded-Protocol https ;
        proxy_ssl_session_reuse off;
        # proxy_ssl_certificate /root/mywebsite.in.crt;
        # proxy_ssl_certificate_key /root/mywebsite.in.key;
        # proxy_ssl_client_certificate /root/intermediate.crt;
        # proxy_ssl_verify off;

        proxy_pass http://localhost:8000/ ;
    }

    location /blog/ {
    proxy_pass https://mywebsitein.blogspot.in/;
    }

    location /upload {
    #  auth_basic                 "Restricted Upload";
    #  auth_basic_user_file       basic.htpasswd;
    limit_except POST          { deny all; }

    client_body_temp_path      /tmp/$request_body_file;
    client_body_in_file_only   on;
    client_body_buffer_size    128K;
    client_max_body_size       1000M;

    proxy_pass_request_headers on;
    proxy_set_header           X-FILE $request_body_file;
    proxy_set_body             off;
    proxy_redirect             off;
    proxy_pass                 http://localhost:8000/file;
    }
}

Here is my nginx.conf

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    proxy_read_timeout 1200;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;
    expires 1h;
    add_header Cache-Control no-cache;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon application/javascript;
}

My API Is of the form https://www.mywebsite.in/py/api/main

Please help me out, where I am going wrong.

Body:
Set config as below for /py

location /py {

        port_in_redirect off;
        proxy_redirect  off;
        proxy_set_header  Host  $http_host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

        proxy_pass http://localhost:8000;
    }


问:
Creating EditText with button
I must create EditText with button inside and assign functions which will run after pressing the button. Then I would like to make it reusable - somehow add it as an element to my Activity. I was wondering about extending EditTextView and adding button and creating functions inside of it.
Any suggestions/ tutorials?</p>

答:
You need to Create Custom View Components

Below links has sample and will solve your problems

https://developer.android.com/training/custom-views/index.html

https://developer.android.com/guide/topics/ui/custom-components.html

Title: Creating EditText with button


问:
split a large file into small file based on pattern that can occur randomly Python
I have this large file with following content:

```<code>Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....
</code>```

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

```<code>column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh
</code>```

File2: Naresh.txt

```<code>column1 column2 column3
298     390     Naresh
</code>```

File3: Suresh.txt

```<code>Column1 column2 column3
123     125      suresh
394     305      suresh
</code>```

and likewise.
I wrote the following python codes and it worked:

```<code>def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()
</code>```

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

```<code>Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh
</code>```

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

答:
Rather than open and close file pointers on every line you could keep them opened until your work is done.

First create a dictionary for file pointers :

```<code>fps = {}
</code>```

Then in the loop iterating your data file, if the file pointer doesn't exist, create it :

```<code>if a[-1] not in fps.keys():
    fps[a[-1]] = open(a[-1], 'a')
fps[a[-1]].write(line)
</code>```

Then at the end of the loop you can close the file pointers :

```<code>for f in fps.values():
    f.close()
</code>```

Body:
I have this large file with following content:

Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh

File2: Naresh.txt

column1 column2 column3
298     390     Naresh

File3: Suresh.txt

Column1 column2 column3
123     125      suresh
394     305      suresh

and likewise.
I wrote the following python codes and it worked:

def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

Body:
Rather than open and close file pointers on every line you could keep them opened until your work is done.

First create a dictionary for file pointers :

fps = {}

Then in the loop iterating your data file, if the file pointer doesn't exist, create it :

if a[-1] not in fps.keys():
    fps[a[-1]] = open(a[-1], 'a')
fps[a[-1]].write(line)

Then at the end of the loop you can close the file pointers :

for f in fps.values():
    f.close()


问:
wpf Stop ctrl+Alt+del and windows button using C#
how to disable ctrl+Alt+del and windows button using C# with wpf ??

I tried to use some events form events like key down but fail.

答:
It isn't possible to disable the shortcut for Ctrl-Alt-Del specifically,
this is because the Ctrl-Alt-Del combo is a deeply baked system call.

However it is possible to filter them separately, so you can prevent the other shortcuts with these keys.
To do this you need to hook into the OS events:

this hooks onto the system events.

```<code>private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
</code>```

if you set the id to 13 it will hook onto the keyboard inputs.

in the callback you need several things:

```<code>[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
    public readonly Keys key;
    private readonly int scanCode;
    private readonly int flags;
    private readonly int time;
    private readonly IntPtr extra;
}
</code>```

this struct is required to read the actual keys in c#.

this can be used by giving the delegate a function like:

```<code>private static IntPtr CaptureKey(int nCode, IntPtr wp, IntPtr lp)
{
    if (nCode < 0) return (IntPtr) 1; //CallNextHookEx(_ptrHook, nCode, wp, lp);
    KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
    if(objKeyInfo.key == /*some key*/){
        // do something
    }
}
</code>```

when using this you can get the key from objKeyInfo.key

for more background info about the Ctrl-Alt-Del combo:
Is there any method to disable logoff,lock and taskmanager in ctrl+alt+del in C#

Body:
It isn't possible to disable the shortcut for Ctrl-Alt-Del specifically,
this is because the Ctrl-Alt-Del combo is a deeply baked system call.

However it is possible to filter them separately, so you can prevent the other shortcuts with these keys.
To do this you need to hook into the OS events:

this hooks onto the system events.

private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);

if you set the id to 13 it will hook onto the keyboard inputs.

in the callback you need several things:

[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
    public readonly Keys key;
    private readonly int scanCode;
    private readonly int flags;
    private readonly int time;
    private readonly IntPtr extra;
}

this struct is required to read the actual keys in c#.

this can be used by giving the delegate a function like:

private static IntPtr CaptureKey(int nCode, IntPtr wp, IntPtr lp)
{
    if (nCode < 0) return (IntPtr) 1; //CallNextHookEx(_ptrHook, nCode, wp, lp);
    KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
    if(objKeyInfo.key == /*some key*/){
        // do something
    }
}

when using this you can get the key from objKeyInfo.key

for more background info about the Ctrl-Alt-Del combo:
Is there any method to disable logoff,lock and taskmanager in ctrl+alt+del in C#

ContentLicense: CC BY-SA 4.0


问:
What difficulties have you had with clojure?
I have started building a system with clojure, mainly because I need to use Java libraries. My main problem with Clojure is lack of proper IDE support (getting it to work well with Emacs on Windows was not trivial). I was wondering what difficulties other people have had.</p>

答:
My problems so far:

It wasn't too easy to get EMACS/SLIME with Common Lisp AND Clojure.

Clojure 1.2.0 stacktraces are a mess so far. It's often so hard to get it what went wrong.

The debugging experience is not very nice. Tried JSWAT and Counterclockwise, but not really happy with it.


问:
MultipleCompilationErrorsException in running Groovy script
I'm trying to access all nodes of my request in XML format using XmlHolder class with getDomNodes method and when I try it it getting this error.

Can somebody explain what does this mean?

My source code:

```<code>import com.eviware.soapui.support.XmlHolder

log.info "hello !! welcome to "
def holder = new XmlHolder(context.expand('${logIn - Request 1#request}')
def allnodes = holder.getDomNodes("//LoginParameters_1")
</code>```

The error I get:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script15.groovy: 6: unexpected token: def @ line 6, column 1. def allnodes = holder.getDomNodes("//LoginParameters_1")throws org.apache.xmlbeans.XmlException ^ org.codehaus.groovy.syntax.SyntaxException: unexpected token: def @ line 6, column 1. at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:140) at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:108) at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:236) at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:162) at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:912) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:574) at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:550)...

```<code>  import com.eviware.soapui.support.XmlHolder import          com.eviware.soapui.support.xml.XmlUtils
  log.info "hello !! welcome to " xmlu= new XmlUtils()
  holder= new XmlHolder(context.expand('${logIn - Request 1#request}'))
  i=0
  for (nodes in holder.getDomNodes("//wsos:logIn")) {       if(xmlu.getNodeValue(nodes[i])=="?")
   xmlu.setNodeValue(nodes[i],"")
     i++;
  }
</code>```

is giving me below error:
groovy.lang.MissingMethodException: No signature of method: org.apache.xmlbeans.impl.store.Xobj$ElementXobj.getAt() is applicable for argument types: (java.lang.Integer) values: [0] Possible solutions: getAt(java.lang.String), item(int), putAt(java.lang.String, java.lang.Object), wait(), grep(), getClass() error at line: 16

答:
The org.codehaus.groovy.syntax.SyntaxException are related with incorrect syntax in the code, in your specific case the problem is a missing closed parenthesis:

A ) is missing to close XmlHolder declaration:

```<code>def holder = new XmlHolder(context.expand('${logIn - Request 1#request}')
</code>```

Must be:

```<code>def holder = new XmlHolder(context.expand('${logIn - Request 1#request}'))
                                                                         ^ missing close
</code>```

Body:
I'm trying to access all nodes of my request in XML format using XmlHolder class with getDomNodes method and when I try it it getting this error.

Can somebody explain what does this mean?

My source code:

import com.eviware.soapui.support.XmlHolder

log.info "hello !! welcome to "
def holder = new XmlHolder(context.expand('${logIn - Request 1#request}')
def allnodes = holder.getDomNodes("//LoginParameters_1")

The error I get:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script15.groovy: 6: unexpected token: def @ line 6, column 1. def allnodes = holder.getDomNodes("//LoginParameters_1")throws org.apache.xmlbeans.XmlException ^ org.codehaus.groovy.syntax.SyntaxException: unexpected token: def @ line 6, column 1. at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:140) at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:108) at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:236) at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:162) at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:912) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:574) at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:550)...

  import com.eviware.soapui.support.XmlHolder import          com.eviware.soapui.support.xml.XmlUtils
  log.info "hello !! welcome to " xmlu= new XmlUtils()
  holder= new XmlHolder(context.expand('${logIn - Request 1#request}'))
  i=0
  for (nodes in holder.getDomNodes("//wsos:logIn")) {       if(xmlu.getNodeValue(nodes[i])=="?")
   xmlu.setNodeValue(nodes[i],"")
     i++;
  }

is giving me below error:
groovy.lang.MissingMethodException: No signature of method: org.apache.xmlbeans.impl.store.Xobj$ElementXobj.getAt() is applicable for argument types: (java.lang.Integer) values: [0] Possible solutions: getAt(java.lang.String), item(int), putAt(java.lang.String, java.lang.Object), wait(), grep(), getClass() error at line: 16

Body:
The org.codehaus.groovy.syntax.SyntaxException are related with incorrect syntax in the code, in your specific case the problem is a missing closed parenthesis:

A ) is missing to close XmlHolder declaration:

def holder = new XmlHolder(context.expand('${logIn - Request 1#request}')

Must be:

def holder = new XmlHolder(context.expand('${logIn - Request 1#request}'))
                                                                         ^ missing close


问:
$env:homedrive is lost occasionally
I use $env:homedrive in my scripts in Azure's CustomScriptExtension.
Strangely sometimes I got blank from this variable but sometimes OK.

Is this environment variable not reliable?

答:
If it concerns a script at logon, it is possible that network is not loaded yet due to windows fast logon. Maybe directly pulling it from the registry is more reliable:</p>

```<code>(Get-Item -ErrorAction SilentlyContinue "HKCU:\Volatile Environment").GetValue("HomeDrive")
</code>```

Title: $env:homedrive is lost occasionally

Body:
If it concerns a script at logon, it is possible that network is not loaded yet due to windows fast logon. Maybe directly pulling it from the registry is more reliable:

(Get-Item -ErrorAction SilentlyContinue "HKCU:\Volatile Environment").GetValue("HomeDrive")


问:
Laravel 5.4 go live with no npm installed
I've just finished my first project with laravel.

Now when I want to go live, I suddenly discovered that my host does not allow installation of nodejs on their shard host package.

The shock the horror....

I managed to do everything on the live server, I ran npm run production on my local machine and uploaded the minified files for the css and js.

The problem is, on my shard server, I still get this vue warning:

You are running Vue in development mode. Make sure to turn on
  production mode when deploying for production. See more tips at
  https://vuejs.org/guide/deployment.html

but not on my local machine.

Looking at the link they refer to, I don't really understand what I need to do as I'm new to laravel, npm, node and vue.

How can I turn vue to production mode manually without npm?

Is it possible?

答:
Yes, you can adjust this manually. If you are using the Laravel scaffolding for Laravel Mix, add the following lines to your resources/js/bootstrap.js file

```<code>Vue.config.devtools = false
Vue.config.debug = false
Vue.config.silent = true
</code>```

These lines will suppress the warnings, debugging and turn off devtools, essentially the same as npm run production. This will also turn them off in your local environment, but it is probably your only solution.

Body:
Yes, you can adjust this manually. If you are using the Laravel scaffolding for Laravel Mix, add the following lines to your resources/js/bootstrap.js file

Vue.config.devtools = false
Vue.config.debug = false
Vue.config.silent = true

These lines will suppress the warnings, debugging and turn off devtools, essentially the same as npm run production. This will also turn them off in your local environment, but it is probably your only solution.


问:
Click on RecyclerView item in ViewHolder
In my ViewHolder i have a function:

```<code>    private fun setupAmountLabel(amountLabelView: CategorizedAmountView, category: Category?,
                             amount: Double, percent: String, isParentView: Boolean) {
    amountLabelView.setTitle(category?.getLocalizedName() ?: "")
    amountLabelView.setSubTitle(percent)
    amountLabelView.setAmountSignType(AmountType.NEGATIVE)
    amountLabelView.setAmountAndCurrencyCode(amount, currencyCode)
    amountLabelView.setIconCategory(category)
    amountLabelView.setAmountColor(amount.toDataSetColor())
    amountLabelView.setOnClickListener {
        listItemClickListener?.onListItemClick(if (isParentView) 1 else 0, category?.guid ?: "")
    }
}
</code>```

Where i want to click on my listItemParent. Earlier this function was in the adapter, and I called the adapter by creating the setListClickListener method. But now i didn t know how i can make click on this item.

答:
where you initialized the list view can able to use this code.     </p>

```<code>listview.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {

                }
            });
</code>```

<p>or </p>

```<code>listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //here you can use the position to determine what checkbox to check
        //this assumes that you have an array of your checkboxes as well. called checkbox

    }
});
</code>```

Body:
In my ViewHolder i have a function:

    private fun setupAmountLabel(amountLabelView: CategorizedAmountView, category: Category?,
                             amount: Double, percent: String, isParentView: Boolean) {
    amountLabelView.setTitle(category?.getLocalizedName() ?: "")
    amountLabelView.setSubTitle(percent)
    amountLabelView.setAmountSignType(AmountType.NEGATIVE)
    amountLabelView.setAmountAndCurrencyCode(amount, currencyCode)
    amountLabelView.setIconCategory(category)
    amountLabelView.setAmountColor(amount.toDataSetColor())
    amountLabelView.setOnClickListener {
        listItemClickListener?.onListItemClick(if (isParentView) 1 else 0, category?.guid ?: "")
    }
}

Where i want to click on my listItemParent. Earlier this function was in the adapter, and I called the adapter by creating the setListClickListener method. But now i didn t know how i can make click on this item.

Body:
where you initialized the list view can able to use this code.

listview.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {

                }
            });

or

listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //here you can use the position to determine what checkbox to check
        //this assumes that you have an array of your checkboxes as well. called checkbox

    }
});