问:
Simple directive that uses TemplateRef yields "No provider for TemplateRef"
I'm trying to create a directive that creates a view based upon a condition. Just like the built in ngIf directive.

This is all I added to my project:

```<code>export class QueryNameContext {
    public name: string;
}

@Directive({
    selector: '[action]'
})
export class QueryNameDirective {
    @Input('action')
    public name: string;

    public constructor(private viewContainerRef: ViewContainerRef,
                       private templateRef: TemplateRef<QueryNameContext>) {
    }
}
</code>```

When I try to use the directive in a template:

```<code><div *action="thing"></div>
</code>```

I get this dependency error:

```<code>core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for TemplateRef!
</code>```

My modules are importing CommonModule and I'm able to use TemplateRef in @ViewChild bindings of other directives.

I can't see what I've done wrong.

答:
Maybe someone will run into this problem so I'll leave this here.

I had two directives with the same selector by mistake. Renaming this fixed the Uncaught (in promise): Error: No provider for TemplateRef! error.

Body:
I'm trying to create a directive that creates a view based upon a condition. Just like the built in ngIf directive.

This is all I added to my project:

export class QueryNameContext {
    public name: string;
}

@Directive({
    selector: '[action]'
})
export class QueryNameDirective {
    @Input('action')
    public name: string;

    public constructor(private viewContainerRef: ViewContainerRef,
                       private templateRef: TemplateRef<QueryNameContext>) {
    }
}

When I try to use the directive in a template:

I get this dependency error:

core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for TemplateRef!

My modules are importing CommonModule and I'm able to use TemplateRef in @ViewChild bindings of other directives.

I can't see what I've done wrong.


来源: stackexchange

问:
Why is my WHERE clause not filtering the year in my date column?
So I'm trying to filter dates, but for example, when I enter the code below, I get all dates after July 1, regardless of the year.  In includes 2015, and 2016 items.  What I am doing wrong?  The original TicketDate column is Text format in our database, that's why I converted.</p>

```<code>SELECT
  EmplCode,
  Comments,
  EmplName,
  CONVERT(NVARCHAR, CAST(TicketDate AS DATE), 1) AS TicketDate,
  CreatedBy,
  ActClockInTime,
  ActClockOutTime,
  AdjClockInTime,
  AdjClockOutTime,
  ROUND(TotActTime, 2) AS ActualTime,
  ROUND(TotAdjTime, 2) AS AdjActualTime,
  PayrollRate,
  OverTime,
  Holiday,
  GLAcct
FROM AttendDet
WHERE
  EmplCode IS NOT NULL
  AND TicketDate > '07/01/17'
ORDER BY TicketDate;
</code>```

答:
If TicketDate is not a date data type, then you need to convert it to one.

Also: The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

```<code>select
  EmplCode,
  Comments,
  EmplName,
  convert(varchar(30), cast(TicketDate as date), 1) as TicketDate,
  CreatedBy,
  ActClockInTime,
  ActClockOutTime,
  AdjClockInTime,
  AdjClockOutTime,
  round(TotActTime, 2) as ActualTime,
  round(TotAdjTime, 2) as AdjActualTime,
  PayrollRate,
  OverTime,
  Holiday,
  glacct
from AttendDet
where EmplCode is not null
  and convert(date,TicketDate) > '20170701'
order by TicketDate;
</code>```

Also, always include a size for varchar and nvarchar.

Bad habits to kick : declaring varchar without (length) - Aaron Bertrand - you should always provide a length for all varchar or nvarchar variables/parameters.

ContentLicense: CC BY-SA 3.0

Body:
So I'm trying to filter dates, but for example, when I enter the code below, I get all dates after July 1, regardless of the year.  In includes 2015, and 2016 items.  What I am doing wrong?  The original TicketDate column is Text format in our database, that's why I converted.

SELECT
  EmplCode,
  Comments,
  EmplName,
  CONVERT(NVARCHAR, CAST(TicketDate AS DATE), 1) AS TicketDate,
  CreatedBy,
  ActClockInTime,
  ActClockOutTime,
  AdjClockInTime,
  AdjClockOutTime,
  ROUND(TotActTime, 2) AS ActualTime,
  ROUND(TotAdjTime, 2) AS AdjActualTime,
  PayrollRate,
  OverTime,
  Holiday,
  GLAcct
FROM AttendDet
WHERE
  EmplCode IS NOT NULL
  AND TicketDate > '07/01/17'
ORDER BY TicketDate;

Body:
If TicketDate is not a date data type, then you need to convert it to one.

Also: The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

select
  EmplCode,
  Comments,
  EmplName,
  convert(varchar(30), cast(TicketDate as date), 1) as TicketDate,
  CreatedBy,
  ActClockInTime,
  ActClockOutTime,
  AdjClockInTime,
  AdjClockOutTime,
  round(TotActTime, 2) as ActualTime,
  round(TotAdjTime, 2) as AdjActualTime,
  PayrollRate,
  OverTime,
  Holiday,
  glacct
from AttendDet
where EmplCode is not null
  and convert(date,TicketDate) > '20170701'
order by TicketDate;

Also, always include a size for varchar and nvarchar.

Bad habits to kick : declaring varchar without (length) - Aaron Bertrand - you should always provide a length for all varchar or nvarchar variables/parameters.

ContentLicense: CC BY-SA 4.0


问:
editing a google form response and data lost
I have created a standard google form and added a record.  i have set options to  edit the response . one of the questions i have added  allows me to jump straight to submit or continue editing .

However When i am editing a response and i choose the my option to jump to submit and then press submit , i find the information is lost when i go back to edit the response.

However if i scroll through all my answers and submit at the end, then the data is saved.

Is there an issue with google forms ? i am not using any scripts - it is standard editing and form options.

答:
This appears to be an issue with Google Forms when editing responses and changing the "go to" path from the initial submission. I've opened a question with a Google "Community Specialist" in the Google Help forums but so far she has not identified how to avoid this problem nor reported escalating it to get it fixed.

For those curious what to avoid, here is the scenario that causes a form to lose data:

Create a form with multiple Go To paths

Fill out a response using one Go To path of questions

Submit response

Click Edit Response

Choose an option that takes you down a different Go To path of questions

Submit the edited response

Click Edit Response

Going back to the original option Go To path, the earlier submitted data will now be gone.

Here is a form I've created that demonstrates the issue.

Here is the thread that as of this writing the Google Community Specialist has not yet solved. Perhaps if more people were to comment that it really is an issue she will pay more attention to it and bring it to the attention of who might be able to fix it.


答:
Let me provide a simple and efficient answer, using regular expressions. There's no need to map (duplicating the original list), or to convert everything to ints; you are basically asking how to keep all 8-digit integers in your list:

```<code>>>> filter(re.compile('^\d{8}$').match, data)
['71229366', '87640804', '71758011']
</code>```

We compile a regular expression which matches exactly 8 digits and then filter the list by providing a partial application of regex.match to the standard filter function.

Title: Extract 8-digit numbers from a list of strings

Body:
I have a list of strings which may contain letters, symbols, digits, etc, as below:

list = ['\n', '', '0', '38059', '', '', '?_', '71229366', '', '1', '38059', '', '', '?_', '87640804', '', '2', '38059', '', '', '?_', '71758011', '', '', ':?', ';__', '71229366287640804271758011287169822']

How do I filter out all other strings, except numbers less than 10000000 and greater than 99999999?

Expected Output:

list = ['71229366', '87640804', '71758011']

Body:
Let me provide a simple and efficient answer, using regular expressions. There's no need to map (duplicating the original list), or to convert everything to ints; you are basically asking how to keep all 8-digit integers in your list:

>>> filter(re.compile('^\d{8}$').match, data)
['71229366', '87640804', '71758011']

We compile a regular expression which matches exactly 8 digits and then filter the list by providing a partial application of regex.match to the standard filter function.


问:
C# function uses extension function but VB equivalent does not?
So I have the following code in C#:

```<code>public Container ConfigureSimpleInjector(IAppBuilder app)
{
    var container = new Container();

    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    container.RegisterPackages();

    app.Use(async (context, next) =>
    {
        using (AsyncScopedLifestyle.BeginScope(container))
        {
            await next();
        }
    });

    container.Verify();

    return container;
}
</code>```

The app.Use() is defined as Owin.AppBuilderUserExtensions.Use() and looks like this:

public static IAppBuilder Use(this IAppBuilder app, Func<IOwinContext, Func<Task>, Task> handler);

The VB equivalent is as follows:

Public Function ConfigureSimpleInjector(app As IAppBuilder) As Container
    Dim container = New Container()

    container.Options.DefaultScopedLifestyle = New AsyncScopedLifestyle()

    container.RegisterPackages()

    app.Use(Async Sub(context, [next])
                Using AsyncScopedLifestyle.BeginScope(container)
                    Await [next]()
                End Using
            End Sub)

    container.Verify()

    Return container
End Function
```

For some reason, in the VB version, the app.Use() doesn't use the extension function that's available and simply uses IAppBuilder.Use() instead, as follows:

Function Use(middleware As Object, ParamArray args() As Object) As IAppBuilder

Why does the VB code not use the same extension function that C# does and how can I make it use that?

Edit

For clarity, the extension methods are not my own. They are from the Owin 3rd party library. So there is no option of renaming the extension methods.

答:
In VB (fiddle), you can pass a lambda expression when an object is required:

Public Shared Sub Main()
    MyMethod(Function() True)    ' compiles
End Sub

Public Shared Sub MyMethod(o As Object)
End Sub
```

<p>In C# (fiddle), that doesn't work:</p>

```public static void Main()
{
    // Compilation error: Cannot convert lambda expression to type 'object' because it is not a delegate type.
    // You'd need to use: MyMethod(new Func<bool>(() => true));
    MyMethod(() => true);
}

public static void MyMethod(object o) { }
```

<p>This is probably due to the fact that lambda expressions can be implicitly converted to delegates in VB but not in C#:</p>

<pre class="lang-vb prettyprint-override"><code>' Compiles
Dim d As System.Delegate = Function() True
</code>```

// Compilation error: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type
System.Delegate d = () => true;
```

<p>Thus, in your code example, VB finds a matching suitable instance method and uses it. In the C# code, no matching instance method is found (since your lambda expression does not match <code>object</code>), and the extension method is used instead.</p>

