问:
What is a datasource in java? Can someone please explain me in simple language?
What is a DataSource in java?
Can someone please explain me in simple language?</p>

答:
DataSource implementation classes allow you to use connection pool and loose coupling for connectivity.

Most of the times we are looking for loose coupling for connectivity so that we can switch databases easily.

Creating connections can be heavy process and it is not a good idea to let every part of program create its own connections which can lead to resource starvation and slow performance. that's why we use connection pooling. most database drivers provide datasource implementation classes that can be used in connection pool.


来源: stackexchange

问:
Bootstrap 3 long modal open fix postion
I am working on mvc 5 application in that  I am using bootstrap modal(pop-up) when click on popup its open at proper position  showing image below first time opening of modal

but when I click cancel button on  popup it close and  while re opening it change its position It causes scroll top of main screen how to avoid this showing in second image. .Second time opening at wrong position

Can anybody please provide me some inputs on this? it will be greatly appreciable.
thanks in advance

答:
```<code>$('#YourModal').on('shown.bs.modal', function () {
    $(this).scrollTop(0);
});
</code>```

Make scrollTop(0) it will work fine

ContentLicense: CC BY-SA 3.0

Title: Bootstrap 3 long modal open fix postion

Body:
$('#YourModal').on('shown.bs.modal', function () {
    $(this).scrollTop(0);
});

Make scrollTop(0) it will work fine


问:
Compiling error on have 2 next variables
Im trying to run code that will copy the text "ready" or "cancel" in column L, based on if there is a value in Column S or T respectively in the specif row.

I keep getting the error Compile error: Invalid Next control variable reference.

My code is as follows,

```<code>    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:10")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Dim lRow    As Long
Dim ws      As Worksheet

Set ws = ThisWorkbook.Sheets("Orders")

Application.ScreenUpdating = False

    For SRow = 1 To 5000
    For TRow = 1 To 5000
    If ws.Cells(SRow, 19) = SRow Then
        ws.Cells(SRow, 12).Select
        ActiveCell.FormulaR1C1 = "ready"

     ElseIf ws.Cells(TRow, 20) = TRow Then
            ws.Cells(TRow, 12).Select
            ActiveCell.FormulaR1C1 = "Cancel"

        Call ScheduleCopyPriceOver

    End If
    Next SRow
    Next TRow

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub
</code>```

答:
Not entirely sure what your data looks like to be able to check the validity of your IF and ELSEIF statements, nor can we tell if running a 5,000 piece loop 5,000 times is warranted.... but tidying up your loop to the following will prevent the compilation error:

```<code>For SRow = 1 To 5000
    For TRow = 1 To 5000
        If ws.Cells(SRow, 19) = SRow Then
            ws.Cells(SRow, 12).FormulaR1C1 = "ready"
        ElseIf ws.Cells(TRow, 20) = TRow Then
            ws.Cells(TRow, 12).FormulaR1C1 = "Cancel"
            Call ScheduleCopyPriceOver
        End If
    Next TRow
Next SRow
</code>```

(Note: I've removed the unnecessary cell selection also)

Body:
Im trying to run code that will copy the text "ready" or "cancel" in column L, based on if there is a value in Column S or T respectively in the specif row.

I keep getting the error Compile error: Invalid Next control variable reference.

My code is as follows,

    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:10")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Dim lRow    As Long
Dim ws      As Worksheet

Set ws = ThisWorkbook.Sheets("Orders")

Application.ScreenUpdating = False

    For SRow = 1 To 5000
    For TRow = 1 To 5000
    If ws.Cells(SRow, 19) = SRow Then
        ws.Cells(SRow, 12).Select
        ActiveCell.FormulaR1C1 = "ready"

     ElseIf ws.Cells(TRow, 20) = TRow Then
            ws.Cells(TRow, 12).Select
            ActiveCell.FormulaR1C1 = "Cancel"

        Call ScheduleCopyPriceOver

    End If
    Next SRow
    Next TRow

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub

Body:
Not entirely sure what your data looks like to be able to check the validity of your IF and ELSEIF statements, nor can we tell if running a 5,000 piece loop 5,000 times is warranted.... but tidying up your loop to the following will prevent the compilation error:

For SRow = 1 To 5000
    For TRow = 1 To 5000
        If ws.Cells(SRow, 19) = SRow Then
            ws.Cells(SRow, 12).FormulaR1C1 = "ready"
        ElseIf ws.Cells(TRow, 20) = TRow Then
            ws.Cells(TRow, 12).FormulaR1C1 = "Cancel"
            Call ScheduleCopyPriceOver
        End If
    Next TRow
Next SRow

(Note: I've removed the unnecessary cell selection also)


问:
excel macros with empty dropdown
I'm working with AutoFilters in VBA with Microsoft Excel. I'm having an issue with how it handles arrays for filtering

i have created macro and auto filter is below.

```<code>ActiveSheet.Range("$A$1:$AC$500").AutoFilter Field:=15, Criteria1:="Not Met"
</code>```

but some times in rows i wont get calls with "Not Met" Condition and the drop down is empty at that time my macro gives error and doesn't progress ,how to over come this, is there any whay i can declare if no match found copy only header.

答:
Once you have filtered your results you can use SpecialCells to test if you have found any results

```<code>Sub Test()
    With ThisWorkbook.Worksheets("Sheet1").Range("A1:AC500")
        .AutoFilter Field:=15, Criteria1:="Not Met"
        If .SpecialCells(xlCellTypeVisible).Count > .Columns.Count Then
            'results found
        Else
            'results not found
        End If
    End With
End Sub
</code>```

Title: excel macros with empty dropdown

Body:
I'm working with AutoFilters in VBA with Microsoft Excel. I'm having an issue with how it handles arrays for filtering

i have created macro and auto filter is below.

ActiveSheet.Range("$A$1:$AC$500").AutoFilter Field:=15, Criteria1:="Not Met"

but some times in rows i wont get calls with "Not Met" Condition and the drop down is empty at that time my macro gives error and doesn't progress ,how to over come this, is there any whay i can declare if no match found copy only header.

Body:
Once you have filtered your results you can use SpecialCells to test if you have found any results

Sub Test()
    With ThisWorkbook.Worksheets("Sheet1").Range("A1:AC500")
        .AutoFilter Field:=15, Criteria1:="Not Met"
        If .SpecialCells(xlCellTypeVisible).Count > .Columns.Count Then
            'results found
        Else
            'results not found
        End If
    End With
End Sub


问:
Manually add reviewers to AOSP change required?
I have pushed two changes to AOSP, same topic and they have been sitting with "Needs Code-Review Label" for 3 days now (weekend included).

I know I can assign reviewers manually, but I wouldn't know who to add. I've read around on how to submit a patch but have not found if reviewers are automatically notified and the change will be processed whenever it should or if there is something else on my side I have to do.

答: You just need to wait or you could, if was the case, add specific reviewers for your change. It's seens that 3 days (weekend included) aren't time enought for the review.</p>


问:
Query showing records that do NOT match in between tables
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

```<code>Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly
</code>```

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

```<code>SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID
</code>```

And my results:

```<code>AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32
</code>```

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

```<code>AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly
</code>```

答:
```<code>select *
from Reports r
left join #QuarterlyReportsDue d
    on d.AssessmentID=r.AssessmentID
    and d.QuarterlyReportType=ReportType
where d.AssessmentID is null
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID

And my results:

AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly


问:
Delete temp files on startup
My program requires a temp folder to put data in while running. This data is not needed after exit of the program and should be deleted. Each running instance of the program needs one folder on its own.

If I use file.deleteOnExit(), this does not make sure the file gets deleted on crash of whatever kind. My idea thus is to check for old temp files on startup that didn't got deleted and remove them. But when starting another instance of the program it shouldn't delete the temp files of still running programs. How can I achieve this?

To be more specific: The temp files should be in the System's temp directory and should be deleted if the program exits normally. This question is only for the few times the program crashed. The program has to be OS-independent. A solution using the Path instead of the File classes is preferred.

答:
Well, I suggest to create at start for each application a private directory where store temporary files say /var/run/myapp/tmp.

And at start delete the directory content:

```<code>void purgeDirectory(File dir) {
    for (File file: dir.listFiles()) {
        if (file.isDirectory()) purgeDirectory(file);
        file.delete();
    }
}
</code>```

You remain free to delete the directory content at app exit, but in this way, even if at the exit cleanup were not done correctly you're sure to have an empty dir at startup.

Title: Delete temp files on startup

Body:
Well, I suggest to create at start for each application a private directory where store temporary files say /var/run/myapp/tmp.

And at start delete the directory content:

void purgeDirectory(File dir) {
    for (File file: dir.listFiles()) {
        if (file.isDirectory()) purgeDirectory(file);
        file.delete();
    }
}

You remain free to delete the directory content at app exit, but in this way, even if at the exit cleanup were not done correctly you're sure to have an empty dir at startup.


问:
How can I write the query as raw in Laravel?
Here is my query:

```<code>SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");
</code>```

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

```<code>DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();
</code>```

答:
You can try this</p>

```<code>DB::table('relations')
    ->select(DB::raw('count(*) as user_count, status'))
    ->whereRaw('rootid IN (736, 781)')
    ->groupBy('rid')
    ->having(DB::Raw('COUNT(rid) = 2'))
    ->get();
</code>```

Body:
Here is my query:

SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();

Body:
You can try this

DB::table('relations')
    ->select(DB::raw('count(*) as user_count, status'))
    ->whereRaw('rootid IN (736, 781)')
    ->groupBy('rid')
    ->having(DB::Raw('COUNT(rid) = 2'))
    ->get();


问:
String replace with dictionary exception handling
I've implemented the answer here to do token replacements of a string:
https://stackoverflow.com/a/1231815/1224021

My issue now is when this method finds a token with a value that is not in the dictionary. I get the exception "The given key was not present in the dictionary." and just return the normal string. What I'd like to happen obviously is all the good tokens get replaced, but the offending one remains au naturale. Guessing I'll need to do a loop vs. the one line regex replace? Using vb.net. Here's what I'm currently doing:

```<code>Shared ReadOnly re As New Regex("\$(\w+)\$", RegexOptions.Compiled)
Public Shared Function GetTokenContent(ByVal val As String) As String
    Dim retval As String = val

    Try
        If Not String.IsNullOrEmpty(val) AndAlso val.Contains("$") Then

            Dim args = GetRatesDictionary()

            retval = re.Replace(val, Function(match) args(match.Groups(1).Value))

        End If

    Catch ex As Exception

        ' not sure how to handle?

    End Try

    Return retval

End Function
</code>```

答:
I know it's been a while since this question was answered, but FYI for anyone wanting to still use the Regex / Dictionary match approach, the following works (based on the sample in the OP question):

```<code>retVal = re.Replace(formatString,
                    match => args.ContainsKey(match.Groups[1].Captures[0].Value)
                        ? args[match.Groups[1].Captures[0].Value]
                        : string.Empty);
</code>```

... or my full sample as a string extension method is:

```<code> public static class StringExtensions
        {
// Will replace parameters enclosed in double curly braces
            private static readonly Lazy<Regex> ParameterReplaceRegex = new Lazy<Regex>(() => new Regex(@"\{\{(?<key>\w+)\}\}", RegexOptions.Compiled));

            public static string InsertParametersIntoFormatString(this string formatString, string parametersJsonArray)
            {
                if (parametersJsonArray != null)
                {
                    var deserialisedParamsDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersJsonArray);

                    formatString = ParameterReplaceRegex.Value.Replace(formatString,
                        match => deserialisedParamsDictionary.ContainsKey(match.Groups[1].Captures[0].Value)
                            ? deserialisedParamsDictionary[match.Groups[1].Captures[0].Value]
                            : string.Empty);
                }

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

There are a few things to note here:
1) My parameters are passed in as a JSON array, e.g.: {"ProjectCode":"12345","AnotherParam":"Hi there!"}
2) The actual template / format string to do the replacements on has the parameters enclosed in double curly braces: "This is the Project Code: {{ProjectCode}}, this is another param {{AnotherParam}}"
3) Regex is both Lazy initialized and Compiled to suit my particular use case of:

