问:
How to parse the individual items from this XML result
I am loading the XML that comes from this Google News URL:

The result is:

```<code><rss version="2.0"><channel><generator>NFE/1.0</generator><title>"birch" - Google News</title><link>https://news.google.com/news?hl=en&pz=1&ned=uk&q=%5Cx22birch%5Cx22</link><language>en-GB</language><webMaster>news-feedback@google.com</webMaster><copyright>©2017 Google</copyright><pubDate>Sun, 09 Jul 2017 15:30:02 GMT</pubDate><lastBuildDate>Sun, 09 Jul 2017 15:30:02 GMT</lastBuildDate><image><title>"birch" - Google News</title><url>https://ssl.gstatic.com/news-static/img/logo/en_uk/news.gif</url><link>https://news.google.com/news?hl=en&pz=1&ned=uk&q=%5Cx22birch%5Cx22</link></image><item><title>Why Birch Water Is The New Beauty Ingredient You Need To Know - Refinery29</title><link>http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNFVyvekSpSA-H1CkHd74v6_mAs60w&clid=c3a7d30bb8a4878e06b80cf16b898331&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.refinery29.uk/birch-water-beauty-benefits</link><guid isPermaLink="false">tag:news.google.com,2005:cluster=http://www.refinery29.uk/birch-water-beauty-benefits</guid><pubDate>Wed, 05 Jul 2017 07:09:16 GMT</pubDate><description><table border="0" cellpadding="2" cellspacing="7" style="vertical-align:top;"><tr><td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNFVyvekSpSA-H1CkHd74v6_mAs60w&clid=c3a7d30bb8a4878e06b80cf16b898331&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.refinery29.uk/birch-water-beauty-benefits"><img src="//t0.gstatic.com/images?q=tbn:ANd9GcRnLZw3tqOQnwtqioj-xl56DSiweOwGyk-lvEwAt8xipD9O6bw5agzjJi1OO58TfM1UY2z9d9V2" alt="" border="1" width="80" height="80"><br><font size="-2">Refinery29</font></a></font></td><td valign="top" class="j"><font style="font-size:85%;font-family:arial,sans-serif"><br><div style="padding-top:0.8em;"><img alt="" height="1" width="1"></div><div class="lh"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNFVyvekSpSA-H1CkHd74v6_mAs60w&clid=c3a7d30bb8a4878e06b80cf16b898331&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.refinery29.uk/birch-water-beauty-benefits"><b>Why <b>Birch</b> Water Is The New Beauty Ingredient You Need To Know</b></a><br><font size="-1"><b><font color="#6f6f6f">Refinery29</font></b></font><br><font size="-1">Not just the source of one of the more questionable new wellness drinks, <b>birch</b> trees are also trending in the world of skincare. Often referred to as the tree of life, <b>birch</b> is found across northern Europe, particularly in Scandinavia, and has been <b>...</b></font><br><font size="-1" class="p"></font><br><font class="p" size="-1"><a class="p" href="http://news.google.com/news/more?ncl=dSsgf_hNiR1IBhM&authuser=0&ned=uk"><nobr><b></b></nobr></a></font></div></font></td></tr></table></description></item><item><title>Recycling Lives' takeover of scrap metal site L&D Mortimer site on ... - Bury Times</title><link>http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNH7tJ4QbojCmGT5ZZo29j5upz0xeQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779549822946&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.burytimes.co.uk/news/15396732.Takeover_of_scrap_metal_site_will_save_and_create_jobs/</link><guid isPermaLink="false">tag:news.google.com,2005:cluster=http://www.burytimes.co.uk/news/15396732.Takeover_of_scrap_metal_site_will_save_and_create_jobs/</guid><pubDate>Sat, 08 Jul 2017 06:03:26 GMT</pubDate><description><table border="0" cellpadding="2" cellspacing="7" style="vertical-align:top;"><tr><td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNH7tJ4QbojCmGT5ZZo29j5upz0xeQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779549822946&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.burytimes.co.uk/news/15396732.Takeover_of_scrap_metal_site_will_save_and_create_jobs/"><img src="//t3.gstatic.com/images?q=tbn:ANd9GcRLzihFeSA1g11dR0H1T3v3nuWT7pQ0ss7urR_21uO0AhuW23gHhA4nTUMo_vZaAgAZ7j9L5Nk-" alt="" border="1" width="80" height="80"><br><font size="-2">Bury Times</font></a></font></td><td valign="top" class="j"><font style="font-size:85%;font-family:arial,sans-serif"><br><div style="padding-top:0.8em;"><img alt="" height="1" width="1"></div><div class="lh"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNH7tJ4QbojCmGT5ZZo29j5upz0xeQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779549822946&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.burytimes.co.uk/news/15396732.Takeover_of_scrap_metal_site_will_save_and_create_jobs/"><b>Recycling Lives' takeover of scrap metal site L&D Mortimer site on ...</b></a><br><font size="-1"><b><font color="#6f6f6f">Bury Times</font></b></font><br><font size="-1">AN award-winning social business has moved in – both saving and creating jobs.</font><br><font size="-1" class="p"></font><br><font class="p" size="-1"><a class="p" href="http://news.google.com/news/more?ncl=d-Kqhhcau4k19TM&authuser=0&ned=uk"><nobr><b>and more »</b></nobr></a></font></div></font></td></tr></table></description></item><item><title>Bacteria closes Dartmouth's Birch Cove Beach | The Chronicle Herald - TheChronicleHerald.ca</title><link>http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNHidwNRYJY0vVolosZbesiAkOMpSQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779548150492&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://thechronicleherald.ca/metro/1483620-bacteria-closes-dartmouth%25E2%2580%2599s-birch-cove-beach</link><guid isPermaLink="false">tag:news.google.com,2005:cluster=http://thechronicleherald.ca/metro/1483620-bacteria-closes-dartmouth%E2%80%99s-birch-cove-beach</guid><pubDate>Wed, 05 Jul 2017 15:26:00 GMT</pubDate><description><table border="0" cellpadding="2" cellspacing="7" style="vertical-align:top;"><tr><td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNGMvNI3ZSUFTfUWD6ia0_HcE3gz-A&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779548150492&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.metronews.ca/news/halifax/2017/07/05/dartmouth-beach-closed-swimming-high-bacteria.html"><img src="//t3.gstatic.com/images?q=tbn:ANd9GcSuM4Lbx1eh7UOr69MB6KAkq5WMI-e3z6loUwqIBzCB_soiJly7oj33gwYTcB8F9QmZvKnZ6EqM" alt="" border="1" width="80" height="80"><br><font size="-2">MetroNews Canada</font></a></font></td><td valign="top" class="j"><font style="font-size:85%;font-family:arial,sans-serif"><br><div style="padding-top:0.8em;"><img alt="" height="1" width="1"></div><div class="lh"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNHidwNRYJY0vVolosZbesiAkOMpSQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779548150492&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://thechronicleherald.ca/metro/1483620-bacteria-closes-dartmouth%25E2%2580%2599s-birch-cove-beach"><b>Bacteria closes Dartmouth's Birch Cove Beach | The Chronicle Herald</b></a><br><font size="-1"><b><font color="#6f6f6f">TheChronicleHerald.ca</font></b></font><br><font size="-1">Birch Cove Beach is closed due to high bacteria levels in the water. Halifax Regional Municipality is advising residents not to swim at the beach until further ...</font><br><font size="-1"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNGMvNI3ZSUFTfUWD6ia0_HcE3gz-A&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779548150492&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.metronews.ca/news/halifax/2017/07/05/dartmouth-beach-closed-swimming-high-bacteria.html">Dartmouth beach closed to swimming over high bacteria levels ...</a><font size="-1" color="#6f6f6f"><nobr>MetroNews Canada</nobr></font></font><br><font size="-1" class="p"></font><br><font class="p" size="-1"><a class="p" href="http://news.google.com/news/more?ncl=dvqw0clrahi5WqMQEdCYeTwyz0taM&authuser=0&ned=uk"><nobr><b>all 2 news articles »</b></nobr></a></font></div></font></td></tr></table></description></item><description>Google News</description></channel></rss>
</code>```

I'd like to extract each item.

```<code>string url = "https://news.google.com/news?pz=1&cf=all&ned=uk&hl=en&q=/"birch/"&cf=all&output=rss"

XmlDocument doc = new XmlDocument();
doc.Load(url);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("item")

foreach (XmlNode node in nodes)
{
    // do stuff
}
</code>```

but I can't seem to access each item URL?

Any suggestions?