<p>Note that <em>both</em> languages prefer instance methods over extension methods if a matching method is found. This can lead to subtle bugs if a matching instance method is added later.</p>

<hr>

<p>How to fix that? I suggest to use different names for the extension method and the instance method - other developers reading your code in the future will thank you for it. If that's not an option, you can always call the extension method explicitly:</p>

```Owin.AppBuilderUserExtensions.Use(app, Async Sub(context, [next]) ...)
```

Body:
So I have the following code in C#:

public Container ConfigureSimpleInjector(IAppBuilder app)
{
    var container = new Container();

    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    container.RegisterPackages();

    app.Use(async (context, next) =>
    {
        using (AsyncScopedLifestyle.BeginScope(container))
        {
            await next();
        }
    });

    container.Verify();

    return container;
}

The app.Use() is defined as Owin.AppBuilderUserExtensions.Use() and looks like this:

public static IAppBuilder Use(this IAppBuilder app, Func<IOwinContext, Func<Task>, Task> handler);

The VB equivalent is as follows:

Public Function ConfigureSimpleInjector(app As IAppBuilder) As Container
    Dim container = New Container()

    container.Options.DefaultScopedLifestyle = New AsyncScopedLifestyle()

    container.RegisterPackages()

    app.Use(Async Sub(context, [next])
                Using AsyncScopedLifestyle.BeginScope(container)
                    Await [next]()
                End Using
            End Sub)

    container.Verify()

    Return container
End Function

For some reason, in the VB version, the app.Use() doesn't use the extension function that's available and simply uses IAppBuilder.Use() instead, as follows:

Function Use(middleware As Object, ParamArray args() As Object) As IAppBuilder

Why does the VB code not use the same extension function that C# does and how can I make it use that?

Edit

For clarity, the extension methods are not my own. They are from the Owin 3rd party library. So there is no option of renaming the extension methods.

Body:
In VB (fiddle), you can pass a lambda expression when an object is required:

Public Shared Sub Main()
    MyMethod(Function() True)    ' compiles
End Sub

Public Shared Sub MyMethod(o As Object)
End Sub

In C# (fiddle), that doesn't work:

public static void Main()
{
    // Compilation error: Cannot convert lambda expression to type 'object' because it is not a delegate type.
    // You'd need to use: MyMethod(new Func<bool>(() => true));
    MyMethod(() => true);
}

public static void MyMethod(object o) { }

This is probably due to the fact that lambda expressions can be implicitly converted to delegates in VB but not in C#:

' Compiles
Dim d As System.Delegate = Function() True

// Compilation error: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type
System.Delegate d = () => true;

Thus, in your code example, VB finds a matching suitable instance method and uses it. In the C# code, no matching instance method is found (since your lambda expression does not match object), and the extension method is used instead.

Note that both languages prefer instance methods over extension methods if a matching method is found. This can lead to subtle bugs if a matching instance method is added later.

How to fix that? I suggest to use different names for the extension method and the instance method - other developers reading your code in the future will thank you for it. If that's not an option, you can always call the extension method explicitly:

Owin.AppBuilderUserExtensions.Use(app, Async Sub(context, [next]) ...)


问:
Input Mask - Dynamic masking with decimals
I have written this code:

```<code>$(".mask_currency").inputmask({
    mask: "$ 9[99999].99",
    placeholder: "",
})
</code>```

I am trying to input:

1.234  // This is Allowed

123.45 // This not allowed until I type all the 6 digits before decimal.

I want to make dynamic mask so that users can do 0.99 or 1234.12.

Body:
I have written this code:

$(".mask_currency").inputmask({
    mask: "$ 9[99999].99",
    placeholder: "",
})

I am trying to input:

1.234  // This is Allowed

123.45 // This not allowed until I type all the 6 digits before decimal.

I want to make dynamic mask so that users can do 0.99 or 1234.12.

Body: $(".mask_currency").inputmask("9{1,5}.99");


问:
HTML map with css rollovers?
I have to create an html page for use on a CD. The navigation is an HTML map with co-ordinates set. When the user rolls over a co-ordinate, I want an image popup to appear beside it. There's 8 map links, and 8 corresponding image popups.

I could do this easily through jQuery, but the CD will be used on IE mainly. IE doesn't allow javascript to be run locally (without user interaction, which isn't acceptable).

Through jQuery I absolutely positioned the rollover images, but I can't set them visible through CSS with a hover. What's the best method to approach this?

答:
You could always try some serious styling effects based on the Pseudo-class of :hover.

Without knowing your markup I would tackle along these lines...

HTML Markup

```<code><div id="mapWrapper">
<ul id="map">
 <li id="location-01"><span>Map Text</span> <div class="item">Additional Pop Up Text</div></li>
 <li id="location-02"><span>Map Text</span> <div class="item">Additional Pop Up Text</div></li>
 <li id="location-03"><span>Map Text</span> <div class="item">Additional Pop Up Text</div></li>
 ....
</ul>
</div>
</code>```

CSS Code

```<code>#mapWrapper {position:relative;} /* include width, height and any bg imagery */
ul#map, #map li {margin:0;padding:0;list-style-type:none} /* just to reset the list to be standard in different browsers */
#location-01 {position:absolute;} /* include with, height and position top-left items as required */
#location-02 {position:absolute;} /* include with, height and position top-left items as required */
etc...
#map li .item {display:none; } /* hide the pop up text, include defaults for position based on the location of the li */
#map li:hover .item {display:block;} /* show the pop up text on hover of the LI*/

/* Note: If you need to position each pop item uniquely you could use something like... If you do, remember to move the :hover effect to be the last item in your style sheet */
#map li#location-01 .item {display:none; }
</code>```

Hope that helps you out, I have had to a similar map online (not with a CD) but wanted to do it without JS and that was the easiest way to do so.

Note:  If you need to offer IE6 support, you would probably be best changing the hover to be based on an ahref instead.

eg: Map Text Additional Pop Up Text

ContentLicense: CC BY-SA 2.5

Title: HTML map with css rollovers?

Body:
You could always try some serious styling effects based on the Pseudo-class of :hover.

Without knowing your markup I would tackle along these lines...

HTML Markup

<div id="mapWrapper">
<ul id="map">
 <li id="location-01"><span>Map Text</span> <div class="item">Additional Pop Up Text</div></li>
 <li id="location-02"><span>Map Text</span> <div class="item">Additional Pop Up Text</div></li>
 <li id="location-03"><span>Map Text</span> <div class="item">Additional Pop Up Text</div></li>
 ....
</ul>
</div>

CSS Code

#mapWrapper {position:relative;} /* include width, height and any bg imagery */
ul#map, #map li {margin:0;padding:0;list-style-type:none} /* just to reset the list to be standard in different browsers */
#location-01 {position:absolute;} /* include with, height and position top-left items as required */
#location-02 {position:absolute;} /* include with, height and position top-left items as required */
etc...
#map li .item {display:none; } /* hide the pop up text, include defaults for position based on the location of the li */
#map li:hover .item {display:block;} /* show the pop up text on hover of the LI*/

/* Note: If you need to position each pop item uniquely you could use something like... If you do, remember to move the :hover effect to be the last item in your style sheet */
#map li#location-01 .item {display:none; }

Hope that helps you out, I have had to a similar map online (not with a CD) but wanted to do it without JS and that was the easiest way to do so.

Note:  If you need to offer IE6 support, you would probably be best changing the hover to be based on an ahref instead.

eg: Map Text Additional Pop Up Text


问:
CSV file not reloading (Google GeoCharts)
I am loading csv file using https://github.com/evanplaice/jquery-csv. Everything works okay until I try to reload the .csv file and load new data into GeoCharts. I know its a problem with reloading the file but how to deal with it? Here is the example code:</p>

```<code>function load(file, colorForSex){

    var region = $('select[name="region"] option:selected').val();

    setTimeout(1000);

    $.get(file, function(data) {

        var newData = $.csv.toArrays(data);

        var j = 1;

        for (var i = 1; i < newData.length; i++) {
           newData[i][j] = parseFloat(newData[i][j]);
        }

    }, 'text');

    console.log(newData[1][1]);

    setTimeout(1000);

    var data = google.visualization.arrayToDataTable(newData);

    var options = {
        region: region,
        backgroundColor: 'none',
        chartArea: { width: '100%', height: '100%' },
        colorAxis: {colors: ['#ddd', colorForSex]},
        datalessRegionColor: 'white',
        legend: {
            numberFormat: '.##',
            textStyle: {
                fontName: 'Verdana',
                color: '#ff1a1a',
                fontSize: 14
            }
        }
    };

    setTimeout(1000);

    chart.draw(data, options);
}
</code>```

答:
need to include the rest of the chart code in the $.get function

$.get is asynchronous

as such, the code after the $.get function runs before the $.get function finishes

see following snippet...

```<code>function loadData(file, colorForSex){
  var region = $('select[name="region"] option:selected').val();
  var file = file + '?q=' + Math.random();
  $.get(file, function(data) {
    var processedData = $.csv.toArrays(data);
    var j = 1;
    for (var i = 1; i < processedData.length; i++) {
      processedData[i][j] = parseFloat(processedData[i][j]);
    }

    var data = google.visualization.arrayToDataTable(processedData);

    var options = {
      region: region,
      backgroundColor: 'none',
      chartArea: { width: '100%', height: '100%' },
      colorAxis: {colors: ['#ddd', colorForSex]},
      datalessRegionColor: 'white',
      legend: {
        numberFormat: '.##',
        textStyle: {
            fontName: 'Verdana',
            color: '#ff1a1a',
            fontSize: 14
        }
      }
    };

    chart.draw(data, options);
  }, 'text');
}
</code>```

Body:
I am loading csv file using https://github.com/evanplaice/jquery-csv. Everything works okay until I try to reload the .csv file and load new data into GeoCharts. I know its a problem with reloading the file but how to deal with it? Here is the example code:

function load(file, colorForSex){

    var region = $('select[name="region"] option:selected').val();

    setTimeout(1000);

    $.get(file, function(data) {

        var newData = $.csv.toArrays(data);

        var j = 1;

        for (var i = 1; i < newData.length; i++) {
           newData[i][j] = parseFloat(newData[i][j]);
        }

    }, 'text');

    console.log(newData[1][1]);

    setTimeout(1000);

    var data = google.visualization.arrayToDataTable(newData);

    var options = {
        region: region,
        backgroundColor: 'none',
        chartArea: { width: '100%', height: '100%' },
        colorAxis: {colors: ['#ddd', colorForSex]},
        datalessRegionColor: 'white',
        legend: {
            numberFormat: '.##',
            textStyle: {
                fontName: 'Verdana',
                color: '#ff1a1a',
                fontSize: 14
            }
        }
    };

    setTimeout(1000);

    chart.draw(data, options);
}