the screen this code serves may not be used often

but once it is, it will get heavy use

so it should be as efficient on subsequent calls as possible.

Body:
I've implemented the answer here to do token replacements of a string:
https://stackoverflow.com/a/1231815/1224021

My issue now is when this method finds a token with a value that is not in the dictionary. I get the exception "The given key was not present in the dictionary." and just return the normal string. What I'd like to happen obviously is all the good tokens get replaced, but the offending one remains au naturale. Guessing I'll need to do a loop vs. the one line regex replace? Using vb.net. Here's what I'm currently doing:

Shared ReadOnly re As New Regex("\$(\w+)\$", RegexOptions.Compiled)
Public Shared Function GetTokenContent(ByVal val As String) As String
    Dim retval As String = val

    Try
        If Not String.IsNullOrEmpty(val) AndAlso val.Contains("$") Then

            Dim args = GetRatesDictionary()

            retval = re.Replace(val, Function(match) args(match.Groups(1).Value))

        End If

    Catch ex As Exception

        ' not sure how to handle?

    End Try

    Return retval

End Function

Body:
I know it's been a while since this question was answered, but FYI for anyone wanting to still use the Regex / Dictionary match approach, the following works (based on the sample in the OP question):

retVal = re.Replace(formatString,
                    match => args.ContainsKey(match.Groups[1].Captures[0].Value)
                        ? args[match.Groups[1].Captures[0].Value]
                        : string.Empty);

... or my full sample as a string extension method is:

 public static class StringExtensions
        {
// Will replace parameters enclosed in double curly braces
            private static readonly Lazy<Regex> ParameterReplaceRegex = new Lazy<Regex>(() => new Regex(@"\{\{(?<key>\w+)\}\}", RegexOptions.Compiled));

            public static string InsertParametersIntoFormatString(this string formatString, string parametersJsonArray)
            {
                if (parametersJsonArray != null)
                {
                    var deserialisedParamsDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersJsonArray);

                    formatString = ParameterReplaceRegex.Value.Replace(formatString,
                        match => deserialisedParamsDictionary.ContainsKey(match.Groups[1].Captures[0].Value)
                            ? deserialisedParamsDictionary[match.Groups[1].Captures[0].Value]
                            : string.Empty);
                }

                return formatString;
            }
        }

There are a few things to note here:
1) My parameters are passed in as a JSON array, e.g.: {"ProjectCode":"12345","AnotherParam":"Hi there!"}
2) The actual template / format string to do the replacements on has the parameters enclosed in double curly braces: "This is the Project Code: {{ProjectCode}}, this is another param {{AnotherParam}}"
3) Regex is both Lazy initialized and Compiled to suit my particular use case of:

the screen this code serves may not be used often

but once it is, it will get heavy use

so it should be as efficient on subsequent calls as possible.


问:
selecting all wpf datagrid checkboxes only selects items in view
I have the following method to select all the checkboxes within my datagrid:

```<code>   private void CheckboxSelectAll(int column)
    {

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

            var row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(i);

            if (row == null) continue;
            var chk = (System.Windows.Controls.CheckBox)dGrid.Columns[column].GetCellContent(row);
            chk.IsChecked = true;
        }
    }
</code>```

This only works so long as all the columns are in view. If, for example, the amount of checkboxes exceeds the height of the datagrid, it will not select those. I will have to scroll down, expose them to the view, and then reinvoke my method to finally select the remaining checkboxes.

What am I missing? These checkboxes are already databound.

If I change the height of the datagrid to expose more checkboxes, this allows me to select more. This is only a workaround and I would like to understand why and what about my code makes the checkboxes being exposed to the view important.

答:
What am I missing? These checkboxes are already databound.

If the CheckBoxes are databound you should set the value of the source property that the IsChecked property of the CheckBox is bound to.

For example, if your CheckBox is defined something like this:

```<code><CheckBox IsChecked="{Binding Checked}" />
</code>```

...you should set the Checked property:

```<code>foreach(var item in dGrid.Items.OfType<YourClass>())
{
    item.Checked = true;
}
</code>```

Make sure that the class where the Checked property is defined implements the INotifyPropertyChanged interface correctly: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx.

This is a way better solution that disabling the built-in virtualization as the latter may affect the performance negatively.

Body:
I have the following method to select all the checkboxes within my datagrid:

   private void CheckboxSelectAll(int column)
    {

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

            var row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(i);

            if (row == null) continue;
            var chk = (System.Windows.Controls.CheckBox)dGrid.Columns[column].GetCellContent(row);
            chk.IsChecked = true;
        }
    }

This only works so long as all the columns are in view. If, for example, the amount of checkboxes exceeds the height of the datagrid, it will not select those. I will have to scroll down, expose them to the view, and then reinvoke my method to finally select the remaining checkboxes.

What am I missing? These checkboxes are already databound.

If I change the height of the datagrid to expose more checkboxes, this allows me to select more. This is only a workaround and I would like to understand why and what about my code makes the checkboxes being exposed to the view important.

Body:
What am I missing? These checkboxes are already databound.

If the CheckBoxes are databound you should set the value of the source property that the IsChecked property of the CheckBox is bound to.

For example, if your CheckBox is defined something like this:

<CheckBox IsChecked="{Binding Checked}" />

...you should set the Checked property:

foreach(var item in dGrid.Items.OfType<YourClass>())
{
    item.Checked = true;
}

Make sure that the class where the Checked property is defined implements the INotifyPropertyChanged interface correctly: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx.

This is a way better solution that disabling the built-in virtualization as the latter may affect the performance negatively.


答:
you could adopt the following pattern:</p>

```<code>With Worksheets("MySheetName") '<--| change "MySheetName" to your actual sheet name and avoid referring to ActiveSheet which can be deceiving
    With .Range("AC", .Cells(.Rows.Count, 1).End(xlUp)) '<--| reference its columns A:AC cells from row 1 down to column A last not empty one
        .AutoFilter Field:=15, Criteria1:="Not Met"
        If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then '<--| if any filered cells other than headers
            With .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible) '<--| reference filtered cells skipping headers
                ' your code to handle filtered data
            End With
        Else
            ' your code to handle no data match condition
        End If
    End With
    .AutoFilterMode = False '<-- remove autofilter
End With
</code>```