答:
You can use System.Xml.Linq

The following code worked for me.

```<code>XDocument xDoc = XDocument.Load(@"Filepath/XMLFile1.xml");
List<XElement> LXElement = xDoc.Root.Element("channel").Elements("item").ToList();

foreach (XElement iElement in LXElement)
{
    Console.WriteLine(iElement.Element("title").Value);
    Console.WriteLine(iElement.Element("link").Value);
    Console.WriteLine(iElement.Element("guid").Value);
    Console.WriteLine(iElement.Element("pubDate").Value);
    Console.WriteLine(iElement.Element("description").Value);
}
</code>```

Body:
I am loading the XML that comes from this Google News URL:

The result is:

<rss version="2.0"><channel><generator>NFE/1.0</generator><title>"birch" - Google News</title><link>https://news.google.com/news?hl=en&pz=1&ned=uk&q=%5Cx22birch%5Cx22</link><language>en-GB</language><webMaster>news-feedback@google.com</webMaster><copyright>&copy;2017 Google</copyright><pubDate>Sun, 09 Jul 2017 15:30:02 GMT</pubDate><lastBuildDate>Sun, 09 Jul 2017 15:30:02 GMT</lastBuildDate><image><title>"birch" - Google News</title><url>https://ssl.gstatic.com/news-static/img/logo/en_uk/news.gif</url><link>https://news.google.com/news?hl=en&pz=1&ned=uk&q=%5Cx22birch%5Cx22</link></image><item><title>Why Birch Water Is The New Beauty Ingredient You Need To Know - Refinery29</title><link>http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNFVyvekSpSA-H1CkHd74v6_mAs60w&clid=c3a7d30bb8a4878e06b80cf16b898331&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.refinery29.uk/birch-water-beauty-benefits</link><guid isPermaLink="false">tag:news.google.com,2005:cluster=http://www.refinery29.uk/birch-water-beauty-benefits</guid><pubDate>Wed, 05 Jul 2017 07:09:16 GMT</pubDate><description>

Refinery29

Why Birch Water Is The New Beauty Ingredient You Need To Know
Refinery29
Not just the source of one of the more questionable new wellness drinks, birch trees are also trending in the world of skincare. Often referred to as the tree of life, birch is found across northern Europe, particularly in Scandinavia, and has been ...

<nobr></nobr>

</description></item><item><title>Recycling Lives' takeover of scrap metal site L&D Mortimer site on ... - Bury Times</title><link>http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNH7tJ4QbojCmGT5ZZo29j5upz0xeQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779549822946&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://www.burytimes.co.uk/news/15396732.Takeover_of_scrap_metal_site_will_save_and_create_jobs/</link><guid isPermaLink="false">tag:news.google.com,2005:cluster=http://www.burytimes.co.uk/news/15396732.Takeover_of_scrap_metal_site_will_save_and_create_jobs/</guid><pubDate>Sat, 08 Jul 2017 06:03:26 GMT</pubDate><description>

Bury Times

Recycling Lives&#39; takeover of scrap metal site L&amp;D Mortimer site on ...
Bury Times
AN award-winning social business has moved in – both saving and creating jobs.

<nobr>and more&nbsp;&raquo;</nobr>

</description></item><item><title>Bacteria closes Dartmouth's Birch Cove Beach | The Chronicle Herald - TheChronicleHerald.ca</title><link>http://news.google.com/news/url?sa=t&fd=R&ct2=uk&usg=AFQjCNHidwNRYJY0vVolosZbesiAkOMpSQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52779548150492&ei=-UtiWbGZHIrkhAGMmrDYBw&url=http://thechronicleherald.ca/metro/1483620-bacteria-closes-dartmouth%25E2%2580%2599s-birch-cove-beach</link><guid isPermaLink="false">tag:news.google.com,2005:cluster=http://thechronicleherald.ca/metro/1483620-bacteria-closes-dartmouth%E2%80%99s-birch-cove-beach</guid><pubDate>Wed, 05 Jul 2017 15:26:00 GMT</pubDate><description>

MetroNews Canada

Bacteria closes Dartmouth&#39;s Birch Cove Beach | The Chronicle Herald
TheChronicleHerald.ca
Birch Cove Beach is closed due to high bacteria levels in the water. Halifax Regional Municipality is advising residents not to swim at the beach until further&nbsp;...
Dartmouth beach closed to swimming over high bacteria levels ...<nobr>MetroNews Canada</nobr>

<nobr>all 2 news articles&nbsp;&raquo;</nobr>

</description></item><description>Google News</description></channel></rss>

I'd like to extract each item.

string url = "https://news.google.com/news?pz=1&cf=all&ned=uk&hl=en&q=/"birch/"&cf=all&output=rss"

XmlDocument doc = new XmlDocument();
doc.Load(url);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("item")

foreach (XmlNode node in nodes)
{
    // do stuff
}

but I can't seem to access each item URL?

Any suggestions?

Body:
You can use System.Xml.Linq

The following code worked for me.

XDocument xDoc = XDocument.Load(@"Filepath/XMLFile1.xml");
List<XElement> LXElement = xDoc.Root.Element("channel").Elements("item").ToList();

foreach (XElement iElement in LXElement)
{
    Console.WriteLine(iElement.Element("title").Value);
    Console.WriteLine(iElement.Element("link").Value);
    Console.WriteLine(iElement.Element("guid").Value);
    Console.WriteLine(iElement.Element("pubDate").Value);
    Console.WriteLine(iElement.Element("description").Value);
}


来源: stackexchange

问:
Set Custom Coordinates to a function, Waze Integration
I'm trying to implement navigation using Waze in my App, using their own API: here.

I want to set in custom coordinates that are set in an array
and then fit them in this code:

```<code>func navigate(toLatitude latitude: Double , longitude: Double) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }
</code>```

i have tried settings up different type of arrays but didn't succeed to make it work . So if you could help me out set custom array holding latitude and longitude that would work properly with the code, that would be awesome

your help will be very much helpful,

Thank you in advance.

答:
To Create custom array for holding lat and long :

```<code>NSMutableArray *latLongArray = [[NSMutableArray alloc]init];
[latLongArray addObject :[NSDictionary dictionaryWithObjectsAndKeys:lat,@"latitude",long,@"longitude",nil]];
[latLongArray addObject :[NSDictionary dictionaryWithObjectsAndKeys:lat,@"latitude",long,@"longitude",nil]];
[latLongArray addObject :[NSDictionary dictionaryWithObjectsAndKeys:lat,@"latitude",long,@"longitude",nil]];
</code>```

Substitute lat long values.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement navigation using Waze in my App, using their own API: here.

I want to set in custom coordinates that are set in an array
and then fit them in this code:

func navigate(toLatitude latitude: Double , longitude: Double) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }

i have tried settings up different type of arrays but didn't succeed to make it work . So if you could help me out set custom array holding latitude and longitude that would work properly with the code, that would be awesome

your help will be very much helpful,

Thank you in advance.

Body:
To Create custom array for holding lat and long :

NSMutableArray *latLongArray = [[NSMutableArray alloc]init];
[latLongArray addObject :[NSDictionary dictionaryWithObjectsAndKeys:lat,@"latitude",long,@"longitude",nil]];
[latLongArray addObject :[NSDictionary dictionaryWithObjectsAndKeys:lat,@"latitude",long,@"longitude",nil]];
[latLongArray addObject :[NSDictionary dictionaryWithObjectsAndKeys:lat,@"latitude",long,@"longitude",nil]];

Substitute lat long values.


问:
if error == nil parse swift
I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks

Option #1

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}
</code>```

Option #2

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}
</code>```

Option #3

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}
</code>```

答: There should never be an error when the save operation succeeds, as a general rule of thumb, it depends on the next steps of your implementation. None of the approach is invalid, i would still recommend that you check the ‘happy value’, object, succeed dtc... before checking the error</p>

Title: if error == nil parse swift

Body:
I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks

Option #1

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}

Option #2

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}

Option #3

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}


问:
IdeaVim with Jupyter Notebook on PyCharm
I am trying out IntelliJ. I have installed the Python plugin, and IdeaVim.

I cannot navigate properly across Jupyter Notebook cells using hj. I mean, on normal mode, I cannot go to the next (or previous) cell, even if there is one, using hj.

Is there a way to do it without the mouse, possibly rebindable? I have read the tutorial and tried to find something in the program, but could not.

答:
Ideavim plugin doesn't seem to support Pycharm's notebook implementation as of right now :(

There's an open issue marked as "bug" on Ideavim's issue tracker that was opened back in 2015 and it seems like it doesn't have any progress made since.

However according to the comment in the issue thread you can:

funny way to get into the command mode is type something so that the suggestion panel appears, now press "esc" you will get into Vim command mode

So this might indicate that this could be solved and updated in the future.

As an alternative you can try out jupyter-vim-binding, however it doesn't work with Pycharm either.


问:
Cannot find source of small memory leak
I created a program that can solve sudoku puzzles in C++ using a brute force backtracking algorithm, however after analyzing the memory usage in valgrind I noticed that it has a small leak. I am aware of a GCC bug that accounts for 1 missed free and 72,704 bytes that are still reachable.

It seems that I am missing 903 free() / delete / delete[] calls that accounts for around 100KB of memory.

Does anyone know what is causing the memory leak and how I can fix it?

Backtracker.cpp

```<code>#include "Backtracker.h"