Body:
need to include the rest of the chart code in the $.get function

$.get is asynchronous

as such, the code after the $.get function runs before the $.get function finishes

see following snippet...

function loadData(file, colorForSex){
  var region = $('select[name="region"] option:selected').val();
  var file = file + '?q=' + Math.random();
  $.get(file, function(data) {
    var processedData = $.csv.toArrays(data);
    var j = 1;
    for (var i = 1; i < processedData.length; i++) {
      processedData[i][j] = parseFloat(processedData[i][j]);
    }

    var data = google.visualization.arrayToDataTable(processedData);

    var options = {
      region: region,
      backgroundColor: 'none',
      chartArea: { width: '100%', height: '100%' },
      colorAxis: {colors: ['#ddd', colorForSex]},
      datalessRegionColor: 'white',
      legend: {
        numberFormat: '.##',
        textStyle: {
            fontName: 'Verdana',
            color: '#ff1a1a',
            fontSize: 14
        }
      }
    };

    chart.draw(data, options);
  }, 'text');
}


问:
Django bootstrap to have both call a view and modal in same anchor tag
I am using Django and pretty new to it. My purpose is to trigger an asynchronous view from the template and stay in the same page showing a pop up that the process is triggered.
I searched a lot for a solution but couldn't work it out.

I am able to stay in the same page and trigger the view asynchronously using Celery but my problem is my modal is displaying the content of my web page and not the content I have mentioned in the modal content.

I am passing the view in the anchor tag href and modal in data-target.

Below is the code of my template:

```<code><!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>DashBoard</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
   <nav class="navbar navbar-inverse">

      <div class="container-fluid">
         <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar">
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
           </button>
           <a class="navbar-brand" href="#">DashBoard</a>
        </div>

    <div class="collapse navbar-collapse" id="topNavBar">
        <ul class="nav navbar-nav">
            <li class="active">
                <a href="#">
                    <span class="#" aria-hidden="true"></span>  Reports
                </a>
            </li>
            <li class="">
                <a href="#">
                    <span class="#" aria-hidden="true"></span>  Projects
                </a>
            </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <li class="">
                <li class="">
                    <a data-toggle="modal" href="{% url 'update-field' %}" data-target="#myModal">
                    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>  Update-Fields
                </a>
                <!-- Modal -->
                <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">×</button>
                            <h4 class="modal-title">Field Param Update</h4>
                        </div>
                        <div class="modal-body">
                            <p>Update is triggered in the backend. An email will be sent when done.</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                  </div>
                </div>
            </li>
            <li class="">
                <a href="#">
                    <span class="glyphicon glyphicon-off" aria-hidden="true"></span>  Logout
                </a>
            </li>
        </ul>
    </div>
</div>

</nav>
</body>
</html>
</code>```

Here "update-field" is the view which is been called to trigger the background process. Any help will be grateful. Thanks in advance.

EDIT:
I am getting the below in my modal which is same as my webpage.

答:
For the closure of the above issue did the following changes:

in the template, moved the modal code to separate html template:

```<code><li class="">
     <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
         <div class="modal-dialog">
               <div class="modal-content"></div>
         </div>
     </div>
     <a data-toggle="modal" href="{% url 'update-field' %}" data-target="#myModal">
           <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>  Update-Fields
     </a>
 </li>
</code>```

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

{{ title }}

{{ body }}

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

```
<pre class="lang-py prettyprint-override"><code># views.py

class UpdateFields(UpdateView):
    def get(self, request):
        updateparams.delay()
        context = {
            'title': 'Initiating task...',
            'body': 'Field parameters update has started. An email will be sent when its complete.'
        }
        return render(request, 'app/modal.html', context)
</code>```

# urls.py

url(r'^update/', views.UpdateFields.as_view(), name='update-field')
```

Body:
I am using Django and pretty new to it. My purpose is to trigger an asynchronous view from the template and stay in the same page showing a pop up that the process is triggered.
I searched a lot for a solution but couldn't work it out.

I am able to stay in the same page and trigger the view asynchronously using Celery but my problem is my modal is displaying the content of my web page and not the content I have mentioned in the modal content.

I am passing the view in the anchor tag href and modal in data-target.

Below is the code of my template:

<!DOCTYPE html>

   <meta charset="UTF-8">
   <title>DashBoard</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar">

           </button>
           DashBoard

                      Reports

                      Projects

                      Update-Fields

                            <button type="button" class="close" data-dismiss="modal">×</button>

Field Param Update

Update is triggered in the backend. An email will be sent when done.

                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                      Logout

Here "update-field" is the view which is been called to trigger the background process. Any help will be grateful. Thanks in advance.

EDIT:
I am getting the below in my modal which is same as my webpage.

Body:
For the closure of the above issue did the following changes:

in the template, moved the modal code to separate html template:

<li class="">
     <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
         <div class="modal-dialog">
               <div class="modal-content"></div>
         </div>
     </div>
     <a data-toggle="modal" href="{% url 'update-field' %}" data-target="#myModal">
           <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>&nbsp; Update-Fields
     </a>
 </li>

<!-- modal.html -->

<!-- Modal -->
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">{{ title }}</h4>
</div>
<div class="modal-body">
    <p>{{ body }}</p>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>

<script>
   $('#myModal').on('hidden.bs.modal', function () {
       location.reload();});     // reloads the current page
</script>

# views.py

class UpdateFields(UpdateView):
    def get(self, request):
        updateparams.delay()
        context = {
            'title': 'Initiating task...',
            'body': 'Field parameters update has started. An email will be sent when its complete.'
        }
        return render(request, 'app/modal.html', context)

# urls.py

url(r'^update/', views.UpdateFields.as_view(), name='update-field')


问:
Attribute error while trying to save excel file with win32
The following is line 684 from code

```<code>try:
  xlBook.SaveAs("%s/ContingencyFile.xlsx" %(os.getcwd()))
  xlApp.DisplayAlerts = True
except:
  xlApp.xlBook.Close
  xlBook.SaveAs("%s/ContingencyFile.xlsx" %(os.getcwd()))
  xlApp.DisplayAlerts = True
</code>```

This is the error that I come across while running my program -

```<code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "H:\proj4\combine.py", line 684, in ProcessNewFile
xlApp.xlBook.Close
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 516,
in__getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Excel.Application.xlBook
</code>```

How can i get rid of the error?

答:
Try with

```<code>xlBook.Close() # or xlApp.xlBook.Close() ?
</code>```

You're not calling a method without the () that's why it raises this AttributeError.

(maybe do the SaveAs(...) before ?, i'm not sure... )

Body:
The following is line 684 from code

try:
  xlBook.SaveAs("%s/ContingencyFile.xlsx" %(os.getcwd()))
  xlApp.DisplayAlerts = True
except:
  xlApp.xlBook.Close
  xlBook.SaveAs("%s/ContingencyFile.xlsx" %(os.getcwd()))
  xlApp.DisplayAlerts = True

This is the error that I come across while running my program -

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "H:\proj4\combine.py", line 684, in ProcessNewFile
xlApp.xlBook.Close
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 516,
in__getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Excel.Application.xlBook

How can i get rid of the error?

Body:
Try with

xlBook.Close() # or xlApp.xlBook.Close() ?

You're not calling a method without the () that's why it raises this AttributeError.

(maybe do the SaveAs(...) before ?, i'm not sure... )


问:
Insertion in Binary Tree (Not BST) Python
I'm trying to insert a node in my binary tree. However, I don't know the proper way to do this. I understand that I should run a bfs and insert in the first null position. How do I translate that into a code?

I was trying with DFS:
The tree looks like this:

```<code>class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
def insert(node, val):
     if not node:
           return Node(val)
     if not node.left:
           node.left = Node(val)
           return
     if not node.right:
           node.right = Node(val)
           return
     return insert(node.left, val)
     return insert(node.right, val)

n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8
</code>```

But that gives me an unreachable code.
What is the proper way to do this? I'm pretty frustrated by the people calling Binary Tree where they really mean BST.

答:
Alright! So I hope this is what you are looking for, but your code is very good, it just needs a few changes:

```<code>class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

    def __str__(self): #This allows you to print out the nodes for testing, other "magic" methods can be created here too!
        return str(self.val)

def insert(node, val=None):
     if not val:
        return Node(node) #This will create a new node if val is None
     if not node.left:
           node.left = val
           return
     if not node.right:
           node.right = val
           return
     return insert(node.left, val)
     return insert(node.right, val)

def main():
     n1 = insert(1)
     n2 = insert(2)
     n3 = insert(3)
     n4 = insert(4)
     n5 = insert(5)
     n6 = insert(6)
     n7 = insert(7)
     n8 = insert(8)

     insert(n1, n2)
     insert(n1, n3)
     insert(n2, n4)
     insert(n2, n5)
     insert(n3, n6)
     insert(n3, n7)
     insert(n4, n8)

     print(n1.left)
     print(n3.left)