Title: excel macros with empty dropdown

Body:
you could adopt the following pattern:

With Worksheets("MySheetName") '<--| change "MySheetName" to your actual sheet name and avoid referring to ActiveSheet which can be deceiving
    With .Range("AC", .Cells(.Rows.Count, 1).End(xlUp)) '<--| reference its columns A:AC cells from row 1 down to column A last not empty one
        .AutoFilter Field:=15, Criteria1:="Not Met"
        If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then '<--| if any filered cells other than headers
            With .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible) '<--| reference filtered cells skipping headers
                ' your code to handle filtered data
            End With
        Else
            ' your code to handle no data match condition
        End If
    End With
    .AutoFilterMode = False '<-- remove autofilter
End With


问:
Angular2 ngFor get only selected values
I have a for loop that populates pre-defined hobbies as checkboxes.
hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking'];

```<code><label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
    <input type="checkbox" name="hobbies" [value]="hobby"
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby)" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label">{{hobby}}</span>
</label>
</code>```

I have created an array my_hobbies: string[]=[]; in which I want to collect only the selected values i.e. ['Sport',..]

My function that collects those values is so far:

```<code>populateMyHobbies(value){

    this.my_hobbies.push(value)
    console.log(this.my_hobbies)
}
</code>```

How can I achieve this? Right now on check and uncheck the values get added even same value multiple times.

答:
You'll want to pass the check event as an argument to populateMyHobbies, and then read event.target.checked to check whether the checkbox is checked or unchecked (Like the answer here).

You can check whether the array contains a value by checking if array.indexOf(value) returns -1, and remove them with array.splice(index,1) (As in this answer).

Title: Angular2 ngFor get only selected values

Body:
I have a for loop that populates pre-defined hobbies as checkboxes.
hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking'];

    <input type="checkbox" name="hobbies" [value]="hobby"
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby)" class="mdl-checkbox__input">
    {{hobby}}

I have created an array my_hobbies: string[]=[]; in which I want to collect only the selected values i.e. ['Sport',..]

My function that collects those values is so far:

populateMyHobbies(value){

    this.my_hobbies.push(value)
    console.log(this.my_hobbies)
}

How can I achieve this? Right now on check and uncheck the values get added even same value multiple times.


问:
$unwind nested document and $match
I have a nested document which looks like:

```<code>    var User = new Schema({
    id: String,
    position: [{
        title: String,
           applied:[{
                candidate_id: String,
                name: String
        }],
        }],
</code>```

What I am looking to do is return all of the 'applied' subdocuments which match a certain 'candidate_id'

What I have so far:

```<code>  app.get('/applied', function(req, res){

  var position = "58dc2bd4e7208a3ea143959e";

  User.aggregate(
        {$unwind : "$position"},
        {$unwind : "$position.applied"},
        {$match:{'position.applied.candidate_id': position}}).exec(function (err, result) {
          console.log(result);
        });
        res.render('applied', { title: 'applied',layout:'candidate'});
});
</code>```

I have another function which returns all the positions that match, and that code works:

```<code>app.post('/search', function (req, res) {

  var position = new RegExp(req.body.position, 'i');
  var location = new RegExp(req.body.location, 'i');

  User.aggregate(
        {$unwind : "$position"},
        {$match:{'position.title': position,'position.location':location}}).exec(function (err, result) {
      console.log(result);
      res.send({ results: result });
  });
});
</code>```

So basically I am struggling with getting a sub-sub-document. Any idea where I'm going wrong?

Sample data:

```<code>{
"_id" : ObjectId("58c2871414cd3d209abf5fc9"),
"position" : [
    {
        "_id" : ObjectId("58d6b7e11e793c9a506ffe8f"),
        "title" : "Software Engineer",

        "applied" : [
            {
                "candidate_id" : "58d153e97e3317291gd80087",
                "name" : "Sample user"

            },
            {
                "candidate_id" : "58d153e97e3317291fd99001",
                "name" : "Sample User2"

            }
        ]
    },
    {
        "_id" : ObjectId("58c2871414cd3d209abf5fc0"),
        "title" : "Software Engineer",

    }
],
</code>```

}

What is going on above is there 2 positions, one of which (first entry) has 2 applied candidates, What I need to do is return the nested object if it matches the mongoose query.

答:
Your code seems fine to me I have implemented same and it works for me only possible issue can be that your position="58dc2bd4e7208a3ea143959e" it might be talking it as a string just convert it to objectId by using the following code and check it should work for you.

```<code>var mongoose = require('mongoose');

     var position = mongoose.Types.ObjectId("58dc2bd4e7208a3ea143959e");

          User.aggregate(
                {$unwind : "$position"},
                {$unwind : "$position.applied"},
                {$match:{'position.applied.candidate_id': position}}).exec(function (err, result) {
                  console.log(result);
                });
                res.render('applied', { title: 'applied',layout:'candidate'});
        });
</code>```

Title: $unwind nested document and $match

Body:
I have a nested document which looks like:

    var User = new Schema({
    id: String,
    position: [{
        title: String,
           applied:[{
                candidate_id: String,
                name: String
        }],
        }],

What I am looking to do is return all of the 'applied' subdocuments which match a certain 'candidate_id'

What I have so far:

  app.get('/applied', function(req, res){

  var position = "58dc2bd4e7208a3ea143959e";

  User.aggregate(
        {$unwind : "$position"},
        {$unwind : "$position.applied"},
        {$match:{'position.applied.candidate_id': position}}).exec(function (err, result) {
          console.log(result);
        });
        res.render('applied', { title: 'applied',layout:'candidate'});
});

I have another function which returns all the positions that match, and that code works:

app.post('/search', function (req, res) {

  var position = new RegExp(req.body.position, 'i');
  var location = new RegExp(req.body.location, 'i');

  User.aggregate(
        {$unwind : "$position"},
        {$match:{'position.title': position,'position.location':location}}).exec(function (err, result) {
      console.log(result);
      res.send({ results: result });
  });
});

So basically I am struggling with getting a sub-sub-document. Any idea where I'm going wrong?

Sample data:

{
"_id" : ObjectId("58c2871414cd3d209abf5fc9"),
"position" : [
    {
        "_id" : ObjectId("58d6b7e11e793c9a506ffe8f"),
        "title" : "Software Engineer",

        "applied" : [
            {
                "candidate_id" : "58d153e97e3317291gd80087",
                "name" : "Sample user"

            },
            {
                "candidate_id" : "58d153e97e3317291fd99001",
                "name" : "Sample User2"

            }
        ]
    },
    {
        "_id" : ObjectId("58c2871414cd3d209abf5fc0"),
        "title" : "Software Engineer",

    }
],

}

What is going on above is there 2 positions, one of which (first entry) has 2 applied candidates, What I need to do is return the nested object if it matches the mongoose query.

Body:
Your code seems fine to me I have implemented same and it works for me only possible issue can be that your position="58dc2bd4e7208a3ea143959e" it might be talking it as a string just convert it to objectId by using the following code and check it should work for you.

var mongoose = require('mongoose');

     var position = mongoose.Types.ObjectId("58dc2bd4e7208a3ea143959e");

          User.aggregate(
                {$unwind : "$position"},
                {$unwind : "$position.applied"},
                {$match:{'position.applied.candidate_id': position}}).exec(function (err, result) {
                  console.log(result);
                });
                res.render('applied', { title: 'applied',layout:'candidate'});
        });