/**
 * Clears all dynamic memory in the list.
 * @param lst: the pointer to the list to be cleared
 */
static void clearList(std::list<Grid*> *lst) {
    std::list<Grid*>::iterator it;
    for (unsigned int i = 0; i < lst->size(); i++) {
        it = lst->begin();
        std::advance(it, i);
        delete *it;
    }
    delete lst;
}

/**
 * Solves the sudoku puzzle or returns a null if there is no solution.
 * @param g: a pointer to the starting grid
 * @return: a pointer to the solution
 */
Grid* solve(Grid *g) {
    if (g->isGoal()) {
        return g;
    }

    std::list<Grid*> *successors = g->getSuccessors();
    std::list<Grid*>::iterator it;

    for (unsigned int i = 0; i < successors->size(); i++) {
        it = successors->begin();
        std::advance(it, i);

        if ((*it)->isValid()) {
            Grid *solution = solve(*it);
            if (solution != nullptr) {
                solution = solution->copyGrid();
                clearList(successors);
                return solution;
            }
        }
    }
    clearList(successors);

    return nullptr;
}`
</code>```

Grid.cpp

```<code>#include "Grid.h"

/**
 * Constructor for the Grid class.
 */
Grid::Grid() {
    grid = new int*[SIZE];

    for (int i = 0; i < SIZE; i++) {
        grid[i] = new int[SIZE];
    }

    currRow = 0;
    currCol = 0;
}

/**
 * Destructor for the Grid class.
 */
Grid::~Grid() {
    for (int i = 0; i < SIZE; i++) {
        delete[] grid[i];
    }

    delete[] grid;
}

/**
 * Getter for any value in the grid.
 * @param row: the index of the row
 * @param col: the index of the column
 * @return: the value at the given row and column indexes
 */
int Grid::getValue(int row, int col) {
    return grid[row][col];
}

/**
 * Setter for any value in the grid.
 * @param row: the index of the row
 * @param col: the index of the column
 * @param value: the value to set at the given row and column
 */
void Grid::setValue(int row, int col, int value) {
    grid[row][col] = value;
}

/**
 * Allocates dynamic memory for a new grid and copies over the contents.
 * @return: a pointer to the new grid object
 */
Grid* Grid::copyGrid() {
    Grid *copy = new Grid();

    for (int r = 0; r < SIZE; r++) {
        for (int c = 0; c < SIZE; c++) {
            copy->setValue(r, c, grid[r][c]);
        }
    }

    copy->currRow = currRow;
    copy->currCol = currCol;

    return copy;
}

/**
 * Creates a list of successors by moving the cursor and setting the next value.
 * @return: a list of the successors
 */
std::list<Grid*>* Grid::getSuccessors() {
    std::list<Grid*> *successors = new std::list<Grid*>();

    if (canMove()) {
        Grid *copy = copyGrid();
        copy->moveCursor();
        if (copy->getValue(currRow, currCol) != 0) {
            successors->push_back(copy);
            return successors;
        } else {
            delete copy;
        }
        for (int i = 0; i < SIZE; i++) {
            copy = copyGrid();
            copy->moveCursor();
            copy->setValue(currRow, currCol, i + 1);
            if (copy->isValid()) {
                successors->push_back(copy);
            } else {
                delete copy;
            }
        }
    }

    return successors;
}

/**
 * Determines if the current configuration could be a possible solution.
 * @return: true if it could be a solution, false if not
 */
bool Grid::isValid() {
    // Checks each row for a duplicate number.
    for (int r = 0; r < SIZE; r++) {
        bool nums[SIZE] = {false * SIZE};
        for (int c = 0; c < SIZE; c++) {
            if ((grid[r][c] > 0) && (!nums[grid[r][c] - 1])) {
                nums[grid[r][c] - 1] = true;
            } else if ((grid[r][c] > 0) && (nums[grid[r][c] - 1])) {
                return false;
            }
        }
    }

    // Checks each column for a duplicate number.
    for (int c = 0; c < SIZE; c++) {
        bool nums[SIZE] = {false * SIZE};
        for (int r = 0; r < SIZE; r++) {
            if ((grid[r][c] > 0) && (!nums[grid[r][c] - 1])) {
                nums[grid[r][c] - 1] = true;
            } else if ((grid[r][c] > 0) && (nums[grid[r][c] - 1])) {
                return false;
            }
        }
    }

    // Checks squares.
    int val;
    for (int sRow = 0; sRow < SQUARES; sRow++) {
        for (int sCol = 0; sCol < SQUARES; sCol++) {
            bool nums[SIZE] = {false * SIZE};
            for (int r = 0; r < SQUARES; r++) {
                for (int c = 0; c < SQUARES; c++) {
                    val = grid[(sRow * 3) + r][(sCol * 3) + c];
                    if ((val > 0) && (!nums[val - 1])) {
                        nums[val - 1] = true;
                    } else if ((val > 0) && (nums[val - 1])) {
                        return false;
                    }
                }
            }
        }
    }

    return true;
}

/**
 * Determines if the current configuration is a solution or not.
 * @return: true if it is a solution, false if not
 */
bool Grid::isGoal() {
    for (int r = 0; r < SIZE; r++) {
        for (int c = 0; c < SIZE; c++) {
            if (grid[r][c] <= 0 || grid[r][c] > 9) {
                return false;
            }
        }
    }

    return isValid();
}

/**
 * Determines if the cursor can be advanced a position or not.
 * @return: true if the cursor can be moved, false if it is at the last position of the board
 */
bool Grid::canMove() {
    return !((currRow == SIZE - 1) && (currCol == SIZE));
}

/**
 * Moves the cursor to the next position if it is not at the last position of the board.
 * @return: true if the cursor was moved, false if it cannot be moved
 */
bool Grid::moveCursor() {
    if (!canMove()) {
        return false;
    } else {
        if (currCol != SIZE - 1) {
            currCol++;
            return true;
        } else {
            currCol = 0;
            if (currRow == SIZE - 1) {
                return false;
            } else {
                currRow++;
                return true;
            }
        }
    }
}

/**
 * Creates a string for the given row.
 * @param row: the index of the row to generate a string for
 * @return: a string for that row
 */
std::string Grid::rowString(int row) {
    std::string output = "";
    int c;

    for (c = 0; c < 3; c++) {
        output += std::to_string(grid[row][c]) + " ";
    }
    output += "| ";

    for (c = 3; c < 6; c++) {
        output += std::to_string(getValue(row, c)) + " ";
    }
    output += "| ";

    for (c = 6; c < SIZE; c++) {
        output += std::to_string(getValue(row, c)) + " ";
    }

    return output;
}

/**
 * Creates a string representation of the entire grid.
 * @return: a string for the entire grid.
 */
std::string Grid::toString() {
    std::string output = "";

    // TODO remove this
    output += std::to_string(currRow) + "," + std::to_string(currCol) + "\n";

    int r;

    for (r = 0; r < 3; r++) {
        output += rowString(r) + "\n";
    }
    output += "---------------------\n";

    for (r = 3; r < 6; r++) {
        output += rowString(r) + "\n";
    }
    output += "---------------------\n";

    for (r = 6; r < SIZE; r++) {
        output += rowString(r) + "\n";
    }

    return output;
}`
</code>```

valgrind output

```<code>==3021==
==3021== HEAP SUMMARY:
==3021==     in use at exit: 106,488 bytes in 903 blocks
==3021==   total heap usage: 3,260,824 allocs, 3,259,921 frees, 121,174,996 bytes allocated
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 19 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x401A69: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 20 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 21 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 22 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 23 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 24 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 25 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 26 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 27 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 28 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 29,664 (1,152 direct, 28,512 indirect) bytes in 72 blocks are definitely lost in loss record 31 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== LEAK SUMMARY:
==3021==    definitely lost: 1,312 bytes in 82 blocks
==3021==    indirectly lost: 32,472 bytes in 820 blocks
==3021==      possibly lost: 0 bytes in 0 blocks
==3021==    still reachable: 72,704 bytes in 1 blocks
==3021==         suppressed: 0 bytes in 0 blocks
==3021== Reachable blocks (those to which a pointer was found) are not shown.
==3021== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==3021==
==3021== For counts of detected and suppressed errors, rerun with: -v
==3021== ERROR SUMMARY: 11 errors from 11 contexts (suppressed: 0 from 0)
</code>```

答:
Not sure that it's your problem, but... according to valgrind, the problem is related with memory allocated in Grid::copyGrid(), so the memory allocated by the following new

```<code>Grid* Grid::copyGrid() {
    Grid *copy = new Grid();
    // ...
    return copy;
}
</code>```

I suspect the problem (a problem?) is in solve().

```<code>if ((*it)->isValid()) {
    Grid *solution = solve(*it);
    if (solution != nullptr) {
        solution = solution->copyGrid();
        clearList(successors);
        return solution;
    }
}
</code>```

Observe that solve() return a solution that is obtained by

```<code>solution = solution->copyGrid();
</code>```

so an allocated (new) value but losing the original value of solution obtained by

```<code>Grid *solution = solve(*it);
</code>```

that come from solve() so it's allocated.

I mean: where you delete the value returned by solve()?

I suppose you should write something like

```<code>if ((*it)->isValid()) {
    Grid *solution = solve(*it);
    if (solution != nullptr) {
        Grid *retSol = solution->copyGrid();
        clearList(successors);
        delete solution;
        return retSol;
    }
}
</code>```

-- EDIT --

The OP answer:

I just tried this, however it only causes a segmentation fault. Removing the delete solution; line fixes the segmentation fault, but the memory leak is still there.

I see...
The problem here is (if I'm not wrong) that solve() can also return the value received

```<code>Grid* solve(Grid *g) {
    if (g->isGoal()) {
        return g;
    }
</code>```

Uhmmm...

So you have to delete it only if different from *it.

I don't like it but I propose

```<code>if ((*it)->isValid()) {
    Grid *solution = solve(*it);
    if (solution != nullptr) {
        Grid *retSol = solution->copyGrid();
        clearList(successors);

        if ( solution != *it )
           delete solution;

        return retSol;
    }
}
</code>```

Title: Cannot find source of small memory leak

Body:
I created a program that can solve sudoku puzzles in C++ using a brute force backtracking algorithm, however after analyzing the memory usage in valgrind I noticed that it has a small leak. I am aware of a GCC bug that accounts for 1 missed free and 72,704 bytes that are still reachable.

It seems that I am missing 903 free() / delete / delete[] calls that accounts for around 100KB of memory.

Does anyone know what is causing the memory leak and how I can fix it?

Backtracker.cpp

#include "Backtracker.h"

/**
 * Clears all dynamic memory in the list.
 * @param lst: the pointer to the list to be cleared
 */
static void clearList(std::list<Grid*> *lst) {
    std::list<Grid*>::iterator it;
    for (unsigned int i = 0; i < lst->size(); i++) {
        it = lst->begin();
        std::advance(it, i);
        delete *it;
    }
    delete lst;
}

/**
 * Solves the sudoku puzzle or returns a null if there is no solution.
 * @param g: a pointer to the starting grid
 * @return: a pointer to the solution
 */
Grid* solve(Grid *g) {
    if (g->isGoal()) {
        return g;
    }

    std::list<Grid*> *successors = g->getSuccessors();
    std::list<Grid*>::iterator it;

    for (unsigned int i = 0; i < successors->size(); i++) {
        it = successors->begin();
        std::advance(it, i);

        if ((*it)->isValid()) {
            Grid *solution = solve(*it);
            if (solution != nullptr) {
                solution = solution->copyGrid();
                clearList(successors);
                return solution;
            }
        }
    }
    clearList(successors);

    return nullptr;
}`

Grid.cpp

#include "Grid.h"

/**
 * Constructor for the Grid class.
 */
Grid::Grid() {
    grid = new int*[SIZE];

    for (int i = 0; i < SIZE; i++) {
        grid[i] = new int[SIZE];
    }

    currRow = 0;
    currCol = 0;
}

/**
 * Destructor for the Grid class.
 */
Grid::~Grid() {
    for (int i = 0; i < SIZE; i++) {
        delete[] grid[i];
    }

    delete[] grid;
}

/**
 * Getter for any value in the grid.
 * @param row: the index of the row
 * @param col: the index of the column
 * @return: the value at the given row and column indexes
 */
int Grid::getValue(int row, int col) {
    return grid[row][col];
}

/**
 * Setter for any value in the grid.
 * @param row: the index of the row
 * @param col: the index of the column
 * @param value: the value to set at the given row and column
 */
void Grid::setValue(int row, int col, int value) {
    grid[row][col] = value;
}

/**
 * Allocates dynamic memory for a new grid and copies over the contents.
 * @return: a pointer to the new grid object
 */
Grid* Grid::copyGrid() {
    Grid *copy = new Grid();

    for (int r = 0; r < SIZE; r++) {
        for (int c = 0; c < SIZE; c++) {
            copy->setValue(r, c, grid[r][c]);
        }
    }

    copy->currRow = currRow;
    copy->currCol = currCol;

    return copy;
}

/**
 * Creates a list of successors by moving the cursor and setting the next value.
 * @return: a list of the successors
 */
std::list<Grid*>* Grid::getSuccessors() {
    std::list<Grid*> *successors = new std::list<Grid*>();

    if (canMove()) {
        Grid *copy = copyGrid();
        copy->moveCursor();
        if (copy->getValue(currRow, currCol) != 0) {
            successors->push_back(copy);
            return successors;
        } else {
            delete copy;
        }
        for (int i = 0; i < SIZE; i++) {
            copy = copyGrid();
            copy->moveCursor();
            copy->setValue(currRow, currCol, i + 1);
            if (copy->isValid()) {
                successors->push_back(copy);
            } else {
                delete copy;
            }
        }
    }

    return successors;
}

/**
 * Determines if the current configuration could be a possible solution.
 * @return: true if it could be a solution, false if not
 */
bool Grid::isValid() {
    // Checks each row for a duplicate number.
    for (int r = 0; r < SIZE; r++) {
        bool nums[SIZE] = {false * SIZE};
        for (int c = 0; c < SIZE; c++) {
            if ((grid[r][c] > 0) && (!nums[grid[r][c] - 1])) {
                nums[grid[r][c] - 1] = true;
            } else if ((grid[r][c] > 0) && (nums[grid[r][c] - 1])) {
                return false;
            }
        }
    }

    // Checks each column for a duplicate number.
    for (int c = 0; c < SIZE; c++) {
        bool nums[SIZE] = {false * SIZE};
        for (int r = 0; r < SIZE; r++) {
            if ((grid[r][c] > 0) && (!nums[grid[r][c] - 1])) {
                nums[grid[r][c] - 1] = true;
            } else if ((grid[r][c] > 0) && (nums[grid[r][c] - 1])) {
                return false;
            }
        }
    }

    // Checks squares.
    int val;
    for (int sRow = 0; sRow < SQUARES; sRow++) {
        for (int sCol = 0; sCol < SQUARES; sCol++) {
            bool nums[SIZE] = {false * SIZE};
            for (int r = 0; r < SQUARES; r++) {
                for (int c = 0; c < SQUARES; c++) {
                    val = grid[(sRow * 3) + r][(sCol * 3) + c];
                    if ((val > 0) && (!nums[val - 1])) {
                        nums[val - 1] = true;
                    } else if ((val > 0) && (nums[val - 1])) {
                        return false;
                    }
                }
            }
        }
    }

    return true;
}

/**
 * Determines if the current configuration is a solution or not.
 * @return: true if it is a solution, false if not
 */
bool Grid::isGoal() {
    for (int r = 0; r < SIZE; r++) {
        for (int c = 0; c < SIZE; c++) {
            if (grid[r][c] <= 0 || grid[r][c] > 9) {
                return false;
            }
        }
    }

    return isValid();
}

/**
 * Determines if the cursor can be advanced a position or not.
 * @return: true if the cursor can be moved, false if it is at the last position of the board
 */
bool Grid::canMove() {
    return !((currRow == SIZE - 1) && (currCol == SIZE));
}

/**
 * Moves the cursor to the next position if it is not at the last position of the board.
 * @return: true if the cursor was moved, false if it cannot be moved
 */
bool Grid::moveCursor() {
    if (!canMove()) {
        return false;
    } else {
        if (currCol != SIZE - 1) {
            currCol++;
            return true;
        } else {
            currCol = 0;
            if (currRow == SIZE - 1) {
                return false;
            } else {
                currRow++;
                return true;
            }
        }
    }
}

/**
 * Creates a string for the given row.
 * @param row: the index of the row to generate a string for
 * @return: a string for that row
 */
std::string Grid::rowString(int row) {
    std::string output = "";
    int c;

    for (c = 0; c < 3; c++) {
        output += std::to_string(grid[row][c]) + " ";
    }
    output += "| ";

    for (c = 3; c < 6; c++) {
        output += std::to_string(getValue(row, c)) + " ";
    }
    output += "| ";

    for (c = 6; c < SIZE; c++) {
        output += std::to_string(getValue(row, c)) + " ";
    }

    return output;
}

/**
 * Creates a string representation of the entire grid.
 * @return: a string for the entire grid.
 */
std::string Grid::toString() {
    std::string output = "";

    // TODO remove this
    output += std::to_string(currRow) + "," + std::to_string(currCol) + "\n";

    int r;

    for (r = 0; r < 3; r++) {
        output += rowString(r) + "\n";
    }
    output += "---------------------\n";

    for (r = 3; r < 6; r++) {
        output += rowString(r) + "\n";
    }
    output += "---------------------\n";

    for (r = 6; r < SIZE; r++) {
        output += rowString(r) + "\n";
    }

    return output;
}`

valgrind output

==3021==
==3021== HEAP SUMMARY:
==3021==     in use at exit: 106,488 bytes in 903 blocks
==3021==   total heap usage: 3,260,824 allocs, 3,259,921 frees, 121,174,996 bytes allocated
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 19 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x401A69: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 20 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 21 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 22 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 23 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 24 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 25 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 26 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 27 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 412 (16 direct, 396 indirect) bytes in 1 blocks are definitely lost in loss record 28 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x40230F: main (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== 29,664 (1,152 direct, 28,512 indirect) bytes in 72 blocks are definitely lost in loss record 31 of 32
==3021==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3021==    by 0x402620: Grid::copyGrid() (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x404104: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==    by 0x4040ED: solve(Grid*) (in /home/anthony/Documents/Code/c-c++-projects/Sudoku-Solver/sudoku-solver)
==3021==
==3021== LEAK SUMMARY:
==3021==    definitely lost: 1,312 bytes in 82 blocks
==3021==    indirectly lost: 32,472 bytes in 820 blocks
==3021==      possibly lost: 0 bytes in 0 blocks
==3021==    still reachable: 72,704 bytes in 1 blocks
==3021==         suppressed: 0 bytes in 0 blocks
==3021== Reachable blocks (those to which a pointer was found) are not shown.
==3021== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==3021==
==3021== For counts of detected and suppressed errors, rerun with: -v
==3021== ERROR SUMMARY: 11 errors from 11 contexts (suppressed: 0 from 0)

Body:
Not sure that it's your problem, but... according to valgrind, the problem is related with memory allocated in Grid::copyGrid(), so the memory allocated by the following new

Grid* Grid::copyGrid() {
    Grid *copy = new Grid();
    // ...
    return copy;
}

I suspect the problem (a problem?) is in solve().

if ((*it)->isValid()) {
    Grid *solution = solve(*it);
    if (solution != nullptr) {
        solution = solution->copyGrid();
        clearList(successors);
        return solution;
    }
}

Observe that solve() return a solution that is obtained by

solution = solution->copyGrid();

so an allocated (new) value but losing the original value of solution obtained by

Grid *solution = solve(*it);

that come from solve() so it's allocated.

I mean: where you delete the value returned by solve()?

I suppose you should write something like

if ((*it)->isValid()) {
    Grid *solution = solve(*it);
    if (solution != nullptr) {
        Grid *retSol = solution->copyGrid();
        clearList(successors);
        delete solution;
        return retSol;
    }
}

-- EDIT --

The OP answer:

I just tried this, however it only causes a segmentation fault. Removing the delete solution; line fixes the segmentation fault, but the memory leak is still there.

I see...
The problem here is (if I'm not wrong) that solve() can also return the value received

Grid* solve(Grid *g) {
    if (g->isGoal()) {
        return g;
    }

Uhmmm...

So you have to delete it only if different from *it.

I don't like it but I propose

if ((*it)->isValid()) {
    Grid *solution = solve(*it);
    if (solution != nullptr) {
        Grid *retSol = solution->copyGrid();
        clearList(successors);

        if ( solution != *it )
           delete solution;

        return retSol;
    }
}


问:
Check and add column in text file
I have a text file:

```
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0017;random information;IT0077;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;random information;IT0077;NaN;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0105;...
```

based on 3 fields: IT0006 IT0017 random data

In the first row, I have IT0017; random information;IT0077 but not IT0006(column_23) and NaN (column_27)

In the second row I have all column(good case)

In the third row I have none of those five column

In the fourth I Have only the IT0006 field.

I would like to create this output:

```
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;<b>IT0006;</b>IT0017;random information;IT0077;<b>NaN;</b>IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;random information;IT0077;NaN;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;<b>IT0006;IT0017;NaN;IT0077;NaN;</b>IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;<b>IT0017;NaN;IT0077;NaN;</b>IT0105;...
```

Getting the same number of columns...

In first row, I added IT0006;

In second row, never column (this is a good case)

In third row I added IT0006; IT0017; and NaN (because I don't have information and use NaN …)

in fourth I add IT0017; NaN

This is solution using PHP and good working:

```<code><?php
$sapFile = fopen("file.txt", "r") or die("Unable to open file!");
$typePers = array("Personale Viaggiante","Personale Interno");
$excludeFields = array("IT0006","IT0017","IT0077","Personale Viaggiante","Personale Interno","IT0105");
$emptyValue = "NaN";
$rowfinal = "";

// Output one line until end-of-file
while(!feof($sapFile)) {
    $row = explode(";",fgets($sapFile));
    $substring = "IT0006;IT0017;";
    $lstr = "";
    $rstr = "";
    $type = array_intersect($row, $typePers);
    $keys = array_keys($type);
    if($keys == null) $type = $emptyValue;
    else $type = $row[$keys[0]];

    $j = 0;
    for($i=0; $i<count($row); $i++){
        if(in_array($row[$i],$excludeFields)){
            unset($row[$i]);
            $j++;
        }
    }

    for($i=0; $i<22;$i++)$lstr .= $row[$i].";";

    foreach($row as $k => $v)
        if($k > 22)if(!empty($v))$rstr .= $v.";";

    $rstr = substr($rstr,0,-1);
    $substring .= $type;
    $substring .= ";IT0077;NaN;IT0105;";
    $rowfinal .= $lstr.$substring.$rstr;
}
$file = 'test.txt';
// Write the contents back to the file
file_put_contents($file, $rowfinal);
fclose($sapFile);
?>
</code>```

In the end, I must export files to CSV(add header column)

Can you help me to trasform in powershell script?

答:
If you know that you miss only these fields in that order you can simply use replace operator with regular expressions (lookbehind + negative lookahead).</p>

```<code>$text = Get-Content .\test.txt
$text = $text -replace '(?<=City;;\d{4};)(?!IT0006)', 'IT0006;'
$text = $text -replace '(?<=IT0006;)(?!IT0017)', 'IT0017;'
$text = $text -replace '(?<=IT0017;)(?!XXXXX)', 'NaN;'
</code>```

Title: Check and add column in text file

Body:
I have a text file:

FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0017;random information;IT0077;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;random information;IT0077;NaN;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0105;...

based on 3 fields: IT0006 IT0017 random data

In the first row, I have IT0017; random information;IT0077 but not IT0006(column_23) and NaN (column_27)

In the second row I have all column(good case)

In the third row I have none of those five column

In the fourth I Have only the IT0006 field.

I would like to create this output:

FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;random information;IT0077;NaN;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;random information;IT0077;NaN;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;NaN;IT0077;NaN;IT0105;...
FIELD1;FIELD2;FIELD3;FIELD4;FIELD5;;FIELD7;FIELD8;FIELD9;FIELD10;FIELD11;FIELD12;FIELD13;FIELD14;FIELD15;FIELD16;FIELD17;FIELD18;FIELD19;FIELD20;FIELD21;FIELD22;IT0006;IT0017;NaN;IT0077;NaN;IT0105;...

Getting the same number of columns...

In first row, I added IT0006;

In second row, never column (this is a good case)

In third row I added IT0006; IT0017; and NaN (because I don't have information and use NaN …)

in fourth I add IT0017; NaN

This is solution using PHP and good working:

<?php
$sapFile = fopen("file.txt", "r") or die("Unable to open file!");
$typePers = array("Personale Viaggiante","Personale Interno");
$excludeFields = array("IT0006","IT0017","IT0077","Personale Viaggiante","Personale Interno","IT0105");
$emptyValue = "NaN";
$rowfinal = "";

// Output one line until end-of-file
while(!feof($sapFile)) {
    $row = explode(";",fgets($sapFile));
    $substring = "IT0006;IT0017;";
    $lstr = "";
    $rstr = "";
    $type = array_intersect($row, $typePers);
    $keys = array_keys($type);
    if($keys == null) $type = $emptyValue;
    else $type = $row[$keys[0]];

    $j = 0;
    for($i=0; $i<count($row); $i++){
        if(in_array($row[$i],$excludeFields)){
            unset($row[$i]);
            $j++;
        }
    }

    for($i=0; $i<22;$i++)$lstr .= $row[$i].";";

    foreach($row as $k => $v)
        if($k > 22)if(!empty($v))$rstr .= $v.";";

    $rstr = substr($rstr,0,-1);
    $substring .= $type;
    $substring .= ";IT0077;NaN;IT0105;";
    $rowfinal .= $lstr.$substring.$rstr;
}
$file = 'test.txt';
// Write the contents back to the file
file_put_contents($file, $rowfinal);
fclose($sapFile);
?>

In the end, I must export files to CSV(add header column)

Can you help me to trasform in powershell script?

Body:
If you know that you miss only these fields in that order you can simply use replace operator with regular expressions (lookbehind + negative lookahead).

$text = Get-Content .\test.txt
$text = $text -replace '(?<=City;;\d{4};)(?!IT0006)', 'IT0006;'
$text = $text -replace '(?<=IT0006;)(?!IT0017)', 'IT0017;'
$text = $text -replace '(?<=IT0017;)(?!XXXXX)', 'NaN;'


问:
MySQL index for only maximum and minimum values
I have a huge table with millions of rows which stores the values obtained from some weather stations. Every row contains the station that gathered the value, the metric (for example, temperature, humidity, noise level, etc.), the date and the value itself.

This is its structure:

station: int(8)

metric: int(8)

date: datetime

value: float

And these are the indices I've defined:

PRIMARY KEY: station+metric+date

KEY: metrica (for the foreign key)

Sometimes, I'm interested in retrieving the last time every station has sent some value. Then I use this query:

```<code> SELECT station, MAX(date)
 FROM MyTable
 GROUP BY station
</code>```

This query is very slow, as it has to read the entire table. If I add an index for station+date, the query now can use it and it becomes very fast. But the table storage also increases a lot, and for me indexing all date values is not useful, given I'm only interested on the max value.

So my question is if it's possible to create an index that indexes some range, ideally to only keep track of the maximum value.

答:
```<code>INDEX(station, date)
</code>```

will handle that query efficiently.  Alternatively, you could rearrange the PRIMARY KEY to (station, date, metric).

If you also want the temp on that date, then you are into a more complex groupwise-max .

ContentLicense: CC BY-SA 4.0

Body:
I have a huge table with millions of rows which stores the values obtained from some weather stations. Every row contains the station that gathered the value, the metric (for example, temperature, humidity, noise level, etc.), the date and the value itself.

This is its structure:

station: int(8)

metric: int(8)

date: datetime

value: float

And these are the indices I've defined:

PRIMARY KEY: station+metric+date

KEY: metrica (for the foreign key)

Sometimes, I'm interested in retrieving the last time every station has sent some value. Then I use this query:

 SELECT station, MAX(date)
 FROM MyTable
 GROUP BY station

This query is very slow, as it has to read the entire table. If I add an index for station+date, the query now can use it and it becomes very fast. But the table storage also increases a lot, and for me indexing all date values is not useful, given I'm only interested on the max value.

So my question is if it's possible to create an index that indexes some range, ideally to only keep track of the maximum value.

Body:
INDEX(station, date)

will handle that query efficiently.  Alternatively, you could rearrange the PRIMARY KEY to (station, date, metric).

If you also want the temp on that date, then you are into a more complex groupwise-max .


问:
Cannot find symbol method FindViewById(int) with extends AppCompatActivity
I'm trying to assign a button to a Button variable using FindViewById like this:

```<code>Button dotBtn = (Button)FindViewById(R.id.dotBtn);
</code>```

I get an error

Cannot find symbol method FindViewById(int)

What is the problem? Does it have something to do with the extends AppCompatActivity? I mean with this:

```<code>public class MainActivity extends AppCompatActivity
</code>```

答: It should be findViewById not FindViewById. Small f

Body:
I'm trying to assign a button to a Button variable using FindViewById like this:

Button dotBtn = (Button)FindViewById(R.id.dotBtn);

I get an error

Cannot find symbol method FindViewById(int)

What is the problem? Does it have something to do with the extends AppCompatActivity? I mean with this:

public class MainActivity extends AppCompatActivity


问:
seg fault error in accessing global pointer from function
Why segmentation fault occur when I am assigning value to pointer in a function.

source_1.c

```<code>int *p = NULL;

func(int **y)
{
    *y = (int *) malloc(sizeof(int));
    *y = 1;
}

int main()
{
    func(&p);
    printf("%d\n",*p);
}
</code>```

source_2.c

```<code>int *p = NULL;

func(int **y)
{
    *y = (int *) malloc(sizeof(int));
    *y = 1;
}

int main()
{
    int *t = p;
    func(&t);
    printf("%d\n",*t);
}
</code>```

whats wrong in pointer definition and  passing address?

答:
Simply you can find out whats wrong in your pointer manipulation  by using your compiler warnings flags.

In windows and in Visual Studio IDE use built in debugger to see coding faults.

In linux environment on GCC compiler try compile your source code (in my case t.c) with this command

```<code>gcc -Wall t.c -o t
</code>```

gcc produce these warnings

```<code>t.c:8:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 func(int **y)
 ^
t.c: In function ‘func’:
t.c:11:8: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     *y = 1;
        ^
t.c:12:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
</code>```

This is obvious that assignment  *y = 1; is wrong.

Thanks for Mark Benningfield for introduce useful link on using pointer to pointer

make change your code to some like this will solve your problem

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

int *p = NULL;

void func(int **y)
{
    *y = malloc(sizeof(int));
    **y = 1;
}

int main()
{

    func(&p);
    printf("%d\n",*p);

}
</code>```

First for a function that not return any value use void as return type.
Second if we try to pass a pointer to pointer to a function as argument
for example func(int **y)  as  y can hold address of a pointer
we must call it with func (&p). p is a integer pointer.

At last this is recommended not to cast result of malloc() with somethings like

```<code>(int *)malloc(sizeof(int))
</code>```

cast the result of malloc?

Body:
Why segmentation fault occur when I am assigning value to pointer in a function.

source_1.c

int *p = NULL;

func(int **y)
{
    *y = (int *) malloc(sizeof(int));
    *y = 1;
}

int main()
{
    func(&p);
    printf("%d\n",*p);
}

source_2.c

int *p = NULL;

func(int **y)
{
    *y = (int *) malloc(sizeof(int));
    *y = 1;
}

int main()
{
    int *t = p;
    func(&t);
    printf("%d\n",*t);
}

whats wrong in pointer definition and  passing address?

Body:
Simply you can find out whats wrong in your pointer manipulation  by using your compiler warnings flags.

In windows and in Visual Studio IDE use built in debugger to see coding faults.

In linux environment on GCC compiler try compile your source code (in my case t.c) with this command

gcc -Wall t.c -o t

gcc produce these warnings

t.c:8:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 func(int **y)
 ^
t.c: In function ‘func’:
t.c:11:8: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     *y = 1;
        ^
t.c:12:1: warning: control reaches end of non-void function [-Wreturn-type]
 }