main()
</code>```

This worked for my tests! I changed the logic behind insert() in order to allow the function to create new Nodes (though I know that is not necessarily how you want it done, you can change that back!). There are a plethora of other ways to implement this, though, but this is the closest I could think of that stayed true to your original code.

Hope it helps!

PS
Another great resource is Interactive Python (granted the chapter is about BSTs). It can still be useful going forward!

Body:
I'm trying to insert a node in my binary tree. However, I don't know the proper way to do this. I understand that I should run a bfs and insert in the first null position. How do I translate that into a code?

I was trying with DFS:
The tree looks like this:

class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
def insert(node, val):
     if not node:
           return Node(val)
     if not node.left:
           node.left = Node(val)
           return
     if not node.right:
           node.right = Node(val)
           return
     return insert(node.left, val)
     return insert(node.right, val)

n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8

But that gives me an unreachable code.
What is the proper way to do this? I'm pretty frustrated by the people calling Binary Tree where they really mean BST.

Body:
Alright! So I hope this is what you are looking for, but your code is very good, it just needs a few changes:

class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

    def __str__(self): #This allows you to print out the nodes for testing, other "magic" methods can be created here too!
        return str(self.val)

def insert(node, val=None):
     if not val:
        return Node(node) #This will create a new node if val is None
     if not node.left:
           node.left = val
           return
     if not node.right:
           node.right = val
           return
     return insert(node.left, val)
     return insert(node.right, val)

def main():
     n1 = insert(1)
     n2 = insert(2)
     n3 = insert(3)
     n4 = insert(4)
     n5 = insert(5)
     n6 = insert(6)
     n7 = insert(7)
     n8 = insert(8)

     insert(n1, n2)
     insert(n1, n3)
     insert(n2, n4)
     insert(n2, n5)
     insert(n3, n6)
     insert(n3, n7)
     insert(n4, n8)

     print(n1.left)
     print(n3.left)

main()

This worked for my tests! I changed the logic behind insert() in order to allow the function to create new Nodes (though I know that is not necessarily how you want it done, you can change that back!). There are a plethora of other ways to implement this, though, but this is the closest I could think of that stayed true to your original code.

Hope it helps!

PS
Another great resource is Interactive Python (granted the chapter is about BSTs). It can still be useful going forward!


问:
TFS Gated Check In - Send Email Notification only to the Build Requester if the build fails
I am using TFS 2015 for Continuous Integrations and Deployment. I have set up the Gated Check in for my build definition.

Question: Is there any way to send an email alerts to the developer who requested the build if the build fails?

I understand that, We have TFS Alerts for sending an email based on the build status but That needs Email addresses to be explicitly specified to send email.

Is there any other option or some keyword which I can mention in the "Send To" field so that I can send the build fail email only to the person who requested the build.

Thanks

答:
I think there is no direct option, developers can subscribe to the TFS custom alerts.

Check This ==> TFS Alerts and Notifications

Refer It here for more Info


问:
REST API not works
I'm working on a project and we're using dspace6 and I want to use the api rest. According to the documentation it is already present, but it needs to configure some things.

I made the settings but when access / rest is redirected to another port using SSL.

I've also disabled SSL but so far nothing.

Does anyone know how to install api rest on dspace 6?

答:
According to the official documentation on installing the DSpace 6 REST API, what you need to do is this:

Installing the REST API

The REST API deploys as a standard webapp for your servlet container / tomcat. For example, depending on how you deploy webapps, one way would be to alter tomcat-home/conf/server.xml and add:

```<code><Context path="/rest"  docBase="/dspace/webapps/rest" />
</code>```

In DSpace 4, the initial/official Jersey-based REST API was added to DSpace. > The DSpace 4 REST API provides READ-ONLY access to DSpace Objects.

In DSpace 5, the REST API adds authentication, allows Creation, Update, and Delete to objects, can access restricted materials if authorized, and it requires SSL.

Disabling SSL

For localhost development purposes, SSL can add additional getting-started difficulty, so security can be disabled. To disable DSpace REST's requirement to require security/ssl, alter [dspace]/webapps/rest/WEB-INF/web.xml or [dspace-source]/dspace-rest/src/main/webapp/WEB-INF/web.xml and comment out the  block, and restart your servlet container. Production usages of the REST API should use SSL, as authentication credentials should not go over the internet unencrypted.

Which of these steps have you done? Did you restart your servlet container (eg tomcat)? Then what do you use to test the REST API, and what happens -- you need to show the actual URL you use and the response.

Title: REST API not works

Body:
According to the official documentation on installing the DSpace 6 REST API, what you need to do is this:

Installing the REST API

The REST API deploys as a standard webapp for your servlet container / tomcat. For example, depending on how you deploy webapps, one way would be to alter tomcat-home/conf/server.xml and add:

<Context path="/rest"  docBase="/dspace/webapps/rest" />

In DSpace 4, the initial/official Jersey-based REST API was added to DSpace. > The DSpace 4 REST API provides READ-ONLY access to DSpace Objects.

In DSpace 5, the REST API adds authentication, allows Creation, Update, and Delete to objects, can access restricted materials if authorized, and it requires SSL.

Disabling SSL

For localhost development purposes, SSL can add additional getting-started difficulty, so security can be disabled. To disable DSpace REST's requirement to require security/ssl, alter [dspace]/webapps/rest/WEB-INF/web.xml or [dspace-source]/dspace-rest/src/main/webapp/WEB-INF/web.xml and comment out the  block, and restart your servlet container. Production usages of the REST API should use SSL, as authentication credentials should not go over the internet unencrypted.

Which of these steps have you done? Did you restart your servlet container (eg tomcat)? Then what do you use to test the REST API, and what happens -- you need to show the actual URL you use and the response.


问:
making a 1D array that contains all the value of a multidimensional array
the way I did this was:

```<code>self.cleaned = []
for a in self.P[-1]:
    for b in a:
        for c in b:
            for d in c:
                self.cleaned.extend(d)
</code>```

which is quite ugly and unintuitive, is there a proper way of doing this? maybe using numpy

答:
You can flatten directly with numpy using np.ndarray.flatten:

```<code>self.cleaned = np.array(self.P).flatten()
</code>```

Body:
the way I did this was:

self.cleaned = []
for a in self.P[-1]:
    for b in a:
        for c in b:
            for d in c:
                self.cleaned.extend(d)

which is quite ugly and unintuitive, is there a proper way of doing this? maybe using numpy

Body:
You can flatten directly with numpy using np.ndarray.flatten:

self.cleaned = np.array(self.P).flatten()


问:
`mongolab` - getting error on post, not able to post a data
I have a account with mongolab(mlab). I am trying to post a data for the users using postman add-on from chrome browser. I am getting error always. I could not able to post a data. I have tried with other diffrent ways. but no luck.

any one help me to sort this issue?

here is my api.js :

```<code>var
    User        = require('../models/user'),
    config      = require('../../config'),
    secretKey   = config.secretKey;

module.exports = function( app, express ) {

    var api = express.Router();

    api.post('/signup', function (req, res) {

        var user = new User({

            name:req.body.name,
            username:req.body.username,
            password:req.body.password

        });

        user.save(function(err){

            if(err){
                res.send(err);
                return;
            }

            res.json({message:'User has been Created!'});
        });
    });

    api.get('/users', function(req, res) {

        User.find({}, function( req, users){
            if(err) {
                res.send(err);
                return;
            }

            res.json(users);
        })

    });

    return api;

}
</code>```

config.js :

```<code>module.exports = {
    "database":"mongodb://xxx:xxxx@ds015700.mlab.com:15700/arifstory",
    "port" : process.env.PORT || 3000,
    "secretKey" : "YourSecretKey"
}
</code>```

And the user.js :

```<code>var
    mongoose    = require('mongoose'),
    Schema      = mongoose.Schema,
    bcrypt      = require('bcrypt-nodejs');

var UserSchema = new Schema({

    name : String,
    userName:{ type:String, required:true, index : { unique: true }},
    password : { type:String, required : true, select : false }

});

UserSchema.pre('save', function(next) {

    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.hash( user.password, null, null, function(err, hash) {
        if(err) return next(err);

        user.password = hash;
        next();
    });

});

UserSchema.methods.comparePassword = function( password ) {

    var user = this;

    return bcrypt.compareSync(password, user.password);

}

module.exports = mongoose.model('User', UserSchema);
</code>```

I really unable to understand the issue here. please any one help me?

error

```<code>{
  "message": "User validation failed",
  "name": "ValidationError",
  "errors": {
    "userName": {
      "message": "Path `userName` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "userName"
      },
      "kind": "required",
      "path": "userName"
    },
    "password": {
      "message": "Path `password` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "password"
      },
      "kind": "required",
      "path": "password"
    }
  }
}
</code>```

答:
The data sent from chrome could be undefined.

Print it in console by including the below 2 lines above user.save function in api.js file:
console.log(req.body.username);
console.log(req.body.password);

if it shows as undefined, then make sure to check "x-www-form-urlencoded" under "body" in Postman and provide username and password under that.

Body:
I have a account with mongolab(mlab). I am trying to post a data for the users using postman add-on from chrome browser. I am getting error always. I could not able to post a data. I have tried with other diffrent ways. but no luck.

any one help me to sort this issue?

here is my api.js :

var
    User        = require('../models/user'),
    config      = require('../../config'),
    secretKey   = config.secretKey;

module.exports = function( app, express ) {

    var api = express.Router();

    api.post('/signup', function (req, res) {

        var user = new User({

            name:req.body.name,
            username:req.body.username,
            password:req.body.password

        });

        user.save(function(err){

            if(err){
                res.send(err);
                return;
            }

            res.json({message:'User has been Created!'});
        });
    });

    api.get('/users', function(req, res) {

        User.find({}, function( req, users){
            if(err) {
                res.send(err);
                return;
            }

            res.json(users);
        })

    });

    return api;

}

config.js :

module.exports = {
    "database":"mongodb://xxx:xxxx@ds015700.mlab.com:15700/arifstory",
    "port" : process.env.PORT || 3000,
    "secretKey" : "YourSecretKey"
}

And the user.js :

var
    mongoose    = require('mongoose'),
    Schema      = mongoose.Schema,
    bcrypt      = require('bcrypt-nodejs');

var UserSchema = new Schema({

    name : String,
    userName:{ type:String, required:true, index : { unique: true }},
    password : { type:String, required : true, select : false }

});

UserSchema.pre('save', function(next) {

    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.hash( user.password, null, null, function(err, hash) {
        if(err) return next(err);

        user.password = hash;
        next();
    });

});

UserSchema.methods.comparePassword = function( password ) {

    var user = this;

    return bcrypt.compareSync(password, user.password);

}

module.exports = mongoose.model('User', UserSchema);

I really unable to understand the issue here. please any one help me?

error

{
  "message": "User validation failed",
  "name": "ValidationError",
  "errors": {
    "userName": {
      "message": "Path `userName` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "userName"
      },
      "kind": "required",
      "path": "userName"
    },
    "password": {
      "message": "Path `password` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "password"
      },
      "kind": "required",
      "path": "password"
    }
  }
}


问:
How do I remove a directory from a Git repository?
How can I delete a single directory containing files from a Git repository?</p>

答:
First git command need to know who you are before deleting anything

git init

git config user.name "someone"

git config user.email "someone@someplace.com"

 git rm -r

git commit -m "deleting dir"

git push origin master


问:
Cloning with jQuery
I have a form that allows users to refer friends. I want to add a link below the two input fields, "friend email" and "friend name", that will clone "friend-box" one time and add it below. In addition, the name attribute of "friend email" and "friend name" are name="friend_email[0]" and name="friend_name[0]" as suggested here. What's the best way to clone and increment the subscript? Here's the code:

```<code><div class="friend-box">

    <div class="field">
        <span><label for='friend_name'><strong>Friend's Name *</strong></label> </span>
        <input id='friend_name' name='friend_name[0]' type='text' />
    </div>

    <div class="field">
        <span><label for='friend_email'><strong>Friend's Email *</strong></label></span>
        <input id='friend_email' name='friend_email[0]' type='text' />
    </div>