问:
ccTalk coin acceptor no reaction when coin inserted
I write Linux application that is supposed to handle coins insertations (let's say that for now I need to recognize in application what coin has been inserted). I use SCA1 Coin Acceptor (ICT). I need to make it work with polish coins (currency - polish zloty).
I was able to get the communication between PC and Coin Acceptor to work, but I have some issues.

Quick description of my setup:

PC connected to Coin Acceptor via RS232 (+USB converter) over the ccTalk protocol.

Switch Block 1: All OFF, but for the 10th switch, which is set to ON (according to documentation)

Switch Block 2: All OFF

I set inhibit status to allow all (from manual docs)

I set master inhibit status to enable device (from manual docs)

I'm able to pull data from Coin Acceptor regarding serial number, software revision etc. Simple poll works as well. The only issues is with actuall information about inserted coins. I send "Read buffered credit or error codes" (Header 229) command - according to the docs - every 500ms or so, and every time I get result 0 (bytes are equal to 0x00), the result is returned correctly, it just seems like I haven't inserted any coin, when I have. I tried to use polish coins as well as 10 cent coin. All coins are "rejected", and by rejected I mean Coin Acceptor doesn't seem to process those coins (just returns them), on the other hand, when I send command to get the number of rejected coins I get 0, again.

So now question for you, are you aware of any additional setup that is required to get it work (preferabley with polish coins) ?
Also, by default (let's say the Coin acceptor is not connected to PC, but is powered) how does the Coin Acceptor should react on inserted coins ? Just returns them (like in my case) or "processes" them and then returns them or puts them into the "bank" ?

I guess there is no point of me posting the code. I've created two different applications, and the issue is the same.

One in python, I took adventage of https://github.com/Baldanos/ccTools, second application is written in C, something like: https://github.com/BitCoding/cctalk.

It's doubtful that the device is broken, because I tried to use other device with no difference. Also, the devices are brand new.

Any suggestions will be helpful.
Thank you in advance.

答:
I would have written this as a comment but I do not have enough reputation:

I have also used Baldanos' library as a starting point to get my coin acceptor to work. I would first replace

```<code>ser.read(50)
</code>```

with

```<code>time.sleep(0.01)          #give it time for all bytes to be in ser.in_waiting
ser.read(ser.in_waiting)
</code>```

Since, as said in the comments, you don't know if the message will be 50 bytes long.

That said, I managed to get it to work without changing too many things. For me, the coin acceptor was already set to Euros. What does your coin acceptor return when you request the coin id's (sending "184" and the range of 1,16)?

Body:
I would have written this as a comment but I do not have enough reputation:

I have also used Baldanos' library as a starting point to get my coin acceptor to work. I would first replace

ser.read(50)

with

time.sleep(0.01)          #give it time for all bytes to be in ser.in_waiting
ser.read(ser.in_waiting)

Since, as said in the comments, you don't know if the message will be 50 bytes long.

That said, I managed to get it to work without changing too many things. For me, the coin acceptor was already set to Euros. What does your coin acceptor return when you request the coin id's (sending "184" and the range of 1,16)?


答:
You can uses apply based on the row axis and then sort_values to order the data. Then you use integer-based indexing on the sorted series' index to get what you want:

```<code># smallest value
df.apply(lambda x: x.sort_values().index[0], axis=1)
# biggest value
df.apply(lambda x: x.sort_values(ascending=False).index[0], axis=1)
# 2nd biggest value
df.apply(lambda x: x.sort_values(ascending=False).index[1], axis=1)
</code>```

If applied, the output looks like:

```<code>In [38]: df.apply(lambda x: x.sort_values().index.to_series().iloc[0], axis=1)
Out[38]:
1.0       DB
2.0       DB
3.0     TWTR
4.0       DB
5.0       DB
6.0     TWTR
7.0     TWTR
8.0     ATVI
9.0     ATVI
10.0    GOOG
dtype: object

In [39]: df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[0], axis=1)
Out[39]:
1.0     TWTR
2.0     TWTR
3.0     TSLA
4.0     TSLA
5.0     GOOG
6.0       DB
7.0       DB
8.0     GOOG
9.0     GOOG
10.0      DB
dtype: object

In [40]: df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[1], axis=1)
Out[40]:
1.0     TSLA
2.0     TSLA
3.0       DB
4.0     TWTR
5.0     ATVI
6.0     ATVI
7.0     TSLA
8.0     TSLA
9.0     TWTR
10.0    ATVI
dtype: object
</code>```

Title: Select column of pandas dataframe based on value

Body:
I have a quite simple issue which I can't get solved:

I have a dataframe which looks like the following:

               DB         GOOG        ATVI         TSLA        TWTR
1.0    -0.0129755  -0.00463688 -0.00408223    0.0653678   0.0779629
2.0     -0.052772  -0.00712359  -0.0120323    0.0230537   0.0245435
3.0    0.00875274   0.00762426  0.00176186    0.0834672  -0.0017326
4.0    -0.0125196   0.00657628 -0.00235884    0.0502074   0.0157572
5.0    -0.0470443  -0.00382168  -0.0153009   -0.0325997  -0.0235564
6.0     0.0140261  -0.00630647 -0.00265291    -0.037598  -0.0454938
7.0   0.000624415  -0.00429897 -0.00088587 -9.73558e-05  -0.0216945
8.0    -0.0138933  -0.00455289   -0.027357  -0.00682128  -0.0186916
9.0   -0.00311624 -0.000168211  -0.0100577  -0.00894537 -0.00181214
10.0    0.0864933    0.0151531     0.05061    0.0294589   0.0395802

For every row I want to find the column name corresponding to the largest, second largest and smallest value.

Example:

For the first row (index 1.0) I want to extract TWTR (largest value), TSLA (second largest value) and DB (smallest value).

...

For the fifth row (index 5.0) I want to extract GOOG (largest value), ATVI (second largest value) and DB (smallest value)

.. and so on.

What is the simplest way to do this? Thanks!

Body:
You can uses apply based on the row axis and then sort_values to order the data. Then you use integer-based indexing on the sorted series' index to get what you want:

# smallest value
df.apply(lambda x: x.sort_values().index[0], axis=1)
# biggest value
df.apply(lambda x: x.sort_values(ascending=False).index[0], axis=1)
# 2nd biggest value
df.apply(lambda x: x.sort_values(ascending=False).index[1], axis=1)

If applied, the output looks like:

In [38]: df.apply(lambda x: x.sort_values().index.to_series().iloc[0], axis=1)
Out[38]:
1.0       DB
2.0       DB
3.0     TWTR
4.0       DB
5.0       DB
6.0     TWTR
7.0     TWTR
8.0     ATVI
9.0     ATVI
10.0    GOOG
dtype: object

In [39]: df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[0], axis=1)
Out[39]:
1.0     TWTR
2.0     TWTR
3.0     TSLA
4.0     TSLA
5.0     GOOG
6.0       DB
7.0       DB
8.0     GOOG
9.0     GOOG
10.0      DB
dtype: object

In [40]: df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[1], axis=1)
Out[40]:
1.0     TSLA
2.0     TSLA
3.0       DB
4.0     TWTR
5.0     ATVI
6.0     ATVI
7.0     TSLA
8.0     TSLA
9.0     TWTR
10.0    ATVI
dtype: object


问:
Uncaught Error: n.onSuccess is not a function AWS Cognito
I'm getting the following javascript error when I try to set up an authenticated user with a new password and I can't figure out where it's happening. Once I call my register function, the user is actually able to overwrite their temp password with a new one and everything looks fine in the cognito console. They're also able to login with their new password.

```<code>Uncaught Error: n.onSuccess is not a function      request.js?1405:31
  at Response.eval (eval at <anonymous> (app.js:1290), <anonymous>:17:14072)
  at Request.eval (eval at <anonymous> (app.js:1746), <anonymous>:355:18)
  at Request.callListeners (eval at <anonymous> (app.js:1056), <anonymous>:105:20)
  at Request.emit (eval at <anonymous> (app.js:1056), <anonymous>:77:10)
  at Request.emit (eval at <anonymous> (app.js:1746), <anonymous>:668:14)
  at Request.transition (eval at <anonymous> (app.js:1746), <anonymous>:22:10)
  at AcceptorStateMachine.runTo (eval at <anonymous> (app.js:1884), <anonymous>:14:12)
  at eval (eval at <anonymous> (app.js:1884), <anonymous>:26:10)
  at Request.eval (eval at <anonymous> (app.js:1746), <anonymous>:38:9)
  at Request.eval (eval at <anonymous> (app.js:1746), <anonymous>:670:12)
</code>```

My register function:

```<code>import {Config, CognitoIdentityCredentials} from 'aws-sdk'
import {CognitoUserPool, CognitoUser, AuthenticationDetails, CognitoUserAttribute} from 'amazon-cognito-identity-js'

import jwtDecode from 'jwt-decode'
import store from './store'

export default class CognitoAuth {

  register (username, email, pass, newPassword, cb) {
    let authenticationDetails = new AuthenticationDetails({
      Username: username,
      Password: pass
    })
    let cognitoUser = new CognitoUser({
      Username: username,
      Pool: this.userPool
    })

    cognitoUser.authenticateUser(authenticationDetails, {
      newPasswordRequired: (userAttributes, requiredAttributes) => {

        // the api doesn't accept this field back
        delete userAttributes.email_verified

        cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this)
      }
    })
  }
}
</code>```

Register.vue

```<code>signup () {
  this.$cognitoAuth.register(this.username, this.email, this.oldPass, this.newPass, (err, result) => {
    if (err) {
      this.error = true
      this.errMsg = err.message
      console.error(err)
    } else {
      console.log('Login Successful:', result)
      this.$router.replace(this.$route.query.redirect || '/search')
    }
  })
}
</code>```

答:
You're missing the onSuccess callback implementation, which is called on success with the a new session. See line 341 in CognitoUser.js.

For example:

```<code>.
.
.
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: (result) => {
        // User authentication was successful.
    },

    onFailure: (err) => {
        // User authentication was not successful.
    },

    mfaRequired: (codeDeliveryDetails) => {
        // MFA is required to complete user authentication.
        // Get the code from user and call:
        cognitoUser.sendMFACode(mfaCode, this)
    },

    newPasswordRequired: (userAttributes, requiredAttributes) => {

        // the api doesn't accept this field back
        delete userAttributes.email_verified;

        cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this);
    }
})
.
.
.
</code>```

Body:
I'm getting the following javascript error when I try to set up an authenticated user with a new password and I can't figure out where it's happening. Once I call my register function, the user is actually able to overwrite their temp password with a new one and everything looks fine in the cognito console. They're also able to login with their new password.

