问:
How to search for an optimal solution that depends on a specific values in a matrix in C#
I need to extract the best path in terms of its length from a rectangular array like this array:

The pathfinding rules:

Start from the indexes provided in the method signature where the rowIndex and colIndex are the positions of the starting point.`

The ones must be able to connect with each other either horizontally, vertically, or diagonally.

The last point on the path is the cell with a value of one that has no path to any other surrounding cells with a value of one.

I tried the following recursion algorithm, but it does not work for me and generate wrong output i.e. not as expected!!.

Here are the results: Results

```<code>        using System;
        using System.IO;
        using System.Text;
        using System.Drawing;
        using System.Collections;
        using System.ComponentModel;
        using System.Windows.Forms;
        using System.Data;
        using System.Threading;
        using AUV_Topology;
        using System.Collections.Generic;
        using System.Media;
        using System.Linq;

        namespace AUVtopology
        {
            public partial class Form1 : Form
            {
              static int[,] array;
              static List<int[]> path;

// *******************************************************************************************************************************//
        //This method is used to make sure the coordinate array
        //is contained in the list. List.contains(new int[] {val1,val2}) was not enough.
        static Boolean containsArray(List<int[]> list, int[] array)
        {
            if (array == null || array.Length == 0)
            {
                return false;
            }
            foreach (var listArray in list)
            {
                if (listArray != null && listArray.Length == array.Length)
                {
                    for (int i = 0; i < listArray.Length; i++)
                    {
                        if (i != listArray.Length - 1)
                        {
                            if (array[i] != listArray[i] && array[i + 1] != listArray[i + 1])
                            {
                                continue;
                            }

                            return true;

                        }

                    }

                }
            }
            return false;
        }

// *******************************************************************************************************************************//

        //This is the recursive method of the algorithm. It finds the
        //maximum path of 1 cells in a matrix of 0/1 cells
        static List<int[]> getMaxPath(int[,] array, List<int[]> maxPath, int rowIndex, int colIndex)
        {

            //Add the current cell to the path.
            maxPath.Add(new int[] { rowIndex, colIndex });

            //Get the array limits.
            int rowLength = array.GetLength(0);
            int colLength = array.GetLength(1);

            //If the path contains all the cells in the matrix, stop
            if (maxPath.Count >= rowLength * colLength)
            {
                return maxPath;
            }

            //remove one from lengths to make it the maximum index
            colLength = colLength - 1;
            rowLength = rowLength - 1;

            //We'll use this variable to see which of the
            //potential 7 paths are the longest.
            List<int[]> futurePath;

            //Go over all 8 possible adjoining cells:
            //If we can go one down, one right, and it's a spot we
            //have not yet visited
            if (colIndex < colLength && rowIndex < rowLength &&
                array[rowIndex + 1, colIndex + 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex + 1, colIndex + 1 }))
            {

                //We use maxPath first, since this is the first
                //direction and by default is the longest
                maxPath = getMaxPath(array, maxPath, rowIndex + 1, colIndex + 1);
            }

            //If we can go one down, and it's a spot we have not
            //yet visited
            if (colIndex < colLength &&
              array[rowIndex, colIndex + 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex, colIndex + 1 }))
            {

                //We use futurePath now, since this is a second
                //direction and a potential contender
                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex + 1);

                //We only need the maximum path.
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one down and one left, and it's a spot
            //we have not yet visited
            if (rowIndex > 0 && colIndex < colLength &&
               array[rowIndex - 1, colIndex + 1] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex + 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex + 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one left, and it's a spot we have not
            //yet visited
            if (rowIndex > 0 &&
               array[rowIndex - 1, colIndex] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one left and one up, and it's a spot we
            //have not yet visited
            if (rowIndex > 0 && colIndex > 0 &&
              array[rowIndex - 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex - 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up, and it's a spot we have not yet
            //visited
            if (colIndex > 0 &&
                array[rowIndex, colIndex - 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up and one right, and it's a spot we
            //have not yet visited
            if (colIndex > 0 && rowIndex < rowLength &&
              array[rowIndex + 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one right, and it's a spot we have not
            //yet visited
            if (rowIndex < rowLength &&
              array[rowIndex + 1, colIndex] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //We return the max path. Note: If none of the directions around
            //us was applicable, we simply return the path we started
            //with our cell included.
            return maxPath;
        }
</code>```

Is prim algorithm the best choice ?

答:
I finally had some time to work this out.  I did it with an enumerator to simplify the if loop.  Did like having 8 if statements. I've been doing code like this for 40 years and know all the pitfalls.</p>

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace AUV_Topology
{
    class Program
    {
        public static object[] PopulationChromosomes = {
                                    new int[,] {
                                        { 1,0,1,1},
                                        { 1,1,1,0},
                                        { 1,0,1,0},
                                        { 0,1,0,0}
                  },
                                      new int[,] {
                                        { 1,1,0,1},
                                        { 1,1,0,0},
                                        { 0,1,0,0},
                                        { 1,0,1,0}
                  },
                                    new int[,] {
                                        { 1,0,0,0},
                                        { 1,1,1,1},
                                        { 1,0,0,1},
                                        { 0,0,0,1}
                  },
                                    new int[,] {
                                        { 0,1,0,0},
                                        { 1,1,1,0},
                                        { 1,0,0,1},
                                        { 0,1,0,1}
                  },
                                    new int[,] {
                                        { 0,1,0,1},
                                        { 0,1,1,0},
                                        { 1,1,0,1},
                                        { 0,0,0,1}
                  },
                                    new int[,] {
                                        { 0,1,1,0},
                                        { 1,1,0,1},
                                        { 0,1,0,1},
                                        { 1,0,0,0}
                  }

        };
        public static int[] auvChromosomeLocationsIndexesX = { 3, 0, 1, 3, 2, 2 };
        public static int[] auvChromosomeLocationsIndexesY = { 2, 1, 0, 1, 3, 0 };

        const string FILENAME = @"C:/temp/TreeParser.txt";
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter(FILENAME);
            int tt = 0;

            foreach (int[,] chromosome in PopulationChromosomes)
            {

                new SpanningTree(auvChromosomeLocationsIndexesY[tt], auvChromosomeLocationsIndexesX[tt], chromosome);
                SpanningTree.OrderHighLow(SpanningTree.root, 0);
                SpanningTree.Print(SpanningTree.root, 0, tt, sw);
                tt++;
            }
            sw.Flush();
            sw.Close();
            Console.ReadLine();

        }
    }
    /* Class Cell */
    /*****************************************************************************************************************************/

    public class Cell
    {

        public int row { get; set; }
        public int col { get; set; }
        public int value { get; set; }
        public Boolean visited { get; set; }

    }

    /* Class EnumCell */
    /*****************************************************************************************************************************/

    public class EnumCell : IEnumerator<Cell>
    {
        public EnumCell() { }

        public EnumCell(int startRow, int startCol, List<List<Cell>> graph)
        {
            row = startRow;
            col = startCol;
            numberOfRows = graph.Count;
            numberOfCols = graph[0].Count;
            EnumCell.graph = graph;
            this.position = LOCATIONS.RESET;
        }
        public enum XY
        {
            Y = 0, //row
            X = 1 //col
        }

        public enum LOCATIONS : byte
        {
            RESET = 0xFF,
            TOP_LEFT = 0,
            TOP_MIDDLE,
            TOP_RIGHT,
            LEFT,
            RIGHT,
            BOTTOM_LEFT,
            BOTTOM_MIDDLE,
            BOTTOM_RIGHT,
            END,
            INVALID
        }

        public static List<List<Cell>> graph { get; set; }
        public static int row { get; set; }
        public static int col { get; set; }
        public static int numberOfRows { get; set; }
        public static int numberOfCols { get; set; }

        //offsets are in same order as enum location as y-offset(row), x-offset (col)
        private static List<List<int>> offsets = new List<List<int>>() {
        new List<int>() { -1, -1 },
        new List<int>() { -1, 0 },
        new List<int>() { -1, +1 },
        new List<int>() { 0, -1 },
        new List<int>() { 0, +1 },
        new List<int>() { +1, -1 },
        new List<int>() { +1, 0 },
        new List<int>() { +1, +1 }
        };
        public LOCATIONS position { get; set; }

        public EnumCell GetEnumerator()
        {
            return new EnumCell(row, col, graph);
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

        /* Class Current Cell */
        /*****************************************************************************************************************************/
        public Cell Current
        {
            get
            {
                try
                {
                    // move to first valid postion
                    if (position == LOCATIONS.RESET) position = LOCATIONS.TOP_LEFT;
                    for (LOCATIONS location = position; location < LOCATIONS.END; location++)
                    {
                        if ((row + offsets[(byte)location][(int)XY.Y] >= 0) && (row + offsets[(byte)location][(int)XY.Y] < numberOfRows) &&
                        (col + offsets[(byte)location][(int)XY.X] >= 0) && (col + offsets[(byte)location][(int)XY.X] < numberOfCols))
                        {
                            position = (LOCATIONS)location;
                            int newRow = row + offsets[(byte)location][(int)XY.Y];
                            int newCol = col + offsets[(byte)location][(int)XY.X];
                            return graph[newRow][newCol];
                        }
                    }
                    throw new InvalidOperationException();
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public Boolean MoveNext()
        {
            Boolean results = false;
            for (LOCATIONS location = ++position; location < LOCATIONS.END; location++)
            {
                int y = offsets[(byte)location][(int)XY.Y];
                int x = offsets[(byte)location][(int)XY.X];
                if ((row + y >= 0) && (row + y < numberOfRows) &&
                (col + x >= 0) && (col + x < numberOfCols))
                {
                    if (graph[row + y][col + x].value == 1)
                    {
                        position = (LOCATIONS)location;
                        return true;
                    }
                }
            }

            return results;
        }

        public void Reset()
        {
            position = LOCATIONS.RESET;
        }
        public void Dispose()
        {
        }
    }

    /* Class Graph */
    /*****************************************************************************************************************************/

    public class Graph
    {
        public Graph(int[,] graph)
        {

            this.graph = new List<List<Cell>>();
            for (int row = 0; row < graph.GetLength(0); row++)
            {
                List<Cell> newRow = new List<Cell>();
                this.graph.Add(newRow);
                for (int col = 0; col < graph.GetLength(1); col++)
                {
                    Cell newCell = new Cell();
                    newRow.Add(newCell);

                    newCell.row = row;
                    newCell.col = col;
                    newCell.value = graph[row, col];
                    newCell.visited = false;
                }
            }

        }
        public List<List<Cell>> graph;

    }

    /* Class SpanningTree */
    /*****************************************************************************************************************************/

    class SpanningTree
    {
        public static Graph graph = null;
        public static SpanningTree root = null;

        public static int counter = 0;

        public int row { get; set; }
        public int col { get; set; }
        public int length { get; set; }
        public List<SpanningTree> children { get; set; }

        public SpanningTree() { }
        public SpanningTree(int startRow, int startCol, int[,] graph)
        {
            root = new SpanningTree();
            SpanningTree.graph = new Graph(graph);
            RecursiveTree(root, SpanningTree.graph.graph[startRow][startCol]);

        }
        public int RecursiveTree(SpanningTree parent, Cell currentCell)
        {
            int length = 0;
            int maxLength = 0;
            parent.row = currentCell.row;
            parent.col = currentCell.col;

            graph.graph[currentCell.row][currentCell.col].visited = true;
            EnumCell enumCell = new EnumCell(currentCell.row, currentCell.col, graph.graph);

            foreach (Cell cell in enumCell)
            {
                if (!cell.visited)
                {
                    SpanningTree newBranch = new SpanningTree();
                    if (parent.children == null) parent.children = new List<SpanningTree>();
                    length = RecursiveTree(newBranch, SpanningTree.graph.graph[cell.row][cell.col]);

                    if (length > maxLength)
                    {
                        if ((EnumCell.numberOfRows > 7) || (EnumCell.numberOfCols > 7))
                        {
                            if (parent.children.Count == 0)
                            {
                                parent.children.Add(newBranch);
                            }
                            else
                            {
                                parent.children[0] = newBranch;
                            }
                        }
                        else
                        {
                            parent.children.Add(newBranch);
                        }
                        maxLength = length;
                    }
                }
            }
            graph.graph[currentCell.row][currentCell.col].visited = false;

            parent.length = maxLength;
            return maxLength + 1;
        }
        public static void OrderHighLow(SpanningTree parent, int level)
        {
            if (parent.children != null)
            {
                parent.children = parent.children.OrderByDescending(x => x.length).ToList();
                foreach (SpanningTree child in parent.children)
                {
                    OrderHighLow(child, level + 1);
                }
            }
        }

        public static void Print(SpanningTree parent, int level, int chromosomeNum, StreamWriter sw)
        {
            sw.WriteLine("------------------- Chromosome : {0} -------------------", chromosomeNum);
            //Print(parent, level, sw);
            sw.WriteLine("---------Longest----------");
            PrintLongest(parent, level, sw);
            counter = 0;
        }

        private static void Print(SpanningTree parent, int level, StreamWriter sw)
        {
            //////////////////////////////////////////////////////////////////////
            sw.WriteLine("{0}Level : '{1}', Row : '{2}', Col : '{3}', Length : '{4}'", new string(' ', 4 * level), level, parent.row, parent.col, parent.length);
            //////////////////////////////////////////////////////////////////////

            if (parent.children != null)
            {
                foreach (SpanningTree child in parent.children)
                {

                    Print(child, level + 1, sw);

                    if (child.length == 0)
                    {

                        sw.WriteLine("||,,,,,,Branch {0},,,,,,||", counter);
                        sw.WriteLine("{0}Level : '{1}', Row : '{2}', Col : '{3}', Length : '{4}'", new string(' ', 4 * level), level, root.row, root.col, root.length);
                        counter += 1;

                    }
                }
            }

        }

        public static void PrintLongest(SpanningTree parent, int level, StreamWriter sw)
        {
            //////////////////////////////////////////////////////////////////////
            sw.WriteLine("{0}Level : '{1}', Row : '{2}', Col : '{3}', Length : '{4}'", new string(' ', 4 * level), level, parent.row, parent.col, parent.length);
            //////////////////////////////////////////////////////////////////////

            if (parent.children != null)
            {
                PrintLongest(parent.children[0], level + 1, sw);
            }
        }
    }

}// end name space
</code>```

Body:
I need to extract the best path in terms of its length from a rectangular array like this array:

The pathfinding rules:

Start from the indexes provided in the method signature where the rowIndex and colIndex are the positions of the starting point.`

The ones must be able to connect with each other either horizontally, vertically, or diagonally.

The last point on the path is the cell with a value of one that has no path to any other surrounding cells with a value of one.

I tried the following recursion algorithm, but it does not work for me and generate wrong output i.e. not as expected!!.

Here are the results: Results

        using System;
        using System.IO;
        using System.Text;
        using System.Drawing;
        using System.Collections;
        using System.ComponentModel;
        using System.Windows.Forms;
        using System.Data;
        using System.Threading;
        using AUV_Topology;
        using System.Collections.Generic;
        using System.Media;
        using System.Linq;

        namespace AUVtopology
        {
            public partial class Form1 : Form
            {
              static int[,] array;
              static List<int[]> path;

// *******************************************************************************************************************************//
        //This method is used to make sure the coordinate array
        //is contained in the list. List.contains(new int[] {val1,val2}) was not enough.
        static Boolean containsArray(List<int[]> list, int[] array)
        {
            if (array == null || array.Length == 0)
            {
                return false;
            }
            foreach (var listArray in list)
            {
                if (listArray != null && listArray.Length == array.Length)
                {
                    for (int i = 0; i < listArray.Length; i++)
                    {
                        if (i != listArray.Length - 1)
                        {
                            if (array[i] != listArray[i] && array[i + 1] != listArray[i + 1])
                            {
                                continue;
                            }

                            return true;

                        }

                    }

                }
            }
            return false;
        }

// *******************************************************************************************************************************//

        //This is the recursive method of the algorithm. It finds the
        //maximum path of 1 cells in a matrix of 0/1 cells
        static List<int[]> getMaxPath(int[,] array, List<int[]> maxPath, int rowIndex, int colIndex)
        {

            //Add the current cell to the path.
            maxPath.Add(new int[] { rowIndex, colIndex });

            //Get the array limits.
            int rowLength = array.GetLength(0);
            int colLength = array.GetLength(1);

            //If the path contains all the cells in the matrix, stop
            if (maxPath.Count >= rowLength * colLength)
            {
                return maxPath;
            }

            //remove one from lengths to make it the maximum index
            colLength = colLength - 1;
            rowLength = rowLength - 1;

            //We'll use this variable to see which of the
            //potential 7 paths are the longest.
            List<int[]> futurePath;

            //Go over all 8 possible adjoining cells:
            //If we can go one down, one right, and it's a spot we
            //have not yet visited
            if (colIndex < colLength && rowIndex < rowLength &&
                array[rowIndex + 1, colIndex + 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex + 1, colIndex + 1 }))
            {

                //We use maxPath first, since this is the first
                //direction and by default is the longest
                maxPath = getMaxPath(array, maxPath, rowIndex + 1, colIndex + 1);
            }

            //If we can go one down, and it's a spot we have not
            //yet visited
            if (colIndex < colLength &&
              array[rowIndex, colIndex + 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex, colIndex + 1 }))
            {

                //We use futurePath now, since this is a second
                //direction and a potential contender
                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex + 1);

                //We only need the maximum path.
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one down and one left, and it's a spot
            //we have not yet visited
            if (rowIndex > 0 && colIndex < colLength &&
               array[rowIndex - 1, colIndex + 1] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex + 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex + 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one left, and it's a spot we have not
            //yet visited
            if (rowIndex > 0 &&
               array[rowIndex - 1, colIndex] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one left and one up, and it's a spot we
            //have not yet visited
            if (rowIndex > 0 && colIndex > 0 &&
              array[rowIndex - 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex - 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up, and it's a spot we have not yet
            //visited
            if (colIndex > 0 &&
                array[rowIndex, colIndex - 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up and one right, and it's a spot we
            //have not yet visited
            if (colIndex > 0 && rowIndex < rowLength &&
              array[rowIndex + 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one right, and it's a spot we have not
            //yet visited
            if (rowIndex < rowLength &&
              array[rowIndex + 1, colIndex] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //We return the max path. Note: If none of the directions around
            //us was applicable, we simply return the path we started
            //with our cell included.
            return maxPath;
        }

Is prim algorithm the best choice ?

Body:
I finally had some time to work this out.  I did it with an enumerator to simplify the if loop.  Did like having 8 if statements. I've been doing code like this for 40 years and know all the pitfalls.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace AUV_Topology
{
    class Program
    {
        public static object[] PopulationChromosomes = {
                                    new int[,] {
                                        { 1,0,1,1},
                                        { 1,1,1,0},
                                        { 1,0,1,0},
                                        { 0,1,0,0}
                  },
                                      new int[,] {
                                        { 1,1,0,1},
                                        { 1,1,0,0},
                                        { 0,1,0,0},
                                        { 1,0,1,0}
                  },
                                    new int[,] {
                                        { 1,0,0,0},
                                        { 1,1,1,1},
                                        { 1,0,0,1},
                                        { 0,0,0,1}
                  },
                                    new int[,] {
                                        { 0,1,0,0},
                                        { 1,1,1,0},
                                        { 1,0,0,1},
                                        { 0,1,0,1}
                  },
                                    new int[,] {
                                        { 0,1,0,1},
                                        { 0,1,1,0},
                                        { 1,1,0,1},
                                        { 0,0,0,1}
                  },
                                    new int[,] {
                                        { 0,1,1,0},
                                        { 1,1,0,1},
                                        { 0,1,0,1},
                                        { 1,0,0,0}
                  }

        };
        public static int[] auvChromosomeLocationsIndexesX = { 3, 0, 1, 3, 2, 2 };
        public static int[] auvChromosomeLocationsIndexesY = { 2, 1, 0, 1, 3, 0 };

        const string FILENAME = @"C:/temp/TreeParser.txt";
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter(FILENAME);
            int tt = 0;

            foreach (int[,] chromosome in PopulationChromosomes)
            {

                new SpanningTree(auvChromosomeLocationsIndexesY[tt], auvChromosomeLocationsIndexesX[tt], chromosome);
                SpanningTree.OrderHighLow(SpanningTree.root, 0);
                SpanningTree.Print(SpanningTree.root, 0, tt, sw);
                tt++;
            }
            sw.Flush();
            sw.Close();
            Console.ReadLine();

        }
    }
    /* Class Cell */
    /*****************************************************************************************************************************/

    public class Cell
    {

        public int row { get; set; }
        public int col { get; set; }
        public int value { get; set; }
        public Boolean visited { get; set; }

    }

    /* Class EnumCell */
    /*****************************************************************************************************************************/

    public class EnumCell : IEnumerator<Cell>
    {
        public EnumCell() { }

        public EnumCell(int startRow, int startCol, List<List<Cell>> graph)
        {
            row = startRow;
            col = startCol;
            numberOfRows = graph.Count;
            numberOfCols = graph[0].Count;
            EnumCell.graph = graph;
            this.position = LOCATIONS.RESET;
        }
        public enum XY
        {
            Y = 0, //row
            X = 1 //col
        }

        public enum LOCATIONS : byte
        {
            RESET = 0xFF,
            TOP_LEFT = 0,
            TOP_MIDDLE,
            TOP_RIGHT,
            LEFT,
            RIGHT,
            BOTTOM_LEFT,
            BOTTOM_MIDDLE,
            BOTTOM_RIGHT,
            END,
            INVALID
        }

        public static List<List<Cell>> graph { get; set; }
        public static int row { get; set; }
        public static int col { get; set; }
        public static int numberOfRows { get; set; }
        public static int numberOfCols { get; set; }

        //offsets are in same order as enum location as y-offset(row), x-offset (col)
        private static List<List<int>> offsets = new List<List<int>>() {
        new List<int>() { -1, -1 },
        new List<int>() { -1, 0 },
        new List<int>() { -1, +1 },
        new List<int>() { 0, -1 },
        new List<int>() { 0, +1 },
        new List<int>() { +1, -1 },
        new List<int>() { +1, 0 },
        new List<int>() { +1, +1 }
        };
        public LOCATIONS position { get; set; }

        public EnumCell GetEnumerator()
        {
            return new EnumCell(row, col, graph);
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

        /* Class Current Cell */
        /*****************************************************************************************************************************/
        public Cell Current
        {
            get
            {
                try
                {
                    // move to first valid postion
                    if (position == LOCATIONS.RESET) position = LOCATIONS.TOP_LEFT;
                    for (LOCATIONS location = position; location < LOCATIONS.END; location++)
                    {
                        if ((row + offsets[(byte)location][(int)XY.Y] >= 0) && (row + offsets[(byte)location][(int)XY.Y] < numberOfRows) &&
                        (col + offsets[(byte)location][(int)XY.X] >= 0) && (col + offsets[(byte)location][(int)XY.X] < numberOfCols))
                        {
                            position = (LOCATIONS)location;
                            int newRow = row + offsets[(byte)location][(int)XY.Y];
                            int newCol = col + offsets[(byte)location][(int)XY.X];
                            return graph[newRow][newCol];
                        }
                    }
                    throw new InvalidOperationException();
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public Boolean MoveNext()
        {
            Boolean results = false;
            for (LOCATIONS location = ++position; location < LOCATIONS.END; location++)
            {
                int y = offsets[(byte)location][(int)XY.Y];
                int x = offsets[(byte)location][(int)XY.X];
                if ((row + y >= 0) && (row + y < numberOfRows) &&
                (col + x >= 0) && (col + x < numberOfCols))
                {
                    if (graph[row + y][col + x].value == 1)
                    {
                        position = (LOCATIONS)location;
                        return true;
                    }
                }
            }

            return results;
        }

        public void Reset()
        {
            position = LOCATIONS.RESET;
        }
        public void Dispose()
        {
        }
    }

    /* Class Graph */
    /*****************************************************************************************************************************/

    public class Graph
    {
        public Graph(int[,] graph)
        {

            this.graph = new List<List<Cell>>();
            for (int row = 0; row < graph.GetLength(0); row++)
            {
                List<Cell> newRow = new List<Cell>();
                this.graph.Add(newRow);
                for (int col = 0; col < graph.GetLength(1); col++)
                {
                    Cell newCell = new Cell();
                    newRow.Add(newCell);

                    newCell.row = row;
                    newCell.col = col;
                    newCell.value = graph[row, col];
                    newCell.visited = false;
                }
            }

        }
        public List<List<Cell>> graph;

    }

    /* Class SpanningTree */
    /*****************************************************************************************************************************/

    class SpanningTree
    {
        public static Graph graph = null;
        public static SpanningTree root = null;

        public static int counter = 0;

        public int row { get; set; }
        public int col { get; set; }
        public int length { get; set; }
        public List<SpanningTree> children { get; set; }

        public SpanningTree() { }
        public SpanningTree(int startRow, int startCol, int[,] graph)
        {
            root = new SpanningTree();
            SpanningTree.graph = new Graph(graph);
            RecursiveTree(root, SpanningTree.graph.graph[startRow][startCol]);

        }
        public int RecursiveTree(SpanningTree parent, Cell currentCell)
        {
            int length = 0;
            int maxLength = 0;
            parent.row = currentCell.row;
            parent.col = currentCell.col;

            graph.graph[currentCell.row][currentCell.col].visited = true;
            EnumCell enumCell = new EnumCell(currentCell.row, currentCell.col, graph.graph);

            foreach (Cell cell in enumCell)
            {
                if (!cell.visited)
                {
                    SpanningTree newBranch = new SpanningTree();
                    if (parent.children == null) parent.children = new List<SpanningTree>();
                    length = RecursiveTree(newBranch, SpanningTree.graph.graph[cell.row][cell.col]);

                    if (length > maxLength)
                    {
                        if ((EnumCell.numberOfRows > 7) || (EnumCell.numberOfCols > 7))
                        {
                            if (parent.children.Count == 0)
                            {
                                parent.children.Add(newBranch);
                            }
                            else
                            {
                                parent.children[0] = newBranch;
                            }
                        }
                        else
                        {
                            parent.children.Add(newBranch);
                        }
                        maxLength = length;
                    }
                }
            }
            graph.graph[currentCell.row][currentCell.col].visited = false;

            parent.length = maxLength;
            return maxLength + 1;
        }
        public static void OrderHighLow(SpanningTree parent, int level)
        {
            if (parent.children != null)
            {
                parent.children = parent.children.OrderByDescending(x => x.length).ToList();
                foreach (SpanningTree child in parent.children)
                {
                    OrderHighLow(child, level + 1);
                }
            }
        }

        public static void Print(SpanningTree parent, int level, int chromosomeNum, StreamWriter sw)
        {
            sw.WriteLine("------------------- Chromosome : {0} -------------------", chromosomeNum);
            //Print(parent, level, sw);
            sw.WriteLine("---------Longest----------");
            PrintLongest(parent, level, sw);
            counter = 0;
        }

        private static void Print(SpanningTree parent, int level, StreamWriter sw)
        {
            //////////////////////////////////////////////////////////////////////
            sw.WriteLine("{0}Level : '{1}', Row : '{2}', Col : '{3}', Length : '{4}'", new string(' ', 4 * level), level, parent.row, parent.col, parent.length);
            //////////////////////////////////////////////////////////////////////

            if (parent.children != null)
            {
                foreach (SpanningTree child in parent.children)
                {

                    Print(child, level + 1, sw);

                    if (child.length == 0)
                    {

                        sw.WriteLine("||,,,,,,Branch {0},,,,,,||", counter);
                        sw.WriteLine("{0}Level : '{1}', Row : '{2}', Col : '{3}', Length : '{4}'", new string(' ', 4 * level), level, root.row, root.col, root.length);
                        counter += 1;

                    }
                }
            }

        }

        public static void PrintLongest(SpanningTree parent, int level, StreamWriter sw)
        {
            //////////////////////////////////////////////////////////////////////
            sw.WriteLine("{0}Level : '{1}', Row : '{2}', Col : '{3}', Length : '{4}'", new string(' ', 4 * level), level, parent.row, parent.col, parent.length);
            //////////////////////////////////////////////////////////////////////

            if (parent.children != null)
            {
                PrintLongest(parent.children[0], level + 1, sw);
            }
        }
    }

}// end name space


来源: stackexchange

问:
Best way to perform an ajax auto complete search box in WPF?
I have been trying to do this with the AutoCompleteBox tool in the WPF Tool Kit. What event would best be used if I wanted to display information from a database based on what the user enters?</p>

答:
Try handling the Populating event as per the following:

WPF: AutoComplete TextBox, ...again

ContentLicense: CC BY-SA 2.5


问:
What exactly constructors do?
Yesterday I was reading PHP classes and suddenly something got weird to me. And that was about constructors in C# and PHP.

My question is what is constructor? Isn't it a special methods, used when instantiating a class that can does something like a method and take necessary resources for class like Memory and etc? And if it is, for example when we have a parent class named A which we derive another class named B and create an instance of B and call the B  constructor and send some arguments to its parent (A) use :base(args.) (in C#) and use parent::__construct(args) (in PHP) , so is it goes and call the parent constructor , we don't want to exactly take resources for the parent but we just call the parent constructor which do it's for us. What happen exactly here?

I guess in this case simply just called it like a function! :\ i don't know i made my self clear or not ... Ask me if there is any Ambiguity, and Thanks ;)

UPDATED
Thank by giving me the negative vote by the way ...
look at this link :
Microsoft Docs
as far i read here it's something more than a simple function which hold a block of codes.(but with differences which you said , no return value and etc.)
if it is just a function which called when an instance get created so why if we make it private then we can not make any instance of it anymore?
why when we wanted to create a class add a () at the end of the class name?and when we want to pass any args to constructor use those () to send ?
[Person new_person = new Person();]
if you think also this a question which doesn't show any effort , vote negative again :D

答:
A constructor is a block of code similar to a method that's called when an instance of an object is getting created.

A constructor doesn't have a return type. The name of the constructor must be the same as the name of the class.

ContentLicense: CC BY-SA 3.0

Title: What exactly constructors do?


问:
Reference (FK) user in administrator table
I have 2 tables in the database: User and Administrator

When an administrator is registered, an entry in the User table is added, and inmediately after, I want reference this user in the Administrator table.

I'm using EF Core and the comments are the steps:

```<code>// Register user
this.context
    .Users
    .Add(new Entities.User()
    {
        Name = "Jhon",
    });

// Get the ID of the newly created user
int userId = this.context
    .Users
    .Select(_ => _.Id ????)

// Reference the user created in the Administrator table
this.context
    .Administradors
    .Add(new Entities.Administrator()
    {
        UserId = userId
    });
</code>```

I need both tables because the administrator has fields that the user no.

答:
Store the newly created user in a variable. Then save the changes, EF will update the ID

```<code>var user = new Entities.User { Name = "John" };
context.Users.Add(user);
context.SaveChanges();

// Reference the user created in the Administrator table
context.Administradors.Add(new Entities.Administrator { UserId = user.Id });
context.SaveChanges();
</code>```

However, a better alternative is to use the navigation property instead of using the ID.

```<code>var user = new Entities.User { Name = "John" };
context.Users.Add(user);

// Reference the user created in the Administrator table
context.Administradors.Add(new Entities.Administrator { User = user });

context.SaveChanges();
</code>```

This requires ony one SaveChanges().

EF is smart enough to make the fixup. I.e., if you work with the ID, EF will update the navigation property when doing the SaveChanges(). If you work with the navigation property, EF will update the ID when doing the SaveChanges().

Body:
I have 2 tables in the database: User and Administrator

When an administrator is registered, an entry in the User table is added, and inmediately after, I want reference this user in the Administrator table.

I'm using EF Core and the comments are the steps:

// Register user
this.context
    .Users
    .Add(new Entities.User()
    {
        Name = "Jhon",
    });

// Get the ID of the newly created user
int userId = this.context
    .Users
    .Select(_ => _.Id ????)

// Reference the user created in the Administrator table
this.context
    .Administradors
    .Add(new Entities.Administrator()
    {
        UserId = userId
    });

I need both tables because the administrator has fields that the user no.

Body:
Store the newly created user in a variable. Then save the changes, EF will update the ID

var user = new Entities.User { Name = "John" };
context.Users.Add(user);
context.SaveChanges();

// Reference the user created in the Administrator table
context.Administradors.Add(new Entities.Administrator { UserId = user.Id });
context.SaveChanges();

However, a better alternative is to use the navigation property instead of using the ID.

var user = new Entities.User { Name = "John" };
context.Users.Add(user);

// Reference the user created in the Administrator table
context.Administradors.Add(new Entities.Administrator { User = user });

context.SaveChanges();

This requires ony one SaveChanges().

EF is smart enough to make the fixup. I.e., if you work with the ID, EF will update the navigation property when doing the SaveChanges(). If you work with the navigation property, EF will update the ID when doing the SaveChanges().


问:
SML Common type for different structures
I am implementing sets in Standard ML. Currently it looks like this:

```<code>signature SET = sig
    type t
    type 'a set
    ...
    val map : ('a -> t) -> 'a set -> t set
end

functor ListSetFn (EQ : sig type t val equal : t * t -> bool end)
        :> SET where type t = EQ.t = struct
    type t = EQ.t
    type 'a set = 'a list
    ...
    fun map f = fromList o (List.map f)
end
</code>```

I want the map function to be able to take any set in a structure SET, ideally not even constrained to those from ListSetFn functor. However, on the top level it can only operate on sets created by a single structure: the one it is called from, e.g.:

```<code>functor EqListSetFn(eqtype t) :> SET where type t = t = struct
    structure T = ListSetFn(struct type t = t val equal = op= end)
    open T
end

structure IntSet = EqListSetFn(type t = int)
IntSet.map : ('a -> IntSet.t) -> 'a IntSet.set -> IntSet.t IntSet.set
</code>```

While I'd really like it to be something like

```<code>IntSet.map : ('a -> IntSet.t) -> 'a ArbitrarySet.set -> IntSet.t IntSet.set
</code>```

Is there a way to do it? I know it could be declared on the top level, but I want to hide the internal implementation and hence use opaque signature(s)

答:
In principle, there are two ways to perform such a parameterisation:

Wrap the function into its own functor, that takes the other structure as argument.

Make the function polymorphic, passing the relevant functions to operate on the other type as individual arguments, or as a record of arguments.

Let's assume the SET signature contains these functions:

```<code>val empty : 'a set
val isEmpty : 'a set -> bool
val add : 'a * 'a set -> 'a set
val remove : 'a * 'a set -> 'a set
val pick : 'a set -> 'a
</code>```

Then the former solution would look like this:

```<code>functor SetMap (structure S1 : SET; structure S2 : SET) =
struct
  fun map f s =
    if S1.isEmpty s then S2.empty else
    let val x = S1.pick s
    in S2.add (f x, map f (S2.remove (x, s)))
    end
end
</code>```

For solution 2, you would need to pass all relevant functions directly, e.g. as records:

```<code>fun map {isEmpty, pick, remove} {empty, add} f s =
    let
      fun iter s =
        if isEmpty s then empty else
        let val x = pick s
        in add (f x, iter (remove (x, s)))
        end
    in iter s end
</code>```

FWIW, this would be nicer with first-class structures, but SML does not have them as a standard feature.

```<code>fun map (pack S1 : SET) (pack S2 : SET) f s =
    let
      fun iter s =
        if S1.isEmpty s then S2.empty else
        let val x = S1.pick s
        in S2.add (f x, iter (S2.remove (x, s)))
        end
    in iter s end
</code>```

Body:
I am implementing sets in Standard ML. Currently it looks like this:

signature SET = sig
    type t
    type 'a set
    ...
    val map : ('a -> t) -> 'a set -> t set
end

functor ListSetFn (EQ : sig type t val equal : t * t -> bool end)
        :> SET where type t = EQ.t = struct
    type t = EQ.t
    type 'a set = 'a list
    ...
    fun map f = fromList o (List.map f)
end

I want the map function to be able to take any set in a structure SET, ideally not even constrained to those from ListSetFn functor. However, on the top level it can only operate on sets created by a single structure: the one it is called from, e.g.:

functor EqListSetFn(eqtype t) :> SET where type t = t = struct
    structure T = ListSetFn(struct type t = t val equal = op= end)
    open T
end

structure IntSet = EqListSetFn(type t = int)
IntSet.map : ('a -> IntSet.t) -> 'a IntSet.set -> IntSet.t IntSet.set

While I'd really like it to be something like

IntSet.map : ('a -> IntSet.t) -> 'a ArbitrarySet.set -> IntSet.t IntSet.set

Is there a way to do it? I know it could be declared on the top level, but I want to hide the internal implementation and hence use opaque signature(s)

Body:
In principle, there are two ways to perform such a parameterisation:

Wrap the function into its own functor, that takes the other structure as argument.

Make the function polymorphic, passing the relevant functions to operate on the other type as individual arguments, or as a record of arguments.

Let's assume the SET signature contains these functions:

val empty : 'a set
val isEmpty : 'a set -> bool
val add : 'a * 'a set -> 'a set
val remove : 'a * 'a set -> 'a set
val pick : 'a set -> 'a

Then the former solution would look like this:

functor SetMap (structure S1 : SET; structure S2 : SET) =
struct
  fun map f s =
    if S1.isEmpty s then S2.empty else
    let val x = S1.pick s
    in S2.add (f x, map f (S2.remove (x, s)))
    end
end

For solution 2, you would need to pass all relevant functions directly, e.g. as records:

fun map {isEmpty, pick, remove} {empty, add} f s =
    let
      fun iter s =
        if isEmpty s then empty else
        let val x = pick s
        in add (f x, iter (remove (x, s)))
        end
    in iter s end

FWIW, this would be nicer with first-class structures, but SML does not have them as a standard feature.

fun map (pack S1 : SET) (pack S2 : SET) f s =
    let
      fun iter s =
        if S1.isEmpty s then S2.empty else
        let val x = S1.pick s
        in S2.add (f x, iter (S2.remove (x, s)))
        end
    in iter s end


问:
C# 6.0 null-coalescing not working correctly for me
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?</p>

```<code>  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";
</code>```

答:
Just as an aside to Ehsan Sajjad's answer, you actually don't need the second ? here, assuming pallets_qty_total is an integer.  You can instead use Nullable.GetValueOrDefault(), like so:

```<code> string qty = stop?.pallets_qty_total.GetValueOrDefault().ToString();
</code>```

If pallets_qty_total has a value, it will return it.  If not, it will return default(T), which, in the case of an int, is 0.

Body:
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?

  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";

Body:
Just as an aside to Ehsan Sajjad's answer, you actually don't need the second ? here, assuming pallets_qty_total is an integer.  You can instead use Nullable.GetValueOrDefault(), like so:

 string qty = stop?.pallets_qty_total.GetValueOrDefault().ToString();

If pallets_qty_total has a value, it will return it.  If not, it will return default(T), which, in the case of an int, is 0.


问:
Changing INT with FLOAT
I have this program:

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

#define n 3
#define m 3

int main(void)
{
int i;
int j;
int mat[n][m];
int sum = 0;

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        printf("Enters the matrix values[%d][%d]: ", i, j);
        scanf("%d", &mat[i][j]);
    }
}

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
}

printf("the sum of all elements of matrix is: %d\n", sum);

for (i = 0; i < n; i++)
{
    sum = 0;
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
    sum = sum / m;
    printf("The average of the i-th line is %d e': %d\n", i, sum);
}
getch();
}
</code>```

This program works but if the result of sum is an odd number, the average of i-th line is approximated by default.

For solving it I have changed "int summ" with "float summ" but it doesn't work.

Can Someone help me please?

答: It would work if you changed the type of sum to a float or double, but you'd also need to change the format specifier in your printf call. Use %f to output a float.

Title: Changing INT with FLOAT

Body:
I have this program:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define n 3
#define m 3

int main(void)
{
int i;
int j;
int mat[n][m];
int sum = 0;

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        printf("Enters the matrix values[%d][%d]: ", i, j);
        scanf("%d", &mat[i][j]);
    }
}

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
}

printf("the sum of all elements of matrix is: %d\n", sum);

for (i = 0; i < n; i++)
{
    sum = 0;
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
    sum = sum / m;
    printf("The average of the i-th line is %d e': %d\n", i, sum);
}
getch();
}

This program works but if the result of sum is an odd number, the average of i-th line is approximated by default.

For solving it I have changed "int summ" with "float summ" but it doesn't work.

Can Someone help me please?


问:
Reactive Extension in msword
I am wondering if it is possible to use Reactive Extensions in Word. I have seen this where Jeff shows how to wire up a workbook open event in excel http://social.msdn.microsoft.com/Forums/en/rx/thread/5ace45b1-778b-4ddd-b2ab-d5c8a1659f5f.

I wondering if I could do the same sort of thing in word.

I have got this far....

```<code>     public static class ApplicationExtensions
  {
    public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(this Word.Application application)
    {
      return Observable.Create<Word.Document>(observer =>
      {
        Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler = observer.OnNext;
        application.DocumentBeforeSave += handler;

        return () => application.DocumentBeforeSave -= handler;
      });
    }
  }
</code>```

but I receive the error No overload for 'OnNext' matches delegate 'Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler

Can anyone point me in the right direction.

Regards

Mike

答:
Your problem is an issue of delegate signatures.

IObserver<T>.OnNext is defined as void (T value)

whereas ApplicationEvents4_DocumentBeforeSaveEventHandler is defined as void (Document doc, ref bool SaveAsUI, ref bool Cancel)

If you only need to emit the Document (and not the other details, like making it cancelable), you can do something like this:

```<code>public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(
    this Word.Application application)
{
    return Observable.Create<Word.Document>(observer =>
    {
        Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler =
            (doc, ref saveAsUI, ref cancel) => observer.OnNext(doc);

        application.DocumentBeforeSave += handler;

        return () => application.DocumentBeforeSave -= handler;
    });
}
</code>```

If you do require all the data, you'll need to create a wrapper class of some kind an IObservable sequence can only emit a single type:

```<code>public class DocumentBeforeSaveEventArgs : CancelEventArgs
{
    public Document Document { get; private set; }
    public bool SaveAsUI { get; private set; }

    public DocumentBeforeSaveEventArgs(Document document, bool saveAsUI)
    {
        this.Document = document;
        this.SaveAsUI = saveAsUI;
    }
}
</code>```

And then you can use it like so:

```<code>public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(
    this Word.Application application)
{
    return Observable.Create<Word.Document>(observer =>
    {
        Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler =
            (doc, ref saveAsUI, ref cancel) =>
            {
                var args = new DocumentBeforeSaveEventArgs(doc, saveAsUI);

                observer.OnNext(args);

                cancel = args.Cancel;
            };

        application.DocumentBeforeSave += handler;

        return () => application.DocumentBeforeSave -= handler;
    });
}
</code>```

Title: Reactive Extension in msword

Body:
I am wondering if it is possible to use Reactive Extensions in Word. I have seen this where Jeff shows how to wire up a workbook open event in excel http://social.msdn.microsoft.com/Forums/en/rx/thread/5ace45b1-778b-4ddd-b2ab-d5c8a1659f5f.

I wondering if I could do the same sort of thing in word.

I have got this far....

     public static class ApplicationExtensions
  {
    public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(this Word.Application application)
    {
      return Observable.Create<Word.Document>(observer =>
      {
        Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler = observer.OnNext;
        application.DocumentBeforeSave += handler;

        return () => application.DocumentBeforeSave -= handler;
      });
    }
  }

but I receive the error No overload for 'OnNext' matches delegate 'Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler

Can anyone point me in the right direction.

Regards

Mike

Body:
Your problem is an issue of delegate signatures.

IObserver<T>.OnNext is defined as void (T value)

whereas ApplicationEvents4_DocumentBeforeSaveEventHandler is defined as void (Document doc, ref bool SaveAsUI, ref bool Cancel)

If you only need to emit the Document (and not the other details, like making it cancelable), you can do something like this:

public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(
    this Word.Application application)
{
    return Observable.Create<Word.Document>(observer =>
    {
        Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler =
            (doc, ref saveAsUI, ref cancel) => observer.OnNext(doc);

        application.DocumentBeforeSave += handler;

        return () => application.DocumentBeforeSave -= handler;
    });
}

If you do require all the data, you'll need to create a wrapper class of some kind an IObservable sequence can only emit a single type:

public class DocumentBeforeSaveEventArgs : CancelEventArgs
{
    public Document Document { get; private set; }
    public bool SaveAsUI { get; private set; }

    public DocumentBeforeSaveEventArgs(Document document, bool saveAsUI)
    {
        this.Document = document;
        this.SaveAsUI = saveAsUI;
    }
}

And then you can use it like so:

public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(
    this Word.Application application)
{
    return Observable.Create<Word.Document>(observer =>
    {
        Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler =
            (doc, ref saveAsUI, ref cancel) =>
            {
                var args = new DocumentBeforeSaveEventArgs(doc, saveAsUI);

                observer.OnNext(args);

                cancel = args.Cancel;
            };

        application.DocumentBeforeSave += handler;

        return () => application.DocumentBeforeSave -= handler;
    });
}


问:
easy code not working on empty project ( binding ,input , ng model) in any browser
Im having a problem with the following code, is a simple one, i want to be able to se in my view what i put in the input text. but nothing is happening. when running in the online simulator no problem, but in my browser nothing happens. what im doing wrong?. my project is empty. Also tried it in firefox, explorer and chrome, and not working at all. the only thing i have is this pice of code. have no error in browser console... im using angular cli.
what im doing wrong guys? please help.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div></code>```

SOURCE

答:
This is second time, you posted same question. The potential reason for not working your code inside browser may be you are not adding the your script.js path correctly. Check your browser console and debug the issue. Your code seems fine.

Just copy and paste this code inside a .html file and open in browser. It should work.

    Name: <input ng-model="firstname">

{{firstname}}

```

Body:
Im having a problem with the following code, is a simple one, i want to be able to se in my view what i put in the input text. but nothing is happening. when running in the online simulator no problem, but in my browser nothing happens. what im doing wrong?. my project is empty. Also tried it in firefox, explorer and chrome, and not working at all. the only thing i have is this pice of code. have no error in browser console... im using angular cli.
what im doing wrong guys? please help.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});

    Name: <input ng-model="firstname">

{{firstname}}

SOURCE

Body:
This is second time, you posted same question. The potential reason for not working your code inside browser may be you are not adding the your script.js path correctly. Check your browser console and debug the issue. Your code seems fine.

Just copy and paste this code inside a .html file and open in browser. It should work.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
  var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});

</script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div>


问:
Python tkinter keeping window on top when focusing on another window
I'm making a text editor, and I have made a find/replace function with it's own window.
It looks like this. I want it to become transparent when changing back to the main text window, but stay there. (Like what notepad++ does).
As you can see here, the find window is in front of the main window but it is transparent.

I already know I can use this to make the window transparent:

```<code>find_window.attributes('-alpha', 0.3)
</code>```

But now I want it to stay on top while the focus is on the other window.

答:
I have figured it out myself. I had to use the focus_out event and then use .lift() to place it on top:</p>

```<code>def leave():
    find_window.attributes('-alpha', 0.3)
    find_window.lift()

find_window.bind('<FocusOut>', leave)
</code>```

Body:
I'm making a text editor, and I have made a find/replace function with it's own window.
It looks like this. I want it to become transparent when changing back to the main text window, but stay there. (Like what notepad++ does).
As you can see here, the find window is in front of the main window but it is transparent.

I already know I can use this to make the window transparent:

find_window.attributes('-alpha', 0.3)

But now I want it to stay on top while the focus is on the other window.

Body:
I have figured it out myself. I had to use the focus_out event and then use .lift() to place it on top:

def leave():
    find_window.attributes('-alpha', 0.3)
    find_window.lift()

find_window.bind('<FocusOut>', leave)


问:
Magento 2 Cannot redirect from admin controller to front end
I am trying to use this code to redirect to a frontend URL, but it always redirects to the admin dashboard. I searched for and tried a lot of demo code, but I can't get it to work. I assume all attributes were set correctly.</p>

```<code> $url= $this->_storeManager->getStore(1)->getUrl('storelocator/index/index');
 $resultRedirect = $this->resultRedirectFactory->create();
 $resultRedirect->setUrl($url);
 return $resultRedirect;
</code>```

答:
Here is a solution of getting storefront URL:</p>

```<code>/* @var \Magento\Framework\ObjectManagerInterface $objectManager */
/* @var \Magento\Store\Api\Data\StoreInterface $store */
$scopeResolver = $objectManager->create( 'Magento\Framework\Url\ScopeResolverInterface', [ 'areaCode' => \Magento\Framework\App\Area\Area::AREA_FRONTEND ] );
$url = $objectManager->create( 'Magento\Framework\Url', [ 'scopeResolver' => $scopeResolver ] )->setScope( $store )->getUrl( 'xxx/xxx/xxx', [ '_scope_to_url' => false, '_nosid' => true ] );
</code>```

Body:
I am trying to use this code to redirect to a frontend URL, but it always redirects to the admin dashboard. I searched for and tried a lot of demo code, but I can't get it to work. I assume all attributes were set correctly.

 $url= $this->_storeManager->getStore(1)->getUrl('storelocator/index/index');
 $resultRedirect = $this->resultRedirectFactory->create();
 $resultRedirect->setUrl($url);
 return $resultRedirect;

Body:
Here is a solution of getting storefront URL:

/* @var \Magento\Framework\ObjectManagerInterface $objectManager */
/* @var \Magento\Store\Api\Data\StoreInterface $store */
$scopeResolver = $objectManager->create( 'Magento\Framework\Url\ScopeResolverInterface', [ 'areaCode' => \Magento\Framework\App\Area\Area::AREA_FRONTEND ] );
$url = $objectManager->create( 'Magento\Framework\Url', [ 'scopeResolver' => $scopeResolver ] )->setScope( $store )->getUrl( 'xxx/xxx/xxx', [ '_scope_to_url' => false, '_nosid' => true ] );


问:
T-SQL | Better alternative to WHERE NOT EXISTS
I've the following query:

```<code>INSERT INTO [Table A]  ([student_name], [class_id],[contact_detail], [birth_date],[note_average])
            SELECT [student_name] = case when CHARINDEX('.', [student_name])>0 then LEFT([student_name],CHARINDEX('.', [student_name])-1)
                        else [student_name] end
                        ,[class_id]
                        ,case when reverse(SUBSTRING(REVERSE([contact_detail]),1,CHARINDEX(':', REVERSE([contact_detail])))) like ':'
                                        then ([contact_detail] + '|')
                                        else    [contact_detail]
                                        end as [contact_detail]
                         ,[birth_date]
                         ,CAST([note_average] AS decimal(13,2)) as [note_average]
                         ,GETDATE()
            FROM [Table A]
            WHERE CAST([birth_date] AS DATE) <= CAST(GETDATE() AS DATE)
                    AND LEN([student_name]) >= 5
                    AND NOT EXISTS
                            (
                      SELECT [student_name]
                                              ,[class_id]
                                              ,[contact_detail]
                                              ,[birth_date]
                      FROM [Table A]  a
                      WHERE  '%' + ods.[student_name] + '%' LIKE a.[student_name]
                                AND '%' +  ods.[class_id] + '%'  LIKE a.[class_id]
                                AND '%' + ods.[contact_detail] + '%' LIKE a.[contact_detail]
                                AND ods.[birth_date] = a.[birth_date]
                            )
GO
</code>```

I don't want to insert duplicate values and I don't have an key in my table. My problem is: this query is taking a lot of time to insert the new values. I'm trying to insert 1000000 rows.

Which alternatives I've?

Many thanks!

答:
Assuming you really want to match on exact duplicate matches, try something like this:

```<code>INSERT INTO [Table A]  ([student_name], [os_name], [class_id],[contact_detail], [birth_date],[note_average])
    SELECT ods.[student_name] = case when CHARINDEX('.', ods.[student_name])>0 then LEFT(ods.[student_name],CHARINDEX('.', ods.[student_name])-1)
            else ods.[student_name] end
        ,ods.[class_id]
        ,case when reverse(SUBSTRING(REVERSE(ods.[contact_detail]),1,CHARINDEX(':', REVERSE(ods.[contact_detail])))) like ':'
            then (ods.[contact_detail] + '|')
            else    ods.[contact_detail]
            end as [contact_detail]
         ,ods.[birth_date]
         ,CAST(ods.[note_average] AS decimal(13,2)) as ods.[note_average]
         ,GETDATE()
    FROM [Table A] ods
    OUTER JOIN [Table A] a ON ods.[student_name] = a.[student_name]
        AND ods.[os_name] = a.[os_name]
        AND ods.[class_id] = a.[class_id]
        AND ods.[contact_detail] = a.[contact_detail]
        AND ods.[birth_date] = a.[birth_date]
    WHERE CAST(ods.[birth_date] AS DATE) <= CAST(GETDATE() AS DATE)
        AND LEN(ods.[student_name]) >= 5
        -- Only include when no matching duplicate is found.
        AND a.[student_name] IS NULL
</code>```

You could stick with a sub-query and NOT EXISTS if you want and that would be fine as well but use SELECT 0 or similar instead of selecting all those columns, which isn't necessary.  Changing the comparisons from LIKE to = will, I believe, give you the results you want along with making the query optimizable with indexes, if necessary.

```<code>AND NOT EXISTS
(
  SELECT 0
  FROM [Table A]  a
  WHERE  ods.[student_name] = a.[student_name]
            AND ods.[os_name] = a.[os_name]
            AND ods.[class_id] = a.[class_id]
            AND ods.[contact_detail] = a.[contact_detail]
            AND ods.[birth_date] = a.[birth_date]
        )
</code>```

Once you have this query working correctly, then you can look at adding indexes if you need better performance.  You might be able to just add an index on [birth_date] or [student_name] to get acceptable query performance.

Body:
I've the following query:

INSERT INTO [Table A]  ([student_name], [class_id],[contact_detail], [birth_date],[note_average])
            SELECT [student_name] = case when CHARINDEX('.', [student_name])>0 then LEFT([student_name],CHARINDEX('.', [student_name])-1)
                        else [student_name] end
                        ,[class_id]
                        ,case when reverse(SUBSTRING(REVERSE([contact_detail]),1,CHARINDEX(':', REVERSE([contact_detail])))) like ':'
                                        then ([contact_detail] + '|')
                                        else    [contact_detail]
                                        end as [contact_detail]
                         ,[birth_date]
                         ,CAST([note_average] AS decimal(13,2)) as [note_average]
                         ,GETDATE()
            FROM [Table A]
            WHERE CAST([birth_date] AS DATE) <= CAST(GETDATE() AS DATE)
                    AND LEN([student_name]) >= 5
                    AND NOT EXISTS
                            (
                      SELECT [student_name]
                                              ,[class_id]
                                              ,[contact_detail]
                                              ,[birth_date]
                      FROM [Table A]  a
                      WHERE  '%' + ods.[student_name] + '%' LIKE a.[student_name]
                                AND '%' +  ods.[class_id] + '%'  LIKE a.[class_id]
                                AND '%' + ods.[contact_detail] + '%' LIKE a.[contact_detail]
                                AND ods.[birth_date] = a.[birth_date]
                            )
GO

I don't want to insert duplicate values and I don't have an key in my table. My problem is: this query is taking a lot of time to insert the new values. I'm trying to insert 1000000 rows.

Which alternatives I've?

Many thanks!

Body:
Assuming you really want to match on exact duplicate matches, try something like this:

INSERT INTO [Table A]  ([student_name], [os_name], [class_id],[contact_detail], [birth_date],[note_average])
    SELECT ods.[student_name] = case when CHARINDEX('.', ods.[student_name])>0 then LEFT(ods.[student_name],CHARINDEX('.', ods.[student_name])-1)
            else ods.[student_name] end
        ,ods.[class_id]
        ,case when reverse(SUBSTRING(REVERSE(ods.[contact_detail]),1,CHARINDEX(':', REVERSE(ods.[contact_detail])))) like ':'
            then (ods.[contact_detail] + '|')
            else    ods.[contact_detail]
            end as [contact_detail]
         ,ods.[birth_date]
         ,CAST(ods.[note_average] AS decimal(13,2)) as ods.[note_average]
         ,GETDATE()
    FROM [Table A] ods
    OUTER JOIN [Table A] a ON ods.[student_name] = a.[student_name]
        AND ods.[os_name] = a.[os_name]
        AND ods.[class_id] = a.[class_id]
        AND ods.[contact_detail] = a.[contact_detail]
        AND ods.[birth_date] = a.[birth_date]
    WHERE CAST(ods.[birth_date] AS DATE) <= CAST(GETDATE() AS DATE)
        AND LEN(ods.[student_name]) >= 5
        -- Only include when no matching duplicate is found.
        AND a.[student_name] IS NULL

You could stick with a sub-query and NOT EXISTS if you want and that would be fine as well but use SELECT 0 or similar instead of selecting all those columns, which isn't necessary.  Changing the comparisons from LIKE to = will, I believe, give you the results you want along with making the query optimizable with indexes, if necessary.

AND NOT EXISTS
(
  SELECT 0
  FROM [Table A]  a
  WHERE  ods.[student_name] = a.[student_name]
            AND ods.[os_name] = a.[os_name]
            AND ods.[class_id] = a.[class_id]
            AND ods.[contact_detail] = a.[contact_detail]
            AND ods.[birth_date] = a.[birth_date]
        )

Once you have this query working correctly, then you can look at adding indexes if you need better performance.  You might be able to just add an index on [birth_date] or [student_name] to get acceptable query performance.


问:
Resource naming reference
In my android app, I have 9 buttons with the following reference:

```<code>R.id.button1;
R.id.button2;
....
R.id.button9
</code>```

If I have an int value, lets say int i which holds the button number, is there a simple way for me to call the reference such as

```<code>String s = "R.id.button" + Integer.toString(i);
Button btn = (Button) findViewbyId(s);
</code>```

My code is gettting way to verbose by doing 9 if checks. Thanks!

答:
You can try like this to get the Button Object from String value,</p>

```<code>String s = "button" + i;
int viewId = getResources().getIdentifier( s, "id", getPackageName());

Button btn = (Button) findViewById(viewId);
</code>```

Title: Resource naming reference

Body:
In my android app, I have 9 buttons with the following reference:

R.id.button1;
R.id.button2;
....
R.id.button9

If I have an int value, lets say int i which holds the button number, is there a simple way for me to call the reference such as

String s = "R.id.button" + Integer.toString(i);
Button btn = (Button) findViewbyId(s);

My code is gettting way to verbose by doing 9 if checks. Thanks!

Body:
You can try like this to get the Button Object from String value,

String s = "button" + i;
int viewId = getResources().getIdentifier( s, "id", getPackageName());

Button btn = (Button) findViewById(viewId);


问:
create function sql server 2005 disable errors

I'm trying to write a *.bat file which runs all sql-scripts in given folder (every file in this folder has a create function script):

```<code>for /r "%~dp0\Production\Functions" %%X in (*.sql) do (
   sqlcmd -S%1 -d%2 -b -i "%%X"
)
</code>```

But some functions in the folder are depended on others. So I get Invalid object name error. Is there a way to disable this error?

答: Rename your files so that they're listed in the correct order of precedence. So, for example, if FuncA.sql uses FuncB.sql, then rename the files as 001-FuncB.sql, 002-FuncA.sql.

Body:
I'm trying to write a *.bat file which runs all sql-scripts in given folder (every file in this folder has a create function script):

for /r "%~dp0\Production\Functions" %%X in (*.sql) do (
   sqlcmd -S%1 -d%2 -b -i "%%X"
)

But some functions in the folder are depended on others. So I get Invalid object name error. Is there a way to disable this error?


问:
Checking value from previous form in ASP .NET, using jQuery
I writing a method that check values in the current page along with one value from the previouse page. I use jQuery for writing the check as following

```<code>function check_Finalized() {
        myTest();
        var Finalized_value = document.createElement("INPUT");
        Finalized_value.type = "hidden";
        Finalized_value.name = "Finalized_value";

        if (((document.getElementById("ContentPlaceHolder1_txtFinalized") != null) && (document.getElementById("ContentPlaceHolder1_txtFinalized").value != "") && (document.getElementById("ContentPlaceHolder1_ddlResponsibility").value=="2") &&document.getElementById("ContentPlaceHolder1_chkSD").value =="checked"))

        {
            // document.getElementById("ContentPlaceHolder1_chkSD").value =="checked") &&
            if (confirm("Remember to forward finalisation email to Study Director" + "\n" + " You are shortly to receive the email in outlook")) {
                Finalized_value.value = "OK";
            } else {
                Finalized_value.value = "No";
            }
        }
       else
            Finalized_value.value = "OK";

        document.forms[0].appendChild(Finalized_value);
    }
</code>```

Where (document.getElementById("ContentPlaceHolder1_chkSD").value =="checked")) is the value checked from the previous page.

Body:
I writing a method that check values in the current page along with one value from the previouse page. I use jQuery for writing the check as following

function check_Finalized() {
        myTest();
        var Finalized_value = document.createElement("INPUT");
        Finalized_value.type = "hidden";
        Finalized_value.name = "Finalized_value";

        if (((document.getElementById("ContentPlaceHolder1_txtFinalized") != null) && (document.getElementById("ContentPlaceHolder1_txtFinalized").value != "") && (document.getElementById("ContentPlaceHolder1_ddlResponsibility").value=="2") &&document.getElementById("ContentPlaceHolder1_chkSD").value =="checked"))

        {
            // document.getElementById("ContentPlaceHolder1_chkSD").value =="checked") &&
            if (confirm("Remember to forward finalisation email to Study Director" + "\n" + " You are shortly to receive the email in outlook")) {
                Finalized_value.value = "OK";
            } else {
                Finalized_value.value = "No";
            }
        }
       else
            Finalized_value.value = "OK";

        document.forms[0].appendChild(Finalized_value);
    }

Where (document.getElementById("ContentPlaceHolder1_chkSD").value =="checked")) is the value checked from the previous page.

Body:
Try,

document.querySelectorAll("[id$=chkSD]")


问:
Exclude fields serializing using Groovy JsonOutput
How to exclude specific fields from being serialized when using the JsonOutput.toJson(..) in groovy?

Given class:

```<code>class Dummy {
  String f1
  transient String f2
}
</code>```

Code:

```<code>// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json
</code>```

Will result in:

```<code>{"f1":"hello", "f2":"world"}
</code>```

Should result in:

```<code>{"f1":"hello"}
</code>```

答:
All properties as per the definition of Groovy are taken.
You could e. g. make the getter inoperable like

```<code>class Dummy {
  String f1
  String f2
  def getF2() {
    throw new RuntimeException()
  }
}

groovy.json.JsonOutput.toJson(new Dummy(f1: "hello", f2: "world"))
</code>```

which will return {"f1":"hello"}

Body:
How to exclude specific fields from being serialized when using the JsonOutput.toJson(..) in groovy?

Given class:

class Dummy {
  String f1
  transient String f2
}

Code:

// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json

Will result in:

{"f1":"hello", "f2":"world"}

Should result in:

{"f1":"hello"}

Body:
All properties as per the definition of Groovy are taken.
You could e. g. make the getter inoperable like

class Dummy {
  String f1
  String f2
  def getF2() {
    throw new RuntimeException()
  }
}

groovy.json.JsonOutput.toJson(new Dummy(f1: "hello", f2: "world"))

which will return {"f1":"hello"}


问:
Jest manual mocking works only for the first function call
I've mocked a custom XHR wrapper that I've written (utils/xhr.js) using Jest manual mocking feature and the issue that I'm having is that only the first XHR call is tracked:

utils/xhr.js

```<code>let xhr = {
    get: function(params) { /* XHR get implementation */ }
    post: function(params) { /* XHR post implementation */ }
};

export default xhr;
</code>```

utils/__mocks__/xhr.js - the mock implementation

```<code>let xhr = jest.genMockFromModule('./../xhr');

module.exports = xhr;
</code>```

Dashboard.api.js - the XHR calls for the dashboard component

```<code>// ...

getTrendingEntities: (days, maxItems) => {

    return xhr.get({url: '/api/aggregator/riskEntities/' +  days + '/' + maxItems})
        .then((response) => {
            companyIds = parseCompanies(response.body);

            return xhr.post({
                url: '/api/entities/specific-companies',
                data: companyIds
            });

        }).then((response) => {
            let companies = parseCompaniesData(response.body);

            return Promise.resolve(companies);
        });
}

// ...
</code>```

TrendingEntitiesPod.jsx - the React component that uses Dashboard.api.js

```<code>class TrendingEntitiesPod extends React.Component {

    // ...

    componentWillMount() {
        this.loadData(this.props.days)
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.days != nextProps.days) {
            this.loadData(nextProps.days);
        }
    }

    loadData(days) {
        this.setState({loading: true});

        api.getTrendingEntities(days, DASHBOARD_PODS_ENTRIES_NUMBER)
            .then((companies) => {
                this.setState({
                    companies: companies,
                    loading:   false
                });
            });
    }

    render() { // ... }

}
</code>```

StartPage.TrendingEntitiesPod.spec.js - the test file

```<code>import React from 'react';
import { mount } from 'enzyme';

import xhr from './../../../utils/xhr';
jest.mock('./../../../utils/xhr');

import TrendingEntitiesPod from './../Dashboard/components/TrendingEntitiesPod/TrendingEntitiesPod.jsx';

describe('StartPage.TrendingEntitiesPod:', () => {

    let wrapper = null;

    beforeAll(() => {
        xhr.get.mockReturnValueOnce(Promise.resolve({body: trendingEntities}));
        xhr.post.mockReturnValueOnce(Promise.resolve({body: trendingEntitiesData}));
        xhr.get.mockReturnValue(Promise.resolve({body: trendingEntityPestleData}));

        wrapper = mount(<TrendingEntitiesPod days={30} />);

    });

    test('...stubbing works', () => {
        expect(xhr.get.mock.calls.length).toBe(1);
        expect(xhr.post.mock.calls.length).toBe(1); // returns false - why??
    });

});
</code>```

答:
It seems that mounting with Enzyme a component that does multiple AJAX calls and multiple state changes, in the components' first lifecycle phases, makes the unit tests run first and afterwards the state changes are reflected.

This is due to the asynchronous nature of the AJAX and setState() calls.

A fix that I found for this is to add a done callback in the beforeAll block which finishes on setTimeout(done, 0):

```<code>beforeAll((done) => {
    xhr.get.mockReturnValueOnce(Promise.resolve({body: trendingEntities}));
    xhr.post.mockReturnValueOnce(Promise.resolve({body: trendingEntitiesData}));
    xhr.get.mockReturnValue(Promise.resolve({body: trendingEntityPestleData}));

    wrapper = mount(<TrendingEntitiesPod days={30} />);

    // Delay the execution of tests, at the end, after the component
    // has been mounted, all XHR, setState and render calls are done.
    setTimeout(done, 0);
});
</code>```

Body:
I've mocked a custom XHR wrapper that I've written (utils/xhr.js) using Jest manual mocking feature and the issue that I'm having is that only the first XHR call is tracked:

utils/xhr.js

let xhr = {
    get: function(params) { /* XHR get implementation */ }
    post: function(params) { /* XHR post implementation */ }
};

export default xhr;

utils/__mocks__/xhr.js - the mock implementation

let xhr = jest.genMockFromModule('./../xhr');

module.exports = xhr;

Dashboard.api.js - the XHR calls for the dashboard component

// ...

getTrendingEntities: (days, maxItems) => {

    return xhr.get({url: '/api/aggregator/riskEntities/' +  days + '/' + maxItems})
        .then((response) => {
            companyIds = parseCompanies(response.body);

            return xhr.post({
                url: '/api/entities/specific-companies',
                data: companyIds
            });

        }).then((response) => {
            let companies = parseCompaniesData(response.body);

            return Promise.resolve(companies);
        });
}

// ...

TrendingEntitiesPod.jsx - the React component that uses Dashboard.api.js

class TrendingEntitiesPod extends React.Component {

    // ...

    componentWillMount() {
        this.loadData(this.props.days)
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.days != nextProps.days) {
            this.loadData(nextProps.days);
        }
    }

    loadData(days) {
        this.setState({loading: true});

        api.getTrendingEntities(days, DASHBOARD_PODS_ENTRIES_NUMBER)
            .then((companies) => {
                this.setState({
                    companies: companies,
                    loading:   false
                });
            });
    }

    render() { // ... }

}

StartPage.TrendingEntitiesPod.spec.js - the test file

import React from 'react';
import { mount } from 'enzyme';

import xhr from './../../../utils/xhr';
jest.mock('./../../../utils/xhr');

import TrendingEntitiesPod from './../Dashboard/components/TrendingEntitiesPod/TrendingEntitiesPod.jsx';

describe('StartPage.TrendingEntitiesPod:', () => {

    let wrapper = null;

    beforeAll(() => {
        xhr.get.mockReturnValueOnce(Promise.resolve({body: trendingEntities}));
        xhr.post.mockReturnValueOnce(Promise.resolve({body: trendingEntitiesData}));
        xhr.get.mockReturnValue(Promise.resolve({body: trendingEntityPestleData}));

        wrapper = mount(<TrendingEntitiesPod days={30} />);

    });

    test('...stubbing works', () => {
        expect(xhr.get.mock.calls.length).toBe(1);
        expect(xhr.post.mock.calls.length).toBe(1); // returns false - why??
    });

});

Body:
It seems that mounting with Enzyme a component that does multiple AJAX calls and multiple state changes, in the components' first lifecycle phases, makes the unit tests run first and afterwards the state changes are reflected.

This is due to the asynchronous nature of the AJAX and setState() calls.

A fix that I found for this is to add a done callback in the beforeAll block which finishes on setTimeout(done, 0):

beforeAll((done) => {
    xhr.get.mockReturnValueOnce(Promise.resolve({body: trendingEntities}));
    xhr.post.mockReturnValueOnce(Promise.resolve({body: trendingEntitiesData}));
    xhr.get.mockReturnValue(Promise.resolve({body: trendingEntityPestleData}));

    wrapper = mount(<TrendingEntitiesPod days={30} />);

    // Delay the execution of tests, at the end, after the component
    // has been mounted, all XHR, setState and render calls are done.
    setTimeout(done, 0);
});


问:
Sum two input values in realtime
I want to sum two different inputs in a third realtime variable. I will explain better what I want:

1 variable : 100 (input)

2 variable : 150 (input)

sum : 250 (not input)

How can I do this?

答:
For realtime operations that is based on the client side events are managed by JavaScript and not PHP, which is server side. So to do something like what you wanted, we can use a keyboard event like keyup and make the third one readonly:

$(function () {
  $("#id-1, #id-2").keyup(function () {
    $("#id-3").val(+$("#id-1").val() + +$("#id-2").val());
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="id-1" />
<input type="number" id="id-2" />
<input type="number" id="id-3" readonly /></code>```

Title: Sum two input values in realtime

Body:
For realtime operations that is based on the client side events are managed by JavaScript and not PHP, which is server side. So to do something like what you wanted, we can use a keyboard event like keyup and make the third one readonly:

$(function () {
  $("#id-1, #id-2").keyup(function () {
    $("#id-3").val(+$("#id-1").val() + +$("#id-2").val());
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="id-1" />
<input type="number" id="id-2" />
<input type="number" id="id-3" readonly />


答:
Although the comments already gives the correct answer, here a more detailed explanation:

Your are right that the ?? operator will take the left operand it its value is not null. Otherwise it will take the right operand. It is essential a short version for:

```<code>var qty = input == null ? "0" : input;
</code>```

However the exception is not thrown by the assignment. The exception is thrown by the call to ToString().

If your input is null your statement equals the following:

```<code>var qty = ((object)null).ToString();
</code>```

Which obviously throws a NullReferenceException.

Solution:

What you are looking for is the ?. operator. Which says "call the function if the object is not null". This expands into the following:

```<code>input != null ? input.ToString() : null
// is equal to
input?.ToString()
</code>```

So the solution for the assignment should be a combination of the two operators:

```<code>var qty = input?.ToString() ?? "0";
</code>```

Title: C# 6.0 null-coalescing not working correctly for me

Body:
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?

  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";

Body:
Although the comments already gives the correct answer, here a more detailed explanation:

Your are right that the ?? operator will take the left operand it its value is not null. Otherwise it will take the right operand. It is essential a short version for:

var qty = input == null ? "0" : input;

However the exception is not thrown by the assignment. The exception is thrown by the call to ToString().

If your input is null your statement equals the following:

var qty = ((object)null).ToString();

Which obviously throws a NullReferenceException.

Solution:

What you are looking for is the ?. operator. Which says "call the function if the object is not null". This expands into the following:

input != null ? input.ToString() : null
// is equal to
input?.ToString()

So the solution for the assignment should be a combination of the two operators:

var qty = input?.ToString() ?? "0";


问:
Good languages to write a compiler for
I'm thinking of writing a compiler in haskell, and just to gain some knowledge and experience, I will try to implement compilers for existing languages. Could someone give me a list of languages which are suitable for this?

Thanks in advance

答: Scheme is often used for this. There's even a tutorial called Write Yourself a Scheme in 48 hours for Haskell.

Title: Good languages to write a compiler for


问:
adding custom SOAP header request
Please I need help to add the following header to my SOAP request in C# ASP.net web application

```<code>    <wata:auth xmlns:wata="http://osb.wata.com">
       <username>username</username>
       <password>password</password>
    </wata:auth>
</code>```

please note the tag should be the same  and already i tried to add this header by inheriting form Microsoft.Web.Service3.WebServicesClientProtocol but this will not work because the tag is different  .

The service call look like the following generated using WSDL definition

```<code>    service.ServiceProxy check = new service.ServiceProxy();
    check.checkPostService(serviceId);
</code>```

Thanks

答:
You can add SOAP headers programmatically using the following :</p>

```<code>service.ServiceProxy check = new service.ServiceProxy();

using (new OperationContextScope(check.InnerChannel))
{
      var usernameHeader = MessageHeader.CreateHeader("username", string.Empty, _username);
      OperationContext.Current.OutgoingMessageHeaders.Add(usernameHeader);
      var passwordHeader = MessageHeader.CreateHeader("password", string.Empty, _passowrd);
      OperationContext.Current.OutgoingMessageHeaders.Add(passwordHeader);

      check.checkPostService(serviceId);
}
</code>```

Title: adding custom SOAP header request

Body:
Please I need help to add the following header to my SOAP request in C# ASP.net web application

    <wata:auth xmlns:wata="http://osb.wata.com">
       <username>username</username>
       <password>password</password>
    </wata:auth>

please note the tag should be the same  and already i tried to add this header by inheriting form Microsoft.Web.Service3.WebServicesClientProtocol but this will not work because the tag is different  .

The service call look like the following generated using WSDL definition

    service.ServiceProxy check = new service.ServiceProxy();
    check.checkPostService(serviceId);

Thanks

Body:
You can add SOAP headers programmatically using the following :

service.ServiceProxy check = new service.ServiceProxy();

using (new OperationContextScope(check.InnerChannel))
{
      var usernameHeader = MessageHeader.CreateHeader("username", string.Empty, _username);
      OperationContext.Current.OutgoingMessageHeaders.Add(usernameHeader);
      var passwordHeader = MessageHeader.CreateHeader("password", string.Empty, _passowrd);
      OperationContext.Current.OutgoingMessageHeaders.Add(passwordHeader);

      check.checkPostService(serviceId);
}