</div>
</code>```

What's the best way to do this? One of the problems I had for example, is that when I cloned "friend-box" once and then twice, it obviously cloned it exponentially. So I'm guessing I need to have an ID number in there as well and increment it. Or, which is another method I saw, is to clone the "friend-box" when the page loads and keep cloning it from memory.

Thanks,
Ryan

答:
I have created an example here:
http://jsfiddle.net/K8hhW/5/

You do not need to worry about incrementing the numbers in the brackets, the form does this automatically for you.

Title: Cloning with jQuery

Body:
I have a form that allows users to refer friends. I want to add a link below the two input fields, "friend email" and "friend name", that will clone "friend-box" one time and add it below. In addition, the name attribute of "friend email" and "friend name" are name="friend_email[0]" and name="friend_name[0]" as suggested here. What's the best way to clone and increment the subscript? Here's the code:

        Friend's Name *
        <input id='friend_name' name='friend_name[0]' type='text' />

        Friend's Email *
        <input id='friend_email' name='friend_email[0]' type='text' />

What's the best way to do this? One of the problems I had for example, is that when I cloned "friend-box" once and then twice, it obviously cloned it exponentially. So I'm guessing I need to have an ID number in there as well and increment it. Or, which is another method I saw, is to clone the "friend-box" when the page loads and keep cloning it from memory.

Thanks,
Ryan


问:
Symfony: An exception occured in driver: could not find driver with mysql
I'm trying to connect with my DB (mysql) which is running on a server (docker). I'm programming on Windows.

In my symfony project I have done the following:
parameters.yml

-> filled in the correct parameters

config.yml

```<code>doctrine:
    dbal:
        driver: pdo_mysql
        host: '%database_host%'
        port: '%database_port%'
        dbname: '%database_name%'
        user: '%database_user%'
        password: '%database_password%'
</code>```

php.ini

```<code>extension=php_mysqli.dll
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll
</code>```

After all of this I get the following error: An exception occured in driver: could not find driver

Anyone who can help since I have tried some solutions that were provided but none worked or were for linux systems.

答:
You must install mysql :</p>
```<code>sudo apt install php-mysql
</code>```

Body:
I'm trying to connect with my DB (mysql) which is running on a server (docker). I'm programming on Windows.

In my symfony project I have done the following:
parameters.yml

-> filled in the correct parameters

config.yml

doctrine:
    dbal:
        driver: pdo_mysql
        host: '%database_host%'
        port: '%database_port%'
        dbname: '%database_name%'
        user: '%database_user%'
        password: '%database_password%'

php.ini

extension=php_mysqli.dll
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll

After all of this I get the following error: An exception occured in driver: could not find driver

Anyone who can help since I have tried some solutions that were provided but none worked or were for linux systems.

Body:
You must install mysql :

sudo apt install php-mysql


问:
PrimeNG Datatable does not allow add components to the rows
I am using PrimeNG Datatable (https://www.primefaces.org/primeng/#/datatable) with lazy loading. Everything works great but I need to add a button in every row (with options to delete, edit each record).

I tried somehow to add the column in every row in the view, but couldn't figure it out.

Then I tried to add the HTML in the controller array that is used by the datatable:

```<code>private addActionsToRow(rows) {

    let rowsWithAction = [];
    for(let row of rows) {
        row['actions'] = '<div>Anything</div>'
        rowsWithAction.push(row);
    }

    return rowsWithAction;

}
</code>```

However it does not evaluate the code and displays the plain HTML
Anything
.

It there a way to it?

答:
Here is what i did to add a delete button to each row-

```<code> <p-column [style]="{'width':'38px'}">
      <ng-template let-h="rowData" pTemplate="body">
           <button class="ui-button-danger" type="button"  pButton (click)="deleteVendorRecord(h)" icon="fa-remove"></button>
      </ng-template>
 </p-column>
</code>```

Then in the ts file created a function deleteVendorRecord that accepts a row

```<code>deleteVendorRecord(row):void{
     this.vendorRecords.splice(this.vendorRecords.indexOf(row),1);
}
</code>```

Body:
I am using PrimeNG Datatable (https://www.primefaces.org/primeng/#/datatable) with lazy loading. Everything works great but I need to add a button in every row (with options to delete, edit each record).

I tried somehow to add the column in every row in the view, but couldn't figure it out.

Then I tried to add the HTML in the controller array that is used by the datatable:

private addActionsToRow(rows) {

    let rowsWithAction = [];
    for(let row of rows) {
        row['actions'] = '
Anything
'
        rowsWithAction.push(row);
    }

    return rowsWithAction;

}

However it does not evaluate the code and displays the plain HTML
Anything
.

It there a way to it?

Body:
Here is what i did to add a delete button to each row-

 <p-column [style]="{'width':'38px'}">
      <ng-template let-h="rowData" pTemplate="body">
           <button class="ui-button-danger" type="button"  pButton (click)="deleteVendorRecord(h)" icon="fa-remove"></button>
      </ng-template>
 </p-column>

Then in the ts file created a function deleteVendorRecord that accepts a row

deleteVendorRecord(row):void{
     this.vendorRecords.splice(this.vendorRecords.indexOf(row),1);
}


问:
c++ Valgrind: Address 0x0 is not stack'd, malloc'd or (recently) free'd
I am learning a bit of programming and I am trying to code an Ant Colony algorithm for QAP, the problem is that sometimes I get segmentation fault and when I use valgrind it tells me "Address 0x0 is not stack'd, malloc'd or (recently) free'd". This is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>  //ifstream
#include <string>
#include <sstream>
#include <vector>
#include <utility> //pair
#include <iostream>
#include <algorithm> //shuffle
#include <random> //default_random_engine
#include <chrono> //chrono::system_clock
#include <cstdlib> // rand
#include <unistd.h>
#include <csignal>
using namespace std;

sig_atomic_t volatile done = 0;
void game_over(int) { done = 1; }

int funCosto(int dim,vector<int> sol,vector<int> dist, vector<int> flujo){
    int costo = 0;
    for (int i = 0; i<dim;i++){
        for (int j = i+1; j<dim;j++){
            // El costo es la * del valor de los flujos por la permutacion de las distancias
            costo += flujo[dim*i+j] * dist[dim*(sol[i]-1) + (sol[j]-1)];
        }
    }
    return costo*2; //La matriz es simétrica
}

int buscarLista(vector<int> lista, int elemento, int dim){
    int aux = 0;
    for (int i = 0; i < dim; i++){
        if (lista[i] == elemento){aux = 1;}
    }
    return aux;
}

vector<int> localSearch(int dim,vector<int> sol, vector<int> dist, vector<int> flujo){

    vector<int> solActual(dim), solAux(dim);
    solActual = sol;
    int mejorCosto = funCosto(dim,solActual,dist,flujo);
    int costoActual, mejorCostoAnterior;

    do{
        mejorCostoAnterior = mejorCosto; // para determinar que se llegó a un óptimo local
        for (int i = 0; i < dim; i++){
            for (int j = i+1; j < dim; j++){
                solAux = solActual;
                solAux[i] = solActual[j];
                solAux[j] = solActual[i]; //intercambiamos dos elementos
                /*Importante, hay que optimizar el cálculo del costo de los vecinos*/
                costoActual = funCosto(dim,solAux,dist,flujo);
                if (costoActual<mejorCosto){
                    break;
                }
            }
            if (costoActual < mejorCosto){
                mejorCosto = costoActual; //se actualiza el mejor costo
                solActual = solAux; //se efectua el movimiento
                break;
            }
        }
    } while (mejorCosto < mejorCostoAnterior); //se detiene cuando ya no hay mejoría

    return solActual;
}

pair<int,vector<int>> antColony(int numAnts, int dim, vector<int> dist, vector<int> flujo){

    done = 0;
    std::signal(SIGALRM, game_over);
    alarm(300);

    vector<vector<int>> hormigas(numAnts, vector<int>(dim));
    vector<vector<int>> hormigasNuevas(numAnts, vector<int>(dim));
    vector<vector<double>> feromonas(dim, vector<double>(dim));
    vector<int> mejorSol, mejorSolNueva;
    double mejorCosto, mejorCostoNuevo, totalFer, prob, auxProb, probAcum = 0 ;
    int numSwaps = dim/3;  // número de cambios que va a hacer cada hormiga en cada iteración
    random_device rd; // obtener un número aleatorio de hardware
    mt19937 eng(rd()); // semilla para el generador
    uniform_int_distribution<> disInt(0,dim-1);
    uniform_real_distribution<> disReal(0,1);
    int prim, seg, aux, contadorRep, sinMejoria = 0; //indices
    int inten = 1; //la intensificación está prendida al comienzo

    for (int i = 1; i <= dim; i++){
        hormigas[0][i-1] = i;
    }
    for (int j = 1; j < numAnts; j++){
        hormigas[j] = hormigas[0];
    }
    //obtener una semilla basada en el tiempo
    for (int k = 0; k < numAnts; k++){
        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
        shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
    }

    for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
        hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
    }

    mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
    mejorSol = hormigas[0];
    for (int i = 1; i < numAnts; i++){
        if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
            mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
            mejorSol = hormigas[i];
        }
    }
    for (int i = 0; i<dim; i++){
        for (int j = 0 ; j<dim; j++){
            feromonas[i][j] = 1.0/(100*mejorCosto);
        }
    }

    for (int z = 0; z < 1; z++){ //máximo número de iteraciones

        for (int i = 0; i < numAnts; i++ ){

            hormigasNuevas[i] = hormigas[i];

            for (int j = 0; j < numSwaps; j++){
                prim = disInt(eng);
                auxProb = disReal(eng);
                seg = -1;
                probAcum = 0;
                do{
                    seg++;
                    if (seg == prim){seg++;}
                    totalFer = 0; //limpiamos para esta iteración
                    for (int k = 0; k < dim; k++){
                        if (k != prim){
                            totalFer += feromonas[prim][hormigasNuevas[i][k]-1] + feromonas[k][hormigasNuevas[i][prim]-1];
                        }
                    }
                    //construimos la probabilidad con la que es aceptado el cambio segun las feromonas
                    prob = (feromonas[prim][hormigasNuevas[i][seg]-1]+feromonas[seg][hormigasNuevas[i][prim]-1]) / totalFer;
                    probAcum += prob;
                }while ((auxProb > probAcum) && (seg < dim));

                if (seg == dim){seg--;}

                aux = hormigasNuevas[i][prim];
                hormigasNuevas[i][prim] = hormigasNuevas[i][seg];
                hormigasNuevas[i][seg] = aux;

            }
            //mejoramos la solución modificada por la hormiga
            hormigasNuevas[i] = localSearch(dim,hormigasNuevas[i],dist,flujo);
        }

        //contadorRep = 0;
        //intensificación
        for (int a = 0; a < numAnts; a++){
            if (inten == 1){
                if (funCosto(dim,hormigasNuevas[a],dist,flujo) < funCosto(dim,hormigas[a],dist,flujo)){
                    hormigas[a] = hormigasNuevas[a];
                }
                else{ contadorRep++;} //para contar cuantas veces se queda con la respuesta anterior
            }
            else{
                hormigas[a] = hormigasNuevas[a];
            }
        }

        //if (contadorRep == numAnts){inten = 0;} //apaga la intensificación

        mejorCostoNuevo = funCosto(dim,hormigas[0],dist,flujo);
        for (int b = 1; b < numAnts; b++){
            if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
                mejorCostoNuevo = funCosto(dim,hormigas[b],dist,flujo);
                mejorSolNueva = hormigas[b];
            }
        }

        if (mejorCostoNuevo < mejorCosto){
            //si se consigue una mejor solucíón
            mejorCosto = mejorCostoNuevo;
            mejorSol = mejorSolNueva;
            inten = 1;
            sinMejoria = 0;
        }

        //actualiación de la matriz de feromonas
        for (int c = 0; c < dim; c++){
            for (int d = 0; d < dim; d++){ //Evaporación
                feromonas[c][d] = 0.9*feromonas[c][d];
            }
        }

        for (int e = 0; e < dim; e++){//reforzamos la mejor solución
            feromonas[e][mejorSol[e]-1] = feromonas[e][mejorSol[e]-1] + 0.1/mejorCosto;
        }

        //diversificación
        if (sinMejoria > dim/2){

            hormigas[0] = mejorSol; //se queda la mejor solución hasta el momento
            //se vuelve a inicializar las hormigas
            for (int k = 1; k < numAnts; k++){
                unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
                shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
            }

            for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
                hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
            }

            mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
            mejorSol = hormigas[0];
            for (int i = 1; i < numAnts; i++){
                if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
                    mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
                    mejorSol = hormigas[i];
                }
            }

            //renovar la matriz de feromonas
            for (int i = 0; i<dim; i++){
                for (int j = 0 ; j<dim; j++){
                    feromonas[i][j] = 1.0/(100*mejorCosto);
                }
            }
        }
        sinMejoria++;
    }

    pair <int,vector<int>> pairSol = make_pair (mejorCosto,mejorSol);
    return pairSol;

}

int main (int argc, char* argv[]) {

    vector<int> resultados(10);
    for (int i = 0; i < 10; i++){

        clock_t startTime = clock();
        ifstream file(argv[1]);
        int dim;  //dimensiones de las matrices
        file >> dim;
        vector<int> suc(dim*dim); //matriz con los flujos entre las sucursales
        vector<int> loc(dim*dim); //matriz con las distancias de las localidades
        pair <int,vector<int>> pairSol; //tiene el costo de la busqueda y la permutación

        //guardar la matriz de distancia
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> suc[dim*i+j];
            }
        }

        //guardar la matriz de flujos
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> loc[dim*i+j];
            }
        }

        pairSol = antColony(10,dim,loc,suc);
        resultados[i] = pairSol.first;
        cout << pairSol.first << endl;

        for (int i = 0; i < dim; i++){
            cout << pairSol.second[i] << " ";
        }
        cout << endl;

        cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
    }

    int total = 0;
    for (int j = 0; j<10; j++){
        total += resultados[j];
    }

    cout << endl << "El promedio de de las soluciones es: " <<endl;
    cout << total/10 << endl;

    return 0;
}
</code>```