This is obvious that assignment  *y = 1; is wrong.

Thanks for Mark Benningfield for introduce useful link on using pointer to pointer

make change your code to some like this will solve your problem

#include <stdio.h>

int *p = NULL;

void func(int **y)
{
    *y = malloc(sizeof(int));
    **y = 1;
}

int main()
{

    func(&p);
    printf("%d\n",*p);

}

First for a function that not return any value use void as return type.
Second if we try to pass a pointer to pointer to a function as argument
for example func(int **y)  as  y can hold address of a pointer
we must call it with func (&p). p is a integer pointer.

At last this is recommended not to cast result of malloc() with somethings like

(int *)malloc(sizeof(int))

cast the result of malloc?


问:
Android:Sound doesn't play after 24th click
So I am a programming beginner and while making a simple soundboard app with 8 buttons, i got a strange problem where it stops playing sound after the 24th button press.Here's the java code:

```<code>public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    int i = 0;
    public void playSound(View view){

            switch(view.getId())
            {
                case R.id.button1:
                    mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                    break;
                case R.id.button2:
                    mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                    break;
                case R.id.button3:
                    mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                    break;
                case R.id.button4:
                    mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                    break;
                case R.id.button5:
                    mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                    break;
                case R.id.button6:
                    mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                    break;
                case R.id.button7:
                    mediaPlayer = MediaPlayer.create(this, R.raw.please);
                    break;
                case R.id.button8:
                    mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                    break;
                default:
                    throw new RuntimeException("Unknown button ID");
            }
            i++;
        Log.i("klik", Integer.toString(i));
            mediaPlayer.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

And here's the error message,I'm not allowed to post the image for being a new user so here's a link

答:
Please read the Annotations on the Media Player:

When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.

So before calling MediaPlayer.create again just call

```<code>mediaPlayer.stop();
mediaPlayer.release();
</code>```

Body:
So I am a programming beginner and while making a simple soundboard app with 8 buttons, i got a strange problem where it stops playing sound after the 24th button press.Here's the java code:

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    int i = 0;
    public void playSound(View view){

            switch(view.getId())
            {
                case R.id.button1:
                    mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                    break;
                case R.id.button2:
                    mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                    break;
                case R.id.button3:
                    mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                    break;
                case R.id.button4:
                    mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                    break;
                case R.id.button5:
                    mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                    break;
                case R.id.button6:
                    mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                    break;
                case R.id.button7:
                    mediaPlayer = MediaPlayer.create(this, R.raw.please);
                    break;
                case R.id.button8:
                    mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                    break;
                default:
                    throw new RuntimeException("Unknown button ID");
            }
            i++;
        Log.i("klik", Integer.toString(i));
            mediaPlayer.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

And here's the error message,I'm not allowed to post the image for being a new user so here's a link

Body:
Please read the Annotations on the Media Player:

When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.

So before calling MediaPlayer.create again just call

mediaPlayer.stop();
mediaPlayer.release();


问:
Change option menu position in fragment
I have an activity with an Option menu (Logout Icon) Inside the activity I have a fragment which is having an option menu too. But the option menu of the fragment is always coming at last. I want it before the parent activity's option menu.

Menu looks like this -

答:
The order of the menus is controlled by the orderInCategory xml attribute, where a smaller order number will appear first (left-most).

If you are inflating the menu items from XML, set the android:orderInCategory attribute in your Activity menu item to be higher than the one in the fragment.

If you are setting the menu items at runtime, set a higher order for the activity's menu item than the fragment's when calling menu.add().

Hope that helps!

Title: Change option menu position in fragment


问:
OpenCart automatically add new products. Products manipulation
I am new to opencart, and I have to write code which will automatically add/delete/edit products on that opencart website, so my question is the following :

How to add new products to the database automatically with php? (Maybe there are some methods in opencart, so I can use them, or I have to write the code from scratch?)

P.S: an example will be great (suppose we have the product information in an array)

P.P.S: not all products will be added automatically.

答:
Combination of above both answers are very good to import products using admin.But if you can manage the excel or csv file for products then following extension is very good extension to import the products.

https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=17&filter_search=import%20export&filter_license=0


问:
How to capture iPhone screen with animating UIImageView?
I have a UIImageView placed over a view and I want to capture iPhone screen while that UIImageView is animating.

I can successfully capture the screen shots of the still frames of the UIImageView like this:

```<code>[[myView layer] renderInContext:context];
</code>```

However when the UIImageView is animating throguh

[MyImageView startAnimating]

then, those animating frames are not captured.

Is there any alternative to renderInContext available at the moment that can capture the animating frames as well?

NOTE: I know UIGetScreenImage() is no longer accepted by Apple after iOS4 update.

答: CALayers use a presentationLayer to represent the current state of the layer while animating. CALayer's -presentationLayer method returns you the presentation layer. So you might want to try [[[myView layer] presentationLayer] renderInContext:context]; to capture its contents.

ContentLicense: CC BY-SA 2.5

Body:
I have a UIImageView placed over a view and I want to capture iPhone screen while that UIImageView is animating.

I can successfully capture the screen shots of the still frames of the UIImageView like this:

[[myView layer] renderInContext:context];

However when the UIImageView is animating throguh

[MyImageView startAnimating]

then, those animating frames are not captured.

Is there any alternative to renderInContext available at the moment that can capture the animating frames as well?

NOTE: I know UIGetScreenImage() is no longer accepted by Apple after iOS4 update.


问:
Can't log user created with a seeder in Laravel 5
I'm having an issue in Laravel 5 logging with a user created by a seeder. The user is correctly created with his role and permission, I just can't log him in. I think this might be because of the user token, but I have no idea how to fix that... Here is the seeder code :

```<code>if ($this->command->confirm('Do you wish to refresh migration before seeding, it will clear all old data ?')) {
        // Call the php artisan migrate:refresh
        $this->command->call('migrate:refresh');
        $this->command->warn("Data cleared, starting from blank database.");
    }

    //create a user
    $mainAdmin = User::create([
        'name' => 'Alex',
        'email' => 'someadress@example.com',
        'password' => bcrypt('password'),
    ]);

    //create a role of admin
    $admin = Role::create([
        'name' => 'admin',
        'display_name' => 'Admin',
        'description' => 'Only one and only admin',
    ]);

    //create a permission for role
    $manageUsers = Permission::create([
        'name' => 'manage-users-roles-and-permissions',
        'display_name' => 'Manage Users,Roles and Permissions',
        'description' => 'Can manage users,roles and permission"s',
    ]);

    //here attaching permission for admin role
    $admin->attachPermission($manageUsers);

    //here attaching role for user
    $mainAdmin->attachRole($admin);