Uncaught Error: n.onSuccess is not a function      request.js?1405:31
  at Response.eval (eval at <anonymous> (app.js:1290), <anonymous>:17:14072)
  at Request.eval (eval at <anonymous> (app.js:1746), <anonymous>:355:18)
  at Request.callListeners (eval at <anonymous> (app.js:1056), <anonymous>:105:20)
  at Request.emit (eval at <anonymous> (app.js:1056), <anonymous>:77:10)
  at Request.emit (eval at <anonymous> (app.js:1746), <anonymous>:668:14)
  at Request.transition (eval at <anonymous> (app.js:1746), <anonymous>:22:10)
  at AcceptorStateMachine.runTo (eval at <anonymous> (app.js:1884), <anonymous>:14:12)
  at eval (eval at <anonymous> (app.js:1884), <anonymous>:26:10)
  at Request.eval (eval at <anonymous> (app.js:1746), <anonymous>:38:9)
  at Request.eval (eval at <anonymous> (app.js:1746), <anonymous>:670:12)

My register function:

import {Config, CognitoIdentityCredentials} from 'aws-sdk'
import {CognitoUserPool, CognitoUser, AuthenticationDetails, CognitoUserAttribute} from 'amazon-cognito-identity-js'

import jwtDecode from 'jwt-decode'
import store from './store'

export default class CognitoAuth {

  register (username, email, pass, newPassword, cb) {
    let authenticationDetails = new AuthenticationDetails({
      Username: username,
      Password: pass
    })
    let cognitoUser = new CognitoUser({
      Username: username,
      Pool: this.userPool
    })

    cognitoUser.authenticateUser(authenticationDetails, {
      newPasswordRequired: (userAttributes, requiredAttributes) => {

        // the api doesn't accept this field back
        delete userAttributes.email_verified

        cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this)
      }
    })
  }
}

Register.vue

signup () {
  this.$cognitoAuth.register(this.username, this.email, this.oldPass, this.newPass, (err, result) => {
    if (err) {
      this.error = true
      this.errMsg = err.message
      console.error(err)
    } else {
      console.log('Login Successful:', result)
      this.$router.replace(this.$route.query.redirect || '/search')
    }
  })
}

Body:
You're missing the onSuccess callback implementation, which is called on success with the a new session. See line 341 in CognitoUser.js.

For example:

.
.
.
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: (result) => {
        // User authentication was successful.
    },

    onFailure: (err) => {
        // User authentication was not successful.
    },

    mfaRequired: (codeDeliveryDetails) => {
        // MFA is required to complete user authentication.
        // Get the code from user and call:
        cognitoUser.sendMFACode(mfaCode, this)
    },

    newPasswordRequired: (userAttributes, requiredAttributes) => {

        // the api doesn't accept this field back
        delete userAttributes.email_verified;

        cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this);
    }
})
.
.
.


问:
What's the simplest way of returning the larger of two numbers?
Let's say I have an entity that looks like this:

```<code>public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}
</code>```

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}
</code>```

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}
</code>```

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

```<code>public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}
</code>```

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

答:
Just store the max in a variable rather that performing the calculation twice.</p>

```<code>public DateTime LastActivity
{
    get
    {
        var max = Pictures.Max(x => x.LastUpdated);
        return max > this.LastUpdated
          ? max
          : this.LastUpdated
    };
}
</code>```

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

Body:
Just store the max in a variable rather that performing the calculation twice.

public DateTime LastActivity
{
    get
    {
        var max = Pictures.Max(x => x.LastUpdated);
        return max > this.LastUpdated
          ? max
          : this.LastUpdated
    };
}


问:
How can I call particular array value of array in php?
I'm getting below output as an array.

```<code>$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );
</code>```

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

答:
You might use the array_walk_recursive function.

```<code>array_walk_recursive($array, function ($val, $key) {
    if ($key == 'service_desc') print_r($val);
} );
</code>```