Valgrind gives me this:

Invalid read of size 4 at 0x804B331: main (antColony.cpp:269)
Address 0x0 is not stack'd, malloc'd or (recently) free'd

Process terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x0
at 0x804B331: main (antColony.cpp:269)

I am using this file:

```<code>20

 0 87 14  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
87  0  0 82 57  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
14  0  0  0  0 68  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0 82  0  0  0  0 19 18 38 47  0  0  0  0  0  0  0  0  0  0
 0 57  0  0  0  0  0  0  0  0 91  0  0  0  0  0  0  0  0  0
 0  0 68  0  0  0  0  0  0  0  0 77  0  0  0  0  0  0  0  0
 0  0  0 19  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0 18  0  0  0  0  0  0  0  0  6  0  0  0  0  0  0  0
 0  0  0 38  0  0  0  0  0  0  0  0  0 75  0  0  0  0  0  0
 0  0  0 47  0  0  0  0  0  0  0  0  0  0 73 52  0  0  0  0
 0  0  0  0 91  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0 77  0  0  0  0  0  0  0  0  0  0 51  0  0  0
 0  0  0  0  0  0  0  6  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0 75  0  0  0  0  0  0  0  0 93  0  0
 0  0  0  0  0  0  0  0  0 73  0  0  0  0  0  0  0  0 84  0
 0  0  0  0  0  0  0  0  0 52  0  0  0  0  0  0  0  0  0 40
 0  0  0  0  0  0  0  0  0  0  0 51  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0 93  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0 84  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 40  0  0  0  0

0 4 7 7 4 6 3 7 1 7 8 7 2 9 8 2 9 3 4 3
4 0 8 1 7 9 8 7 6 5 1 3 1 4 4 2 7 6 3 5
7 8 0 5 7 9 1 6 3 2 9 8 4 8 7 7 4 3 7 1
7 1 5 0 3 1 9 9 7 1 6 6 1 1 2 2 4 2 7 8
4 7 7 3 0 9 9 6 9 4 1 8 2 9 8 6 1 9 2 6
6 9 9 1 9 0 7 6 9 2 3 1 4 1 9 5 3 3 7 3
3 8 1 9 9 7 0 3 7 3 5 1 9 4 6 4 7 4 9 6
7 7 6 9 6 6 3 0 7 1 6 7 3 9 4 1 8 4 9 1
1 6 3 7 9 9 7 7 0 6 1 5 7 6 5 3 4 9 8 1
7 5 2 1 4 2 3 1 6 0 6 3 9 3 3 6 4 1 8 6
8 1 9 6 1 3 5 6 1 6 0 6 3 8 2 4 8 1 9 6
7 3 8 6 8 1 1 7 5 3 6 0 8 2 7 6 4 5 4 1
2 1 4 1 2 4 9 3 7 9 3 8 0 4 4 2 5 6 4 9
9 4 8 1 9 1 4 9 6 3 8 2 4 0 3 2 8 7 2 8
8 4 7 2 8 9 6 4 5 3 2 7 4 3 0 4 3 3 8 4
2 2 7 2 6 5 4 1 3 6 4 6 2 2 4 0 8 5 9 9
9 7 4 4 1 3 7 8 4 4 8 4 5 8 3 8 0 1 2 7
3 6 3 2 9 3 4 4 9 1 1 5 6 7 3 5 1 0 1 1
4 3 7 7 2 7 9 9 8 8 9 4 4 2 8 9 2 1 0 4
3 5 1 8 6 3 6 1 1 6 6 1 9 8 4 9 7 1 4 0
</code>```

The error comes from this lines near the end:

```<code>    for (int i = 0; i < dim; i++){
        cout << pairSol.second[i] << " ";
    }
</code>```

Where I am trying to print the solution vector.

I don't understand the problem with the memory this is generating. This is more confusing because sometimes it works perfectly. If someone could explain it to me I would be grateful.

Thanks in anticipation for your help!

答:
It looks like problem in this part of the code:

```<code>mejorCostoNuevo = funCosto(dim,hormigas[0],dist,flujo);
for (int b = 1; b < numAnts; b++){
    if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
        mejorCostoNuevo = funCosto(dim,hormigas[b],dist,flujo);
        mejorSolNueva = hormigas[b];
    }
}

if (mejorCostoNuevo < mejorCosto){
    //si se consigue una mejor solucíón
    mejorCosto = mejorCostoNuevo;
    mejorSol = mejorSolNueva;
    inten = 1;
    sinMejoria = 0;
}
</code>```

In the loop you have condition

```<code>    if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
</code>```

And next after it you have

```<code>if (mejorCostoNuevo < mejorCosto){
</code>```

mejorSol gets assigned when mejorCostoNuevo is greater than result of funCosto. But then you are checking if mejorCostoNuevo is less than mejorCosto.
Shouldn't these two conditions be in correspondednce?

Changing second condition to

```<code>if (mejorCostoNuevo > mejorCosto){
</code>```

stopped producing errors for me. Anyway if condition in for loop is not true and it mejorCostoNuevo is less than mejorCosto, then you have mejorSol of zero size and thus the error.

Body:
I am learning a bit of programming and I am trying to code an Ant Colony algorithm for QAP, the problem is that sometimes I get segmentation fault and when I use valgrind it tells me "Address 0x0 is not stack'd, malloc'd or (recently) free'd". This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>  //ifstream
#include <string>
#include <sstream>
#include <vector>
#include <utility> //pair
#include <iostream>
#include <algorithm> //shuffle
#include <random> //default_random_engine
#include <chrono> //chrono::system_clock
#include <cstdlib> // rand
#include <unistd.h>
#include <csignal>
using namespace std;

sig_atomic_t volatile done = 0;
void game_over(int) { done = 1; }