</code>```

Here is the login form, it's a standard laravel login form, didn't touch it.

```<code><form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">
   {{ csrf_field() }}

   <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
   <label for="email" class="col-md-4 control-label">E-Mail Address</label>

  <div class="col-md-6">
      <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

      @if ($errors->has('email'))
         <span class="help-block">
             <strong>{{ $errors->first('email') }}</strong>
         </span>
      @endif
 </div>
 </div>

 <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
 <label for="password" class="col-md-4 control-label">Password</label>

<div class="col-md-6">
    <input id="password" type="password" class="form-control" name="password" required>

    @if ($errors->has('password'))
        <span class="help-block">
          <strong>{{ $errors->first('password') }}</strong>
        </span>
    @endif
</div>
</div>

<div class="form-group">
   <div class="col-md-6 col-md-offset-4">
       <div class="checkbox">
            <label>
                <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
            </label>
       </div>
   </div>
 </div>

 <div class="form-group">
     <div class="col-md-8 col-md-offset-4">
         <button type="submit" class="btn btn-primary">
                                Login
        </button>

       <a class="btn btn-link" href="{{ route('password.request') }}">
          Forgot Your Password?
      </a>
    </div>
  </div>
</form>
</code>```

Hope someone can help me figure out this issue I'm really stuck with it !

答:
U are using user:create() and hashing the password on it, since default Laravel user:create() will automatically hash it once it seems u are hashing the password twice before inserting it on database.

I suggest you to leave password=> 'password' delete and run the seeding again.

Body:
I'm having an issue in Laravel 5 logging with a user created by a seeder. The user is correctly created with his role and permission, I just can't log him in. I think this might be because of the user token, but I have no idea how to fix that... Here is the seeder code :

if ($this->command->confirm('Do you wish to refresh migration before seeding, it will clear all old data ?')) {
        // Call the php artisan migrate:refresh
        $this->command->call('migrate:refresh');
        $this->command->warn("Data cleared, starting from blank database.");
    }

    //create a user
    $mainAdmin = User::create([
        'name' => 'Alex',
        'email' => 'someadress@example.com',
        'password' => bcrypt('password'),
    ]);

    //create a role of admin
    $admin = Role::create([
        'name' => 'admin',
        'display_name' => 'Admin',
        'description' => 'Only one and only admin',
    ]);

    //create a permission for role
    $manageUsers = Permission::create([
        'name' => 'manage-users-roles-and-permissions',
        'display_name' => 'Manage Users,Roles and Permissions',
        'description' => 'Can manage users,roles and permission"s',
    ]);

    //here attaching permission for admin role
    $admin->attachPermission($manageUsers);

    //here attaching role for user
    $mainAdmin->attachRole($admin);

Here is the login form, it's a standard laravel login form, didn't touch it.

<form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">
   {{ csrf_field() }}

has('email') ? ' has-error' : '' }}">
   E-Mail Address

      <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

      @if ($errors->has('email'))

             {{ $errors->first('email') }}

      @endif

has('password') ? ' has-error' : '' }}">
 Password

    <input id="password" type="password" class="form-control" name="password" required>

    @if ($errors->has('password'))

          {{ $errors->first('password') }}

    @endif

                <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me

         <button type="submit" class="btn btn-primary">
                                Login
        </button>

          Forgot Your Password?

</form>

Hope someone can help me figure out this issue I'm really stuck with it !


问:
Labeling points in matplotlib scatterplot
Edit: This question is not a duplicate, I don't want to plot numbers instead of points, I wanted to plot numbers beside my points.

I'm making a plot using matplotlib. There are three points to plot [[3,9],[4,8],[5,4]]

I can easily make a scatterplot with them

```<code>import matplotlib.pyplot as plt