Instead of the print_r statement, you can collect your data into another structure, which you convey using the use statement, or with the $userdata additional parameter (see http://www.php.net/manual/en/function.array-walk-recursive.php ).

```<code>$results = array();
array_walk_recursive($array, function ($val, $key) use (&$results) {
    if ($key == 'service_desc') {
        $results []= $val;
    }
} );
</code>```

Pay extra care to the & in front of the use (&$results) otherwise your array of results will be considered immutable inside the callback (i.e. all changes discarded).

Body:
I'm getting below output as an array.

$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

Body:
You might use the array_walk_recursive function.

array_walk_recursive($array, function ($val, $key) {
    if ($key == 'service_desc') print_r($val);
} );

Instead of the print_r statement, you can collect your data into another structure, which you convey using the use statement, or with the $userdata additional parameter (see http://www.php.net/manual/en/function.array-walk-recursive.php ).

$results = array();
array_walk_recursive($array, function ($val, $key) use (&$results) {
    if ($key == 'service_desc') {
        $results []= $val;
    }
} );

Pay extra care to the & in front of the use (&$results) otherwise your array of results will be considered immutable inside the callback (i.e. all changes discarded).


问:
Find number in given range without if statement in javascript
I have 3 inputs Number min and max

if number is in range between min and max the function should return number

if number is less than min the function should return min

if number is greater than max the function should return max

```<code>3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7
</code>```

I have tried doing it but cannot do it without if statement
Hint : Need to use Math function

```<code>function minCalulator(number,min,max){
    if(Math.min(number,min) == number){
        return min;
    }
    if(Math.min(number,max) === max){
            return max;
    }
    return number;
}
</code>```

How to implement this without if or any conditional statements?

答:
here you are first checking for the max of number and max, then checking for the minimum of the min and the other comparison.

const minCalculator = (number, min, max) => Math.max(min, Math.min(number, max))

const test1 = minCalculator(3,4,5)
const test2 = minCalculator(3,1,7)
const test3 = minCalculator(9,1,7)

console.log(test1, test1 === 4)
console.log(test2, test2 === 3)
console.log(test3, test3 === 7)```

Body:
I have 3 inputs Number min and max

if number is in range between min and max the function should return number

if number is less than min the function should return min

if number is greater than max the function should return max

3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7

I have tried doing it but cannot do it without if statement
Hint : Need to use Math function

function minCalulator(number,min,max){
    if(Math.min(number,min) == number){
        return min;
    }
    if(Math.min(number,max) === max){
            return max;
    }
    return number;
}

How to implement this without if or any conditional statements?


问:
CADisplayLink catches animation with delay
Trying to reproduce behaviour described in this article. Line by line. Everything works well but the last step...

The problem is: I unpause CADisplayLink just before calling UIView.animate and expect the unpaused CADisplayLink to call the attached selector on main thread during animation. It does work, but it starts to call the attached selector with a half a second delay.

Any suggestions?

答: It seems that you've chosen a wrong RunLoopMode. With RunLoopMode.commonModes it works like a charm. Look here for a detailed answer.</p>


问:
RegEx with OR not matching first expression
i'm trying to create a Regular Expression with an Or

i have this

```<code>(?<data1>a[^b]+b)|(?<data2>^[^b]+b)
</code>```

the goal is to capture everything behind a or, when a is not present, everything from the start.

```<code>data = "123412123b" result should be "123412123b"
data = "123412a123b" result should be "a123b"
</code>```

it always matches the second part of the or as it captures to group (data2)
can anyone tell me why this happens

答:
you can try below - Easy to understand.</p>

```<code>var reg = @"(.*)([a].*)";
string data = "123412x123b";
var gps = Regex.Match(data, reg).Groups;

string result = gps.Count > 1 ? gps[2].Value : data;
</code>```

Body:
i'm trying to create a Regular Expression with an Or

i have this

(?<data1>a[^b]+b)|(?<data2>^[^b]+b)

the goal is to capture everything behind a or, when a is not present, everything from the start.

data = "123412123b" result should be "123412123b"
data = "123412a123b" result should be "a123b"

it always matches the second part of the or as it captures to group (data2)
can anyone tell me why this happens

Body:
you can try below - Easy to understand.

var reg = @"(.*)([a].*)";
string data = "123412x123b";
var gps = Regex.Match(data, reg).Groups;

string result = gps.Count > 1 ? gps[2].Value : data;


答:
Not sure if it is the simplest solution, but it works:</p>

```<code>df =pd.DataFrame(np.random.rand(5,5), columns=['a','b','c','d','e'])
largest = [df.T.sort_values(by=k).T.keys()[-1] for k in df.T.keys()]
largest2 = [df.T.sort_values(by=k).T.keys()[-2] for k in df.T.keys()]
smallest = [df.T.sort_values(by=k).T.keys()[0] for k in df.T.keys()]
</code>```

Body:
Not sure if it is the simplest solution, but it works:

df =pd.DataFrame(np.random.rand(5,5), columns=['a','b','c','d','e'])
largest = [df.T.sort_values(by=k).T.keys()[-1] for k in df.T.keys()]
largest2 = [df.T.sort_values(by=k).T.keys()[-2] for k in df.T.keys()]
smallest = [df.T.sort_values(by=k).T.keys()[0] for k in df.T.keys()]


问:
Apply a style to all textbox in my WPF application
I am having an issue while I want to apply a style (font size) to all my textbox, where ever they are.

I, of course found those links :
Apply an application-level style to all textboxes

How to target all controls (WPF Styles)

But this doesn't work for me.

The first one is still better because you don't need to use a key, and going to all your textbox.

I already have, in my app.xml, style applying to all controls (applying a color), so I tried something like this (even if this won't really be enough for me, since those styles are not everywhere) :

```<code><Style x:Key="Type1Data" TargetType="{x:Type Control}">
    <Setter Property="Background" Value="#FEE9E6"/>
    <Style.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="FontSize" Value="50" />
        </Style>
    </Style.Resources>
</Style>
</code>```

And as I said, I tried    this too, but won't work.

```<code><Style TargetType="{x:Type TextBox}">
                <Setter Property="FontSize" Value="50" />
            </Style>
</code>```

Any idea what is my probleme and how I can achieve what I want to?
All  the hings I can find make me come back to the same code, and didn't found one that works.

edit : here is my current app.xaml

```<code><Application x:Class="myApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:myApp"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
    <Style TargetType="TextBox"><!-- tried adding those 3 lines too-->
        <Setter Property="FontSize" Value="50"/>
    </Style>
        <Style x:Key="Type1Data" TargetType="{x:Type Control}">
            <Setter Property="Background" Value="Blue"/>
        </Style>
        <Style x:Key="Type2Data" TargetType="{x:Type Control}">
            <Setter Property="Background" Value="White"/>
        </Style>
        <Style x:Key="Type3Data" TargetType="{x:Type Control}">
            <Setter Property="Background" Value="Green"/>
        </Style>
    </Application.Resources>
</Application>
</code>```

As I said, the current styles does not cover the whole app (I add the key that is needed, or nothing)

edit : and if I add directly (as a second setter) font size to the Type 1,2 or 3, the font size apply. So it seems, there is no oter styles that are applying besides the 3 in app.xml.

```<code><Setter Property="FontSize" Value="50" />
</code>```

Sample of code who should get a different textbox size(one with already a style, one without), they are in grid:

```<code><com:ViewControl x:Class="myApp.View.ViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             xmlns:input="http://schemas.syncfusion.com/wpf"
             xmlns:local="clr-namespace:myApp.View"
             xmlns:com="clr-namespace:RAPINF.PLL.Common;assembly=myApp.Common"
             xmlns:entities="clr-namespace:myApp.Entities;assembly=myApp.Entities"
             mc:Ignorable="d"
             d:DesignHeight="500" d:DesignWidth="700">

<TextBox Style="{StaticResource Type1Data}" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Margin="2" Text="{Binding Data.Name}" VerticalAlignment="Center" />

        <TextBox Grid.Row="0" Grid.Column="1" Margin="2" Text="{Binding Data.Name}" VerticalAlignment="Center" Grid.ColumnSpan="3" />
</code>```

edit : adding the code of the popup I use sometimes and works

```<code><sf:RibbonWindow x:Class="namespace:myApp.Common.DetailViewWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:sf="http://schemas.syncfusion.com/wpf"
                xmlns:self="clr-namespace:myApp.Common"
                mc:Ignorable="d"
                d:Height="300" d:Width="400"
                WindowStartupLocation="CenterOwner"
                >
</sf:RibbonWindow>
</code>```

How my usercontrol is added to the dock :

```<code>public void AddView(UserControl View, string sTitle, DockState docState)
{
    int Width = 800;
    int Height = 400;

    DockingManager.SetHeader(View, sTitle);
    DocumentContainer.SetMDIBounds(View, new Rect(30, 30, Width, Height));
    DockingManager.SetState(View, docState);
    DockingManager.SetShowCloseMenuItem(View, true);
    DockingManager.SetDesiredWidthInDockedMode(View, Width);

    DockManager.Children.Add(View);
    ActivateView(View);
}
</code>```

If I use the dock I do this before :

```<code>ApplicationContext.Current.AddView(View, DockState.Document);
</code>```

ANd with a popup, almost the same :

```<code>    DetailViewWindow dlg = new DetailViewWindow(View);
    dlg.ShowDialog();
</code>```

As, those two code are used with the same View (yes, exactly the same), then I guess the problem comes from the fact of adding the view in the dock, and not in a popup window.

Does the dock manager forces me to use a key?

Thank you for your help.

答:
I can't reproduce your problem. I can just show you a working example. Maybe it's helping you finding your problem.

App.xaml

```<code><Application x:Class="WpfApplication2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication2"
             StartupUri="MainWindow.xaml">
<Application.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="FontSize"
                    Value="50" />
        </Style>
    </Application.Resources>
</Application>
</code>```

MainWindow.xaml

```<code><Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        mc:Ignorable="d"
        Title="MainWindow"
        Name="MyWindow"
        SizeToContent="WidthAndHeight">
    <TextBox Width="150"/>
</Window>
</code>```

Output

Body:
I am having an issue while I want to apply a style (font size) to all my textbox, where ever they are.

I, of course found those links :
Apply an application-level style to all textboxes

How to target all controls (WPF Styles)

But this doesn't work for me.

The first one is still better because you don't need to use a key, and going to all your textbox.

I already have, in my app.xml, style applying to all controls (applying a color), so I tried something like this (even if this won't really be enough for me, since those styles are not everywhere) :

    </Style.Resources>
</Style>

And as I said, I tried    this too, but won't work.

Any idea what is my probleme and how I can achieve what I want to?
All  the hings I can find make me come back to the same code, and didn't found one that works.

edit : here is my current app.xaml

<Application x:Class="myApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:myApp"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>

As I said, the current styles does not cover the whole app (I add the key that is needed, or nothing)

edit : and if I add directly (as a second setter) font size to the Type 1,2 or 3, the font size apply. So it seems, there is no oter styles that are applying besides the 3 in app.xml.

<Setter Property="FontSize" Value="50" />

Sample of code who should get a different textbox size(one with already a style, one without), they are in grid:

<com:ViewControl x:Class="myApp.View.ViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             xmlns:input="http://schemas.syncfusion.com/wpf"
             xmlns:local="clr-namespace:myApp.View"
             xmlns:com="clr-namespace:RAPINF.PLL.Common;assembly=myApp.Common"
             xmlns:entities="clr-namespace:myApp.Entities;assembly=myApp.Entities"
             mc:Ignorable="d"
             d:DesignHeight="500" d:DesignWidth="700">

<TextBox Style="{StaticResource Type1Data}" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Margin="2" Text="{Binding Data.Name}" VerticalAlignment="Center" />

        <TextBox Grid.Row="0" Grid.Column="1" Margin="2" Text="{Binding Data.Name}" VerticalAlignment="Center" Grid.ColumnSpan="3" />

edit : adding the code of the popup I use sometimes and works

<sf:RibbonWindow x:Class="namespace:myApp.Common.DetailViewWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:sf="http://schemas.syncfusion.com/wpf"
                xmlns:self="clr-namespace:myApp.Common"
                mc:Ignorable="d"
                d:Height="300" d:Width="400"
                WindowStartupLocation="CenterOwner"
                >
</sf:RibbonWindow>

How my usercontrol is added to the dock :

public void AddView(UserControl View, string sTitle, DockState docState)
{
    int Width = 800;
    int Height = 400;

    DockingManager.SetHeader(View, sTitle);
    DocumentContainer.SetMDIBounds(View, new Rect(30, 30, Width, Height));
    DockingManager.SetState(View, docState);
    DockingManager.SetShowCloseMenuItem(View, true);
    DockingManager.SetDesiredWidthInDockedMode(View, Width);

    DockManager.Children.Add(View);
    ActivateView(View);
}

If I use the dock I do this before :

ApplicationContext.Current.AddView(View, DockState.Document);

ANd with a popup, almost the same :

    DetailViewWindow dlg = new DetailViewWindow(View);
    dlg.ShowDialog();

As, those two code are used with the same View (yes, exactly the same), then I guess the problem comes from the fact of adding the view in the dock, and not in a popup window.

Does the dock manager forces me to use a key?

Thank you for your help.

Body:
I can't reproduce your problem. I can just show you a working example. Maybe it's helping you finding your problem.

App.xaml

<Application x:Class="WpfApplication2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication2"
             StartupUri="MainWindow.xaml">
<Application.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="FontSize"
                    Value="50" />
        </Style>
    </Application.Resources>
</Application>

MainWindow.xaml

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        mc:Ignorable="d"
        Title="MainWindow"
        Name="MyWindow"
        SizeToContent="WidthAndHeight">
    <TextBox Width="150"/>
</Window>

Output


问:
Google Analytics behaving differently in development and production/staging
I have one of my projects setup with analytics.js and Enhanced Ecommerce.

My staging site is subdomain.site.com, and for the site I have the cookie domain (analytics_domain) set to 'none' in development, and 'auto' in staging.

  ga('create', analytics_id, analytics_domain);
  ga('require', 'ec');

The Enhanced Ecommerce is enabled and setup to track events and transactions.
I have the goals setup, using GA's template for creating an account/purchase, and tracking a specific event.

Behavior problem:

Development

Create an url for a campaign like this:

localhost:3000/login?utm_source=test_campaign&utm_campaign=tcp&utm_medium=test_url

Create an account and go through purchase.
I have in GA view, 1 create account event, 1 transaction_completed event and on eCommerce 1 purchase.

This is the expected behavior, I can see the events and have the transactions connected to that campaign.

Staging:

https://subdomain.website.com/login?utm_source=test_campaign&utm_campaign=tcp&utm_medium=test_url

Create an account and go through purchase.
I have in GA view, 1 create account event, 0 transaction_completed event and on eCommerce 0 purchases.

I can see the transactions on staging, I can see all the events, it's just they are not tied to the campaign.

I have created a Site Test, view and I use that code for development and staging. Since they share the same setup for the Google Analytics part I assume I'm not understanding something.

Things I did so far:
- Every test was done in Chrome incognito with no plugin enabled
- Tested the same transaction setup on staging multiple times, results are consistent
- Checked the cookie domain, is .domain.com on the cookie
- Checked throughout the transaction if the clientId for the user is the same (with analytics debugger), it is the same

I ran out of ideas and I really need to get this working so I can track paid campaigns.

Thank you very much.

答:
For me the problem was that with our third-party payment providers (like PayPal), the session was reset when the user returned to our success page.

Solution: add ?utm_nooverride=1 to your return url from each provider, and that should fix it.


问:
Fade out last 5 px of text in UILabel
I want to fade out the last 5 px of a UILabel. The label can never be longer than one line.
At the moment I have the following function.

```<code>  func addFadeOut() {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [self.theme.darkJungleGreenColor().cgColor, self.theme.darkJungleGreenColor().withAlphaComponent(0.1).cgColor]

        gradient.startPoint = CGPoint.init(x: 0.95, y: 1)
        gradient.endPoint = CGPoint.init(x: 1, y: 1)
        self.layer.mask = gradient
    }
</code>```

Can anybody help me how to interpret the start and endpoint?

答:
You can calculate the start points and end points from the width and height of the label.</p>

```<code> extension UILabel {

    func fadeOut() {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [self.textColor.cgColor, UIColor.clear.cgColor]

        //Get Height and width
        let width = self.bounds.size.width
        let height = self.bounds.size.height

        //Calculate the start points and end points
        let startPointX: CGFloat = (width-5)/width
        let startPointY: CGFloat = (height/2)/height
        let endPointX: CGFloat = 1
        let endPointY: CGFloat = (height/2)/height

        gradient.startPoint = CGPoint(x: startPointX, y: startPointY)
        gradient.endPoint = CGPoint(x: endPointX, y: endPointY)
        self.layer.mask = gradient
    }
}
</code>```

Title: Fade out last 5 px of text in UILabel

Body:
I want to fade out the last 5 px of a UILabel. The label can never be longer than one line.
At the moment I have the following function.

  func addFadeOut() {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [self.theme.darkJungleGreenColor().cgColor, self.theme.darkJungleGreenColor().withAlphaComponent(0.1).cgColor]

        gradient.startPoint = CGPoint.init(x: 0.95, y: 1)
        gradient.endPoint = CGPoint.init(x: 1, y: 1)
        self.layer.mask = gradient
    }

Can anybody help me how to interpret the start and endpoint?

Body:
You can calculate the start points and end points from the width and height of the label.

 extension UILabel {

    func fadeOut() {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [self.textColor.cgColor, UIColor.clear.cgColor]

        //Get Height and width
        let width = self.bounds.size.width
        let height = self.bounds.size.height

        //Calculate the start points and end points
        let startPointX: CGFloat = (width-5)/width
        let startPointY: CGFloat = (height/2)/height
        let endPointX: CGFloat = 1
        let endPointY: CGFloat = (height/2)/height

        gradient.startPoint = CGPoint(x: startPointX, y: startPointY)
        gradient.endPoint = CGPoint(x: endPointX, y: endPointY)
        self.layer.mask = gradient
    }
}

ContentLicense: CC BY-SA 4.0


问:
Pass parameter from one jsp to another
Even there are many answers available to this question, still i am not able to find what i am missing. Below is my code, where i am trying to pass irepno parameter from main jsp to another using query parameter. But i am receiving null. Please someone help to findout what is the mistake.

main.jsp
Print Current Report

printcurreport.jsp
String repno = request.getParameter("irepno");```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>IRno:</label><input type="text" name="irepno" id="irepno" class="inp" value="<%=session.getAttribute("irepno")%>" /><br><br></code>```

答:
Try this,if it could help you.

main.jsp

```<code> <label>IRno:</label><input type="text" name="irepno" id="irepno" class="inp" value="<%=session.getAttribute("irepno")%>" />

 <a href="printcurreport.jsp?irepno=<%=session.getAttribute("irepno")%>">Print Current Report</a>
</code>```

printcurreport.jsp

```<code><%
  String irepno=request.getParameter("irepno");
  request.setAttribute("irepno",irepno);

%>
</code>```

Title: Pass parameter from one jsp to another

Body:
Even there are many answers available to this question, still i am not able to find what i am missing. Below is my code, where i am trying to pass irepno parameter from main jsp to another using query parameter. But i am receiving null. Please someone help to findout what is the mistake.

main.jsp
Print Current Report

printcurreport.jsp
String repno = request.getParameter("irepno");

IRno:<input type="text" name="irepno" id="irepno" class="inp" value="<%=session.getAttribute("irepno")%>" />

Body:
Try this,if it could help you.

main.jsp

 <label>IRno:</label><input type="text" name="irepno" id="irepno" class="inp" value="<%=session.getAttribute("irepno")%>" />

 <a href="printcurreport.jsp?irepno=<%=session.getAttribute("irepno")%>">Print Current Report</a>

printcurreport.jsp

<%
  String irepno=request.getParameter("irepno");
  request.setAttribute("irepno",irepno);

%>


问:
c# asp.net second page not showing
The problem is that I use a list to fill a html page but I want to implement paging. Now the first page renders with no problem but as soon as I press the second page button or any other for that matter, I just get a blank page as if nothing happend.

(I will give pieces of my controller cause the rest is not realy nenecessary)

Controller:

```<code>//input is a textfield from the webview which hold the url I want to use
public ActionResult RequestLinks(FormCollection input, int? page = null) {
List<string> links;

//FindLinks will give back a list of links retrieved from an url
links = FindLinks(input["url"].ToString(), download);
int pageSize = 25;
int pageNumber = page ?? 1;
ViewBag.links =  links.ToPagedList(pageNumber, pageSize);

return View(links.ToPagedList(pageNumber, pageSize));
}
</code>```

Html pager:

```<code>@Html.PagedListPager((IPagedList)ViewBag.links, page => Url.Action("RequestLinks", new { page }))
</code>```

If any more information is required for explanation or help feel free to ask.

EDIT:

Maybe it has something to do with routes etc?

答:
<s>Answer #1:</s>

I think that when you use Url.Action(..) you need to provide the name for each of the route value parameters you pass.

For example:

```<code>@Html.PagedListPager((IPagedList)ViewBag.links, pageNumber => Url.Action("RequestLinks", new { page = pageNumber }))
</code>```

Here I'm using pageNumber to be the name of the variable from the predicate, and explicitly naming page as the name of the route parameter I'm setting, assuming the desired action is:

```<code>public ActionResult RequestLinks( int? page = null ) {
    // ...
}
</code>```

Answer #2:

Your action requires that the URL is always passed through in order to download the links and in your current example it isn't. The FormCollection input won't exist when you follow a link, it's only there after the initial POST.

You should be able to change the action to:

```<code>public ActionResult RequestLinks(string url, int? page = null) {

    // Store it.
    ViewBag.url = url;

    // Everything else
    // ...

}
</code>```

And then in your view:

```<code>@Html.PagedListPager((IPagedList)ViewBag.links, pageNumber => Url.Action("RequestLinks", new { url = ViewBag.url, page = pageNumber }))
</code>```

Which (making some assumptions) should generate links like:

```<code>/{controller}/RequestLinks?url=http://google.com&page=3
</code>```

Title: c# asp.net second page not showing

Body:
The problem is that I use a list to fill a html page but I want to implement paging. Now the first page renders with no problem but as soon as I press the second page button or any other for that matter, I just get a blank page as if nothing happend.

(I will give pieces of my controller cause the rest is not realy nenecessary)

Controller:

//input is a textfield from the webview which hold the url I want to use
public ActionResult RequestLinks(FormCollection input, int? page = null) {
List<string> links;

//FindLinks will give back a list of links retrieved from an url
links = FindLinks(input["url"].ToString(), download);
int pageSize = 25;
int pageNumber = page ?? 1;
ViewBag.links =  links.ToPagedList(pageNumber, pageSize);

return View(links.ToPagedList(pageNumber, pageSize));
}

Html pager:

@Html.PagedListPager((IPagedList)ViewBag.links, page => Url.Action("RequestLinks", new { page }))

If any more information is required for explanation or help feel free to ask.

EDIT:

Maybe it has something to do with routes etc?

Body:
<s>Answer #1:</s>

I think that when you use Url.Action(..) you need to provide the name for each of the route value parameters you pass.

For example:

@Html.PagedListPager((IPagedList)ViewBag.links, pageNumber => Url.Action("RequestLinks", new { page = pageNumber }))

Here I'm using pageNumber to be the name of the variable from the predicate, and explicitly naming page as the name of the route parameter I'm setting, assuming the desired action is:

public ActionResult RequestLinks( int? page = null ) {
    // ...
}

Answer #2:

Your action requires that the URL is always passed through in order to download the links and in your current example it isn't. The FormCollection input won't exist when you follow a link, it's only there after the initial POST.

You should be able to change the action to:

public ActionResult RequestLinks(string url, int? page = null) {

    // Store it.
    ViewBag.url = url;

    // Everything else
    // ...

}

And then in your view:

@Html.PagedListPager((IPagedList)ViewBag.links, pageNumber => Url.Action("RequestLinks", new { url = ViewBag.url, page = pageNumber }))

Which (making some assumptions) should generate links like:

/{controller}/RequestLinks?url=http://google.com&page=3


问:
Debug Assertion Failed
Today I run .exe file from Visual Studio's debug folder and it appears an Invalid Null Pointer error from this section of code

Error : Debug Assertion Failed

Program : C:\WINDOWS\SYSTEM32\MSVCP110D.dll

File : E:\visual studio 11\vc\include\xstring

Line : 1143

Expression : Invalid Null Pointer

I mostly done the code, but there are one problem with a line of code. It keeps saying the error because of the 4th line ( the one that I bold ) :

```<code>void main(int argc,const char *argv[])
{
string a, HauTo;
**string fileName(argv[1]);**
StackC s;
InitS(s); //Initialize an empty stack

fstream fi, fo;
fi.open(fileName, ios::in);
fo.open("Output.txt", ios::out);
getline(fi, a);
</code>```

I'm doing an assignment so it would be grateful if someone help me with this.

答:
You haven't said how you run this, but note that you have an argc which you didn't check.

This says how many args you sent in to main.

If you try to access argv[1] and there is only one arg (argv[0] - the program name itself) you have an error.

If you specifically wish to pass parameters or "Command arguments" inside Visual Studio, right click on the project and go to "Properties". Then find "Debugging" and enter you arguments there

Title: Debug Assertion Failed

Body:
Today I run .exe file from Visual Studio's debug folder and it appears an Invalid Null Pointer error from this section of code

Error : Debug Assertion Failed

Program : C:\WINDOWS\SYSTEM32\MSVCP110D.dll

File : E:\visual studio 11\vc\include\xstring

Line : 1143

Expression : Invalid Null Pointer

I mostly done the code, but there are one problem with a line of code. It keeps saying the error because of the 4th line ( the one that I bold ) :

void main(int argc,const char *argv[])
{
string a, HauTo;
**string fileName(argv[1]);**
StackC s;
InitS(s); //Initialize an empty stack

fstream fi, fo;
fi.open(fileName, ios::in);
fo.open("Output.txt", ios::out);
getline(fi, a);

I'm doing an assignment so it would be grateful if someone help me with this.


问:
Converting FORTRAN to C / C++
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

```<code>copy makefile.vc makefile
nmake
</code>```

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?

答:
You aren't real clear on this, but it sounds like you want to study the code, and in order to do that you want to convert it to C or C++.  If you want to use the code rather than study it, then I'm off-base here, and you should look for Fortran compilers.

Give up.  You can't find any way of translating idiomatic Fortran to idiomatic C or C++.  There's subtle semantic differences between the languages, and in order to get it right the translation program needs to be very precise, and account for lots of things, and make obscure function calls, and that can be very confusing.  You will not get readable C or C++.

Instead, you should learn the appropriate version of Fortran.  If you understand C and C++, it shouldn't be at all hard to learn.  It's just another language, and it won't have much in the way of new concepts.

Title: Converting FORTRAN to C / C++

Body:
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

copy makefile.vc makefile
nmake

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?


问:
Duplicate values of every data row
There are 2 rows in my table and I'm receiving values within my site as follows:

I should only be receiving 2 rows so I'm not sure what I've done wrong with my code?

```<code>if (binForm.Rows.Count != 0)
{
    int rowCounter = binForm.Rows.Count;
    int increment = 0;
    while (rowCounter > 0)
    {
        tableData.Append("<tr><td>" + binForm.Rows[increment]["binType"].ToString() + "</td><td>" + binForm.Rows[increment]["binColour"].ToString() + "</td><td>" + binForm.Rows[increment]["date"].ToString() + "</td><tr>");
        increment++;
        rowCounter--;

    }

  }
</code>```

This is how the form is generated:

```<code>DataTable binForm = new DataTable();

MySqlDataAdapter dataAdapter = new MySqlDataAdapter("SELECT bin.binType, bin.binColour, missedbin.date FROM bin INNER JOIN missedbin ON missedbin.address_addressID=bin.address_addressID WHERE '" + sessionVarAddress.ToString() + "' = bin.address_addressID ", connect);
dataAdapter.Fill(binForm);
</code>```

here is the actual data in the bin table.

and missedbin table.

EDIT: It seems as though as suggested my sql query is incorrect as it is returning 4 rows.

答:
The problem will be the join, not this snip-it of code.

if you join on a field with 2 entries the same, it will double up as per this example. please go back and check your query.

Title: Duplicate values of every data row

Body:
There are 2 rows in my table and I'm receiving values within my site as follows:

I should only be receiving 2 rows so I'm not sure what I've done wrong with my code?

if (binForm.Rows.Count != 0)
{
    int rowCounter = binForm.Rows.Count;
    int increment = 0;
    while (rowCounter > 0)
    {
        tableData.Append("
" + binForm.Rows[increment]["binType"].ToString() + "	" + binForm.Rows[increment]["binColour"].ToString() + "	" + binForm.Rows[increment]["date"].ToString() + "
");
        increment++;
        rowCounter--;

    }

  }

This is how the form is generated:

DataTable binForm = new DataTable();

MySqlDataAdapter dataAdapter = new MySqlDataAdapter("SELECT bin.binType, bin.binColour, missedbin.date FROM bin INNER JOIN missedbin ON missedbin.address_addressID=bin.address_addressID WHERE '" + sessionVarAddress.ToString() + "' = bin.address_addressID ", connect);
dataAdapter.Fill(binForm);

here is the actual data in the bin table.

and missedbin table.

EDIT: It seems as though as suggested my sql query is incorrect as it is returning 4 rows.


问:
What happens if a use-case fails use-case testing?
I've not been able to find this question anywhere on the Internet, and since i'm working on my exam project at the moment, I would hope for this to get answered.

What happens to a use-case if it fails the boss/EBP/size tests? Do you throw it out, rewrite it, does it become a non-functional requirement?

Or does the testing simply prove whether or not a use-case has high business/risk/architectural value for the rest of the project? And you should down prioritize a use-case which failed tests (if only just one test)?

Thanks for your time. Craig Larman's book doesn't really go into depth about this, as far as I know.

答:
If a usecase under consideration fails Boss Test (means this usecase is not valuable for boss)

Then it might stand as a Common Sub Function (as it is a sub function of all major other usecases

If you ask me i dont formalize any name for assigning Priority to usecases in order to consider them for a proper testing.

These are just names assigned to Priority Levels.


问:
XSLT: rename XML attributes
I've got the following XML

```<code><message code="100" description="checkSnr">
 <string name="id" />
 <string name="serialNr" />
</message>
</code>```

Now I basically want to rename

```<code><string name="serialNr" />
</code>```

into

```<code><string name1="serialNr" />
</code>```

I read all the other questions about this topic but none work for me.

The idea behind this is easy: The single strings are supposed to be different to each other. Example:

```<code><xsl:value-of select="message/string/@name"  />
</code>```

will be "id".

```<code><xsl:value-of select="message/string/@name1"  />
</code>```

will be "serialNr".

I want them to be listed in a CSV like "id;serialNr" my actual output without renaming the attributes is "id;id". If you've got any other ideas how to solve this problem, your solutions are appreciated aswell!

Thanks in advance.

答:
If @TimC has correctly guessed what your real requirements are, then you want</p>

```<code><xsl:template match="message">
  <xsl:apply-templates select="string"/>
</xsl:template>

<xsl:template match="string">
  <string>
    <xsl:attribute name="name{position()}">
      <xsl:value-of select="@name"/>
    </xsl:attribute>
  </string>
</xsl:template>
</code>```

Title: XSLT: rename XML attributes

Body:
I've got the following XML

<message code="100" description="checkSnr">
 <string name="id" />
 <string name="serialNr" />
</message>

Now I basically want to rename

<string name="serialNr" />

into

<string name1="serialNr" />

I read all the other questions about this topic but none work for me.

The idea behind this is easy: The single strings are supposed to be different to each other. Example:

<xsl:value-of select="message/string/@name"  />

will be "id".

<xsl:value-of select="message/string/@name1"  />

will be "serialNr".

I want them to be listed in a CSV like "id;serialNr" my actual output without renaming the attributes is "id;id". If you've got any other ideas how to solve this problem, your solutions are appreciated aswell!

Thanks in advance.

Body:
If @TimC has correctly guessed what your real requirements are, then you want

<xsl:template match="message">
  <xsl:apply-templates select="string"/>
</xsl:template>

<xsl:template match="string">
  <string>
    <xsl:attribute name="name{position()}">
      <xsl:value-of select="@name"/>
    </xsl:attribute>
  </string>
</xsl:template>