int funCosto(int dim,vector<int> sol,vector<int> dist, vector<int> flujo){
    int costo = 0;
    for (int i = 0; i<dim;i++){
        for (int j = i+1; j<dim;j++){
            // El costo es la * del valor de los flujos por la permutacion de las distancias
            costo += flujo[dim*i+j] * dist[dim*(sol[i]-1) + (sol[j]-1)];
        }
    }
    return costo*2; //La matriz es simétrica
}

int buscarLista(vector<int> lista, int elemento, int dim){
    int aux = 0;
    for (int i = 0; i < dim; i++){
        if (lista[i] == elemento){aux = 1;}
    }
    return aux;
}

vector<int> localSearch(int dim,vector<int> sol, vector<int> dist, vector<int> flujo){

    vector<int> solActual(dim), solAux(dim);
    solActual = sol;
    int mejorCosto = funCosto(dim,solActual,dist,flujo);
    int costoActual, mejorCostoAnterior;

    do{
        mejorCostoAnterior = mejorCosto; // para determinar que se llegó a un óptimo local
        for (int i = 0; i < dim; i++){
            for (int j = i+1; j < dim; j++){
                solAux = solActual;
                solAux[i] = solActual[j];
                solAux[j] = solActual[i]; //intercambiamos dos elementos
                /*Importante, hay que optimizar el cálculo del costo de los vecinos*/
                costoActual = funCosto(dim,solAux,dist,flujo);
                if (costoActual<mejorCosto){
                    break;
                }
            }
            if (costoActual < mejorCosto){
                mejorCosto = costoActual; //se actualiza el mejor costo
                solActual = solAux; //se efectua el movimiento
                break;
            }
        }
    } while (mejorCosto < mejorCostoAnterior); //se detiene cuando ya no hay mejoría

    return solActual;
}

pair<int,vector<int>> antColony(int numAnts, int dim, vector<int> dist, vector<int> flujo){

    done = 0;
    std::signal(SIGALRM, game_over);
    alarm(300);

    vector<vector<int>> hormigas(numAnts, vector<int>(dim));
    vector<vector<int>> hormigasNuevas(numAnts, vector<int>(dim));
    vector<vector<double>> feromonas(dim, vector<double>(dim));
    vector<int> mejorSol, mejorSolNueva;
    double mejorCosto, mejorCostoNuevo, totalFer, prob, auxProb, probAcum = 0 ;
    int numSwaps = dim/3;  // número de cambios que va a hacer cada hormiga en cada iteración
    random_device rd; // obtener un número aleatorio de hardware
    mt19937 eng(rd()); // semilla para el generador
    uniform_int_distribution<> disInt(0,dim-1);
    uniform_real_distribution<> disReal(0,1);
    int prim, seg, aux, contadorRep, sinMejoria = 0; //indices
    int inten = 1; //la intensificación está prendida al comienzo

    for (int i = 1; i <= dim; i++){
        hormigas[0][i-1] = i;
    }
    for (int j = 1; j < numAnts; j++){
        hormigas[j] = hormigas[0];
    }
    //obtener una semilla basada en el tiempo
    for (int k = 0; k < numAnts; k++){
        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
        shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
    }

    for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
        hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
    }

    mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
    mejorSol = hormigas[0];
    for (int i = 1; i < numAnts; i++){
        if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
            mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
            mejorSol = hormigas[i];
        }
    }
    for (int i = 0; i<dim; i++){
        for (int j = 0 ; j<dim; j++){
            feromonas[i][j] = 1.0/(100*mejorCosto);
        }
    }

    for (int z = 0; z < 1; z++){ //máximo número de iteraciones

        for (int i = 0; i < numAnts; i++ ){

            hormigasNuevas[i] = hormigas[i];

            for (int j = 0; j < numSwaps; j++){
                prim = disInt(eng);
                auxProb = disReal(eng);
                seg = -1;
                probAcum = 0;
                do{
                    seg++;
                    if (seg == prim){seg++;}
                    totalFer = 0; //limpiamos para esta iteración
                    for (int k = 0; k < dim; k++){
                        if (k != prim){
                            totalFer += feromonas[prim][hormigasNuevas[i][k]-1] + feromonas[k][hormigasNuevas[i][prim]-1];
                        }
                    }
                    //construimos la probabilidad con la que es aceptado el cambio segun las feromonas
                    prob = (feromonas[prim][hormigasNuevas[i][seg]-1]+feromonas[seg][hormigasNuevas[i][prim]-1]) / totalFer;
                    probAcum += prob;
                }while ((auxProb > probAcum) && (seg < dim));

                if (seg == dim){seg--;}

                aux = hormigasNuevas[i][prim];
                hormigasNuevas[i][prim] = hormigasNuevas[i][seg];
                hormigasNuevas[i][seg] = aux;

            }
            //mejoramos la solución modificada por la hormiga
            hormigasNuevas[i] = localSearch(dim,hormigasNuevas[i],dist,flujo);
        }

        //contadorRep = 0;
        //intensificación
        for (int a = 0; a < numAnts; a++){
            if (inten == 1){
                if (funCosto(dim,hormigasNuevas[a],dist,flujo) < funCosto(dim,hormigas[a],dist,flujo)){
                    hormigas[a] = hormigasNuevas[a];
                }
                else{ contadorRep++;} //para contar cuantas veces se queda con la respuesta anterior
            }
            else{
                hormigas[a] = hormigasNuevas[a];
            }
        }

        //if (contadorRep == numAnts){inten = 0;} //apaga la intensificación

        mejorCostoNuevo = funCosto(dim,hormigas[0],dist,flujo);
        for (int b = 1; b < numAnts; b++){
            if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
                mejorCostoNuevo = funCosto(dim,hormigas[b],dist,flujo);
                mejorSolNueva = hormigas[b];
            }
        }

        if (mejorCostoNuevo < mejorCosto){
            //si se consigue una mejor solucíón
            mejorCosto = mejorCostoNuevo;
            mejorSol = mejorSolNueva;
            inten = 1;
            sinMejoria = 0;
        }

        //actualiación de la matriz de feromonas
        for (int c = 0; c < dim; c++){
            for (int d = 0; d < dim; d++){ //Evaporación
                feromonas[c][d] = 0.9*feromonas[c][d];
            }
        }

        for (int e = 0; e < dim; e++){//reforzamos la mejor solución
            feromonas[e][mejorSol[e]-1] = feromonas[e][mejorSol[e]-1] + 0.1/mejorCosto;
        }

        //diversificación
        if (sinMejoria > dim/2){

            hormigas[0] = mejorSol; //se queda la mejor solución hasta el momento
            //se vuelve a inicializar las hormigas
            for (int k = 1; k < numAnts; k++){
                unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
                shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
            }

            for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
                hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
            }

            mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
            mejorSol = hormigas[0];
            for (int i = 1; i < numAnts; i++){
                if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
                    mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
                    mejorSol = hormigas[i];
                }
            }

            //renovar la matriz de feromonas
            for (int i = 0; i<dim; i++){
                for (int j = 0 ; j<dim; j++){
                    feromonas[i][j] = 1.0/(100*mejorCosto);
                }
            }
        }
        sinMejoria++;
    }

    pair <int,vector<int>> pairSol = make_pair (mejorCosto,mejorSol);
    return pairSol;

}

int main (int argc, char* argv[]) {

    vector<int> resultados(10);
    for (int i = 0; i < 10; i++){

        clock_t startTime = clock();
        ifstream file(argv[1]);
        int dim;  //dimensiones de las matrices
        file >> dim;
        vector<int> suc(dim*dim); //matriz con los flujos entre las sucursales
        vector<int> loc(dim*dim); //matriz con las distancias de las localidades
        pair <int,vector<int>> pairSol; //tiene el costo de la busqueda y la permutación

        //guardar la matriz de distancia
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> suc[dim*i+j];
            }
        }

        //guardar la matriz de flujos
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> loc[dim*i+j];
            }
        }

        pairSol = antColony(10,dim,loc,suc);
        resultados[i] = pairSol.first;
        cout << pairSol.first << endl;

        for (int i = 0; i < dim; i++){
            cout << pairSol.second[i] << " ";
        }
        cout << endl;

        cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
    }

    int total = 0;
    for (int j = 0; j<10; j++){
        total += resultados[j];
    }

    cout << endl << "El promedio de de las soluciones es: " <<endl;
    cout << total/10 << endl;

    return 0;
}

Valgrind gives me this:

Invalid read of size 4 at 0x804B331: main (antColony.cpp:269)
Address 0x0 is not stack'd, malloc'd or (recently) free'd

Process terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x0
at 0x804B331: main (antColony.cpp:269)

I am using this file:

20

 0 87 14  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
87  0  0 82 57  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
14  0  0  0  0 68  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0 82  0  0  0  0 19 18 38 47  0  0  0  0  0  0  0  0  0  0
 0 57  0  0  0  0  0  0  0  0 91  0  0  0  0  0  0  0  0  0
 0  0 68  0  0  0  0  0  0  0  0 77  0  0  0  0  0  0  0  0
 0  0  0 19  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0 18  0  0  0  0  0  0  0  0  6  0  0  0  0  0  0  0
 0  0  0 38  0  0  0  0  0  0  0  0  0 75  0  0  0  0  0  0
 0  0  0 47  0  0  0  0  0  0  0  0  0  0 73 52  0  0  0  0
 0  0  0  0 91  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0 77  0  0  0  0  0  0  0  0  0  0 51  0  0  0
 0  0  0  0  0  0  0  6  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0 75  0  0  0  0  0  0  0  0 93  0  0
 0  0  0  0  0  0  0  0  0 73  0  0  0  0  0  0  0  0 84  0
 0  0  0  0  0  0  0  0  0 52  0  0  0  0  0  0  0  0  0 40
 0  0  0  0  0  0  0  0  0  0  0 51  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0 93  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0 84  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 40  0  0  0  0