allPoints = [[3,9],[4,8],[5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    xPoint =  allPoints[i][0]
    yPoint =  allPoints[i][1]
    diagram.plot(xPoint, yPoint, 'bo')
</code>```

That produces this plot:

I want to label each point with numbers 1,2,3.

Based on this SO answer I tried to use annotate to label each point.

```<code>import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.annotate(pointRefNumber, (xPoint, yPoint))
</code>```

This produces a blank plot. I'm closely following the other answer but it isn't producing any plot. Where have I made a mistake?

答:
You can do that:

```<code>import matplotlib.pyplot as plt

points = [[3,9],[4,8],[5,4]]

for i in range(len(points)):
    x = points[i][0]
    y = points[i][1]
    plt.plot(x, y, 'bo')
    plt.text(x * (1 + 0.01), y * (1 + 0.01) , i, fontsize=12)

plt.xlim((0, 10))
plt.ylim((0, 10))
plt.show()
</code>```

Body:
Edit: This question is not a duplicate, I don't want to plot numbers instead of points, I wanted to plot numbers beside my points.

I'm making a plot using matplotlib. There are three points to plot [[3,9],[4,8],[5,4]]

I can easily make a scatterplot with them

import matplotlib.pyplot as plt

allPoints = [[3,9],[4,8],[5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    xPoint =  allPoints[i][0]
    yPoint =  allPoints[i][1]
    diagram.plot(xPoint, yPoint, 'bo')

That produces this plot:

I want to label each point with numbers 1,2,3.

Based on this SO answer I tried to use annotate to label each point.

import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.annotate(pointRefNumber, (xPoint, yPoint))

This produces a blank plot. I'm closely following the other answer but it isn't producing any plot. Where have I made a mistake?

Body:
You can do that:

import matplotlib.pyplot as plt

points = [[3,9],[4,8],[5,4]]

for i in range(len(points)):
    x = points[i][0]
    y = points[i][1]
    plt.plot(x, y, 'bo')
    plt.text(x * (1 + 0.01), y * (1 + 0.01) , i, fontsize=12)

plt.xlim((0, 10))
plt.ylim((0, 10))
plt.show()


问:
Exception when converting to image from Base-64 string
I am trying to send a Highcharts chart via image on ASP.NET button click.
What I am trying to do is:

Convert the chart to base64 image, the code is the following :

```<code>  var chart = $('#main-content').highcharts();
    EXPORT_WIDTH = 1000;
    var render_width = EXPORT_WIDTH;
    var render_height = render_width * chart.chartHeight / chart.chartWidth;

    var svg = chart.getSVG({
        exporting: {
            sourceWidth: chart.chartWidth,
            sourceHeight: chart.chartHeight
        }
    });
    var contentToSend = 'data:image/svg+xml;base64,' + window.btoa(svg);
    var hdnField = document.getElementById("MainContent_ChartImage");
    hdnField.value = contentToSend;
</code>```

Next step is taking the base64 image value, convert it to image an attach it to the mail, the code is:

```<code> string textImage = ChartImage.Value;

 var imageData = Convert.FromBase64String(HttpUtility.UrlDecode(data));
 System.Net.Mail.LinkedResource res;
 AlternateView htmlView;
 using (MemoryStream ms = new MemoryStream(imageData, true))
 {
      ms.Position = 0;
      ms.Write(imageData, 0, imageData.Length);
      ms.Seek(0, SeekOrigin.Begin);
      res = new System.Net.Mail.LinkedResource(ms);
      htmlView = AlternateView.CreateAlternateViewFromString("<html><body><img src='cid:imageReport' width='100%' ></body></html>", null, "text/html");
      res.ContentId = "imageReport";
      htmlView.LinkedResources.Add(res);
      MailMessage mailMsg = new MailMessage();
      SmtpClient client = new SmtpClient();

      // ...

      mailMsg.IsBodyHtml = true;
      mailMsg.AlternateViews.Add(htmlView);
      client.Send(mailMsg);
 }
</code>```

but the method Convert.FromBase64String throws an exception

{"The input is not a valid Base-64 string as it contains a non-base 64
  character, more than two padding characters, or an illegal character
  among the padding characters. "}

However when I remove 'data:image/svg+xml;base64,' then convert it, it doesn't throw an exception but the image will not appear. What should I do?

Thank you

答:
Get rid of the beginning part of the string: "data:image/svg+xml;base64," that part is not base64, just the remainder is. You don't need to use HttpUtility.UrlDecode either.

You should specify the TransferEncoding as Base64:

```<code>res.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
</code>```

However with all that said, there are some strong caveats to using SVG in email. So you may want to consider a different format such as JPG or PNG. If that's the route you take, you will need to use a library to convert formats.

Body:
I am trying to send a Highcharts chart via image on ASP.NET button click.
What I am trying to do is:

Convert the chart to base64 image, the code is the following :

  var chart = $('#main-content').highcharts();
    EXPORT_WIDTH = 1000;
    var render_width = EXPORT_WIDTH;
    var render_height = render_width * chart.chartHeight / chart.chartWidth;

    var svg = chart.getSVG({
        exporting: {
            sourceWidth: chart.chartWidth,
            sourceHeight: chart.chartHeight
        }
    });
    var contentToSend = 'data:image/svg+xml;base64,' + window.btoa(svg);
    var hdnField = document.getElementById("MainContent_ChartImage");
    hdnField.value = contentToSend;

Next step is taking the base64 image value, convert it to image an attach it to the mail, the code is:

 string textImage = ChartImage.Value;

 var imageData = Convert.FromBase64String(HttpUtility.UrlDecode(data));
 System.Net.Mail.LinkedResource res;
 AlternateView htmlView;
 using (MemoryStream ms = new MemoryStream(imageData, true))
 {
      ms.Position = 0;
      ms.Write(imageData, 0, imageData.Length);
      ms.Seek(0, SeekOrigin.Begin);
      res = new System.Net.Mail.LinkedResource(ms);
      htmlView = AlternateView.CreateAlternateViewFromString("", null, "text/html");
      res.ContentId = "imageReport";
      htmlView.LinkedResources.Add(res);
      MailMessage mailMsg = new MailMessage();
      SmtpClient client = new SmtpClient();

      // ...

      mailMsg.IsBodyHtml = true;
      mailMsg.AlternateViews.Add(htmlView);
      client.Send(mailMsg);
 }

but the method Convert.FromBase64String throws an exception

{"The input is not a valid Base-64 string as it contains a non-base 64
  character, more than two padding characters, or an illegal character
  among the padding characters. "}

However when I remove 'data:image/svg+xml;base64,' then convert it, it doesn't throw an exception but the image will not appear. What should I do?

Thank you

Body:
Get rid of the beginning part of the string: "data:image/svg+xml;base64," that part is not base64, just the remainder is. You don't need to use HttpUtility.UrlDecode either.

You should specify the TransferEncoding as Base64:

res.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

However with all that said, there are some strong caveats to using SVG in email. So you may want to consider a different format such as JPG or PNG. If that's the route you take, you will need to use a library to convert formats.