0 4 7 7 4 6 3 7 1 7 8 7 2 9 8 2 9 3 4 3
4 0 8 1 7 9 8 7 6 5 1 3 1 4 4 2 7 6 3 5
7 8 0 5 7 9 1 6 3 2 9 8 4 8 7 7 4 3 7 1
7 1 5 0 3 1 9 9 7 1 6 6 1 1 2 2 4 2 7 8
4 7 7 3 0 9 9 6 9 4 1 8 2 9 8 6 1 9 2 6
6 9 9 1 9 0 7 6 9 2 3 1 4 1 9 5 3 3 7 3
3 8 1 9 9 7 0 3 7 3 5 1 9 4 6 4 7 4 9 6
7 7 6 9 6 6 3 0 7 1 6 7 3 9 4 1 8 4 9 1
1 6 3 7 9 9 7 7 0 6 1 5 7 6 5 3 4 9 8 1
7 5 2 1 4 2 3 1 6 0 6 3 9 3 3 6 4 1 8 6
8 1 9 6 1 3 5 6 1 6 0 6 3 8 2 4 8 1 9 6
7 3 8 6 8 1 1 7 5 3 6 0 8 2 7 6 4 5 4 1
2 1 4 1 2 4 9 3 7 9 3 8 0 4 4 2 5 6 4 9
9 4 8 1 9 1 4 9 6 3 8 2 4 0 3 2 8 7 2 8
8 4 7 2 8 9 6 4 5 3 2 7 4 3 0 4 3 3 8 4
2 2 7 2 6 5 4 1 3 6 4 6 2 2 4 0 8 5 9 9
9 7 4 4 1 3 7 8 4 4 8 4 5 8 3 8 0 1 2 7
3 6 3 2 9 3 4 4 9 1 1 5 6 7 3 5 1 0 1 1
4 3 7 7 2 7 9 9 8 8 9 4 4 2 8 9 2 1 0 4
3 5 1 8 6 3 6 1 1 6 6 1 9 8 4 9 7 1 4 0

The error comes from this lines near the end:

    for (int i = 0; i < dim; i++){
        cout << pairSol.second[i] << " ";
    }

Where I am trying to print the solution vector.

I don't understand the problem with the memory this is generating. This is more confusing because sometimes it works perfectly. If someone could explain it to me I would be grateful.

Thanks in anticipation for your help!

Body:
It looks like problem in this part of the code:

mejorCostoNuevo = funCosto(dim,hormigas[0],dist,flujo);
for (int b = 1; b < numAnts; b++){
    if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
        mejorCostoNuevo = funCosto(dim,hormigas[b],dist,flujo);
        mejorSolNueva = hormigas[b];
    }
}

if (mejorCostoNuevo < mejorCosto){
    //si se consigue una mejor solucíón
    mejorCosto = mejorCostoNuevo;
    mejorSol = mejorSolNueva;
    inten = 1;
    sinMejoria = 0;
}

In the loop you have condition

    if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){

And next after it you have

if (mejorCostoNuevo < mejorCosto){

mejorSol gets assigned when mejorCostoNuevo is greater than result of funCosto. But then you are checking if mejorCostoNuevo is less than mejorCosto.
Shouldn't these two conditions be in correspondednce?

Changing second condition to

if (mejorCostoNuevo > mejorCosto){

stopped producing errors for me. Anyway if condition in for loop is not true and it mejorCostoNuevo is less than mejorCosto, then you have mejorSol of zero size and thus the error.


问:
How to create a dynamic id for a dynamic button?
I am able to create an onlick dynamic button with an incrementer and a decrementer option, but I am unable to create a dynamic id for other buttons due to which these buttons are not getting incremented or decremented. Currently only the first button gets decremented/incremented even when clicked on other buttons.

Here is the plunker

When you click on + icon content and a incrementer/decrementer button is added in Manage Portfolio section. I have tried different solutions which have been defined on Stack Overflow but they don't seem to work here.

```<code>             <table>
                <thead>
                    <tr>
                        <th>STOCK</th>
                        <th>PRICE</th>
                        <th>SHARES</th>
                        <th>WEIGHT</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                        <td>{{stock.key}}</td>
                        <td class="portfoliovalue">{{"₹" + stock.value}}</td>
                        <td>
                            <input type="button" onclick="decrementValue()" value="-">
                            <input type="button" id="number" value="0" />
                            <input type="button" onclick="incrementValue()" value="+" />
                        </td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
</code>```

Script

```<code>   function incrementValue() {
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}

function decrementValue() {
    value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value--;
    document.getElementById('number').value = value;
}
</code>```

答:
Here's my working version, using the index in the id.

https://plnkr.co/edit/lSteH17zNL7gMHqQQCSI?p=preview

 var app = angular.module('myApp', []);

    // var app = angular.module('myApp', []);

    app.controller('stockCtrl', function($scope, $http) {
        $http.get('data.json').then(function(response) {
            $scope.stocksArray = [];
            var indexes = [];
            $scope.stocks = response.data.price;
            $scope.addToTable = function(key, value, index) {
                var mystock = {};
                mystock.key = key;
                mystock.value = value;
                mystock.index = index;
                if (indexes.indexOf(index) == -1) {
                    indexes.push(index);
                    $scope.stocksArray.push(mystock);
                }
            };
            $scope.incrementValue = function( index ) {
                var value = parseInt(document.getElementById('number' + index).value, 10);
                value = isNaN(value) ? 0 : value;
                value++;
                document.getElementById('number' + index).value = value;
            };

            $scope.decrementValue = function( index ) {
                value = parseInt(document.getElementById('number' + index).value, 10);
                value = isNaN(value) ? 0 : value;
                value--;
                document.getElementById('number' + index).value = value;
            };

        });

    });

    app.filter('objLimitTo', [function() {
        return function(obj, limit) {
            if (obj) {
                var keys = Object.keys(obj);
                if (keys.length < 1) {
                    return [];
                }
            }

            var result = {},
                count = 0;
            angular.forEach(keys, function(key) {
                if (count >= limit) {
                    return false;
                }
                result[key] = obj[key];
                count++;
            });
            return result;
        };
    }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-App="myApp">

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
    <script src="script.js"></script>

  </head>

  <body>

  <div ng-controller="stockCtrl">
        <section class="pickstocks">
            <label class="basiclabel">Pick Stocks</label>
            <div class="infoone">
                <p>Showing matching stocks</p>
                <button>Apply Filters</button>
            </div>
            <div class="stockpage">
                <ul id="nav">
                    <li ng-repeat="(key,value) in stocks | objLimitTo:8 track by $index">
                        <span class="keyvalue"> {{key}} </span>
                        <span class="keyvalue">{{"₹" + value}}</span>
                        <span class="fa fa-plus plus" ng-click="addToTable(key, value, $index)"></span>
                    </li>
                </ul>
            </div>
        </section>
        <section class="pickstocks">
            <label class="basiclabel">Manage Portfolio</label>
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>STOCK</th>
                            <th>PRICE</th>
                            <th>SHARES</th>
                            <th>WEIGHT</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                            <td>{{stock.key}}</td>
                            <td class="portfoliovalue">{{"₹" + stock.value}}</td>
                            <td>
                                <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                                <input type="button" id="number{{ stock.index }}" value="0" />
                                <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                            </td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>
    </div>
  </body>

</html></code>```

Body:
I am able to create an onlick dynamic button with an incrementer and a decrementer option, but I am unable to create a dynamic id for other buttons due to which these buttons are not getting incremented or decremented. Currently only the first button gets decremented/incremented even when clicked on other buttons.

Here is the plunker

When you click on + icon content and a incrementer/decrementer button is added in Manage Portfolio section. I have tried different solutions which have been defined on Stack Overflow but they don't seem to work here.

                        STOCK
                        PRICE
                        SHARES
                        WEIGHT

                        {{stock.key}}
                        {{"₹" + stock.value}}

                            <input type="button" onclick="decrementValue()" value="-">
                            <input type="button" id="number" value="0" />
                            <input type="button" onclick="incrementValue()" value="+" />

Script

   function incrementValue() {
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}

function decrementValue() {
    value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value--;
    document.getElementById('number').value = value;
}

Body:
Here's my working version, using the index in the id.

https://plnkr.co/edit/lSteH17zNL7gMHqQQCSI?p=preview

 var app = angular.module('myApp', []);

    // var app = angular.module('myApp', []);

    app.controller('stockCtrl', function($scope, $http) {
        $http.get('data.json').then(function(response) {
            $scope.stocksArray = [];
            var indexes = [];
            $scope.stocks = response.data.price;
            $scope.addToTable = function(key, value, index) {
                var mystock = {};
                mystock.key = key;
                mystock.value = value;
                mystock.index = index;
                if (indexes.indexOf(index) == -1) {
                    indexes.push(index);
                    $scope.stocksArray.push(mystock);
                }
            };
            $scope.incrementValue = function( index ) {
                var value = parseInt(document.getElementById('number' + index).value, 10);
                value = isNaN(value) ? 0 : value;
                value++;
                document.getElementById('number' + index).value = value;
            };

            $scope.decrementValue = function( index ) {
                value = parseInt(document.getElementById('number' + index).value, 10);
                value = isNaN(value) ? 0 : value;
                value--;
                document.getElementById('number' + index).value = value;
            };

        });

    });

    app.filter('objLimitTo', [function() {
        return function(obj, limit) {
            if (obj) {
                var keys = Object.keys(obj);
                if (keys.length < 1) {
                    return [];
                }
            }

            var result = {},
                count = 0;
            angular.forEach(keys, function(key) {
                if (count >= limit) {
                    return false;
                }
                result[key] = obj[key];
                count++;
            });
            return result;
        };
    }]);

<!DOCTYPE html>
<html ng-App="myApp">

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
    <script src="script.js"></script>

  </head>

  <body>

  <div ng-controller="stockCtrl">
        <section class="pickstocks">
            <label class="basiclabel">Pick Stocks</label>
            <div class="infoone">
                <p>Showing matching stocks</p>
                <button>Apply Filters</button>
            </div>
            <div class="stockpage">
                <ul id="nav">
                    <li ng-repeat="(key,value) in stocks | objLimitTo:8 track by $index">
                        <span class="keyvalue"> {{key}} </span>
                        <span class="keyvalue">{{"&#x20b9;" + value}}</span>
                        <span class="fa fa-plus plus" ng-click="addToTable(key, value, $index)"></span>
                    </li>
                </ul>
            </div>
        </section>
        <section class="pickstocks">
            <label class="basiclabel">Manage Portfolio</label>
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>STOCK</th>
                            <th>PRICE</th>
                            <th>SHARES</th>
                            <th>WEIGHT</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                            <td>{{stock.key}}</td>
                            <td class="portfoliovalue">{{"&#x20b9;" + stock.value}}</td>
                            <td>
                                <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                                <input type="button" id="number{{ stock.index }}" value="0" />
                                <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                            </td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>
    </div>
  </body>

</html>