问:
MS ACCESS VBA, working days function incl. holiday when faling on weekend
When deploying MSDN function for calculating working days, beside a problem with date formatting I found an issue with Holiday count.

Calculation is correct, but only if Holiday is on working day. If it is on a saturday or sunday, it also substract it and produce a false result.
illustration of a false reading

A Function for Workdays:

```<code>Public Function Workdays(ByRef startDate As Date, ByRef endDate As Date, Optional ByRef strHolidays As String = "Holidays") As Integer
On Error GoTo Workdays_Error
Dim nWeekdays, nHolidays As Integer
Dim strWhere As String

startDate = DateValue(startDate)
endDate = DateValue(endDate)
nWeekdays = Weekdays(startDate, endDate)

If nWeekdays = -1 Then
    Workdays = -1
    GoTo Workdays_Exit
End If

strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

Workdays_Exit:
    Exit Function
    Resume Workdays_Exit

End Function
</code>```

And here is a function for calculating weekdays:

```<code>Public Function Weekdays(ByRef startDate As Date, ByRef endDate As Date) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.

On Error GoTo Weekdays_Error
Const ncNumberOfWeekendDays As Integer = 2 'The number of weekend days per week.
Dim varDays As Variant                  'The number of days inclusive.
Dim varWeekendDays As Variant     'The number of weekend days.
Dim dtmX As Date                          'Temporary storage for datetime.

' If the end date is earlier, swap the dates.
If endDate < startDate Then
    dtmX = startDate
    startDate = endDate
    endDate = dtmX
End If

' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", date1:=startDate, date2:=endDate) + 1

' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", date1:=startDate, date2:=endDate) _
    * ncNumberOfWeekendDays) + IIf(DatePart(Interval:="w", _
    Date:=startDate) = vbSunday, 1, 0) + IIf(DatePart(Interval:="w", Date:=endDate) = vbSaturday, 1, 0)

' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)

Weekdays_Exit:
    Exit Function

Weekdays_Error:
    Weekdays = -1
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Weekdays"
    Resume Weekdays_Exit
</code>```

Please advise how to ignore holiday if holiday = 1 or holiday = 7.
Plus, in extended period of time, there could be more than one holidays, falling or not on weekend.

答:
It is much simpler just to loop the dates and count:

```<code>Public Function DateDiffWorkdays( _
    ByVal datDate1 As Date, _
    ByVal datDate2 As Date, _
    Optional ByVal booWorkOnHolidays As Boolean) _
    As Long

'   Calculates the count of workdays between datDate1 and datDate2.
'   2014-10-03. Cactus Data ApS, CPH

    Dim aHolidays() As Date

    Dim lngDiff     As Long
    Dim lngSign     As Long
    Dim lngHoliday  As Long

    lngSign = Sgn(DateDiff("d", datDate1, datDate2))
    If lngSign <> 0 Then
        If booWorkOnHolidays = True Then
            ' Holidays are workdays.
        Else
            ' Retrieve array with holidays between datDate1 and datDate2.
            aHolidays = GetHolidays(datDate1, datDate2)
        End If

        Do Until DateDiff("d", datDate1, datDate2) = 0
            Select Case Weekday(datDate1)
                Case vbSaturday, vbSunday
                    ' Skip weekend.
                Case Else
                    ' Check for holidays to skip.
                    ' Ignore error when using LBound and UBound on an unassigned array.
                    On Error Resume Next
                    For lngHoliday = LBound(aHolidays) To UBound(aHolidays)
                        If Err.Number > 0 Then
                            ' No holidays between datDate1 and datDate2.
                        ElseIf DateDiff("d", datDate1, aHolidays(lngHoliday)) = 0 Then
                            ' This datDate1 hits a holiday.
                            ' Subtract one day before adding one after the loop.
                            lngDiff = lngDiff - lngSign
                            Exit For
                        End If
                    Next
                    On Error GoTo 0
                    lngDiff = lngDiff + lngSign
            End Select
            datDate1 = DateAdd("d", lngSign, datDate1)
        Loop
    End If

    DateDiffWorkdays = lngDiff

End Function
</code>```

and the holidays function:

```<code>Public Function GetHolidays( _
    ByVal datDate1 As Date, _
    ByVal datDate2 As Date, _
    Optional ByVal booDesc As Boolean) _
    As Date()

'   Finds the count of holidays between datDate1 and datDate2.
'   The holidays are returned as an array of dates.
'   DAO objects are declared static to speed up repeated calls with identical date parameters.
'   2014-10-03. Cactus Data ApS, CPH

    ' The table that holds the holidays.
    Const cstrTable             As String = "tblHoliday"
    ' The field of the table that holds the dates of the holidays.
    Const cstrField             As String = "HolidayDate"
    ' Constants for the arrays.
    Const clngDimRecordCount    As Long = 2
    Const clngDimFieldOne       As Long = 0

    Static dbs              As DAO.Database
    Static rst              As DAO.Recordset

    Static datDate1Last     As Date
    Static datDate2Last     As Date

    Dim adatDays()  As Date
    Dim avarDays    As Variant

    Dim strSQL      As String
    Dim strDate1    As String
    Dim strDate2    As String
    Dim strOrder    As String
    Dim lngDays     As Long

    If DateDiff("d", datDate1, datDate1Last) <> 0 Or DateDiff("d", datDate2, datDate2Last) <> 0 Then
        ' datDate1 or datDate2 has changed since the last call.
        strDate1 = Format(datDate1, "\#yyyy\/mm\/dd\#")
        strDate2 = Format(datDate2, "\#yyyy\/mm\/dd\#")
        strOrder = Format(booDesc, "\A\s\c;\D\e\s\c")

        strSQL = "Select " & cstrField & " From " & cstrTable & " " & _
            "Where " & cstrField & " Between " & strDate1 & " And " & strDate2 & " " & _
            "Order By 1 " & strOrder

        Set dbs = CurrentDb
        Set rst = dbs.OpenRecordset(strSQL, dbOpenSnapshot)

        ' Save the current set of date parameters.
        datDate1Last = datDate1
        datDate2Last = datDate2
    End If

    lngDays = rst.RecordCount
    If lngDays = 0 Then
        ' Leave adatDays() as an unassigned array.
    Else
        ReDim adatDays(lngDays - 1)
        ' As repeated calls may happen, do a movefirst.
        rst.MoveFirst
        avarDays = rst.GetRows(lngDays)
        ' rst is now positioned at the last record.
        For lngDays = LBound(avarDays, clngDimRecordCount) To UBound(avarDays, clngDimRecordCount)
            adatDays(lngDays) = avarDays(clngDimFieldOne, lngDays)
        Next
    End If

    ' DAO objects are static.
    ' Set rst = Nothing
    ' Set dbs = Nothing

    GetHolidays = adatDays()

End Function
</code>```

Body:
When deploying MSDN function for calculating working days, beside a problem with date formatting I found an issue with Holiday count.

Calculation is correct, but only if Holiday is on working day. If it is on a saturday or sunday, it also substract it and produce a false result.
illustration of a false reading

A Function for Workdays:

Public Function Workdays(ByRef startDate As Date, ByRef endDate As Date, Optional ByRef strHolidays As String = "Holidays") As Integer
On Error GoTo Workdays_Error
Dim nWeekdays, nHolidays As Integer
Dim strWhere As String

startDate = DateValue(startDate)
endDate = DateValue(endDate)
nWeekdays = Weekdays(startDate, endDate)

If nWeekdays = -1 Then
    Workdays = -1
    GoTo Workdays_Exit
End If

strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

Workdays_Exit:
    Exit Function
    Resume Workdays_Exit

End Function

And here is a function for calculating weekdays:

Public Function Weekdays(ByRef startDate As Date, ByRef endDate As Date) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.

On Error GoTo Weekdays_Error
Const ncNumberOfWeekendDays As Integer = 2 'The number of weekend days per week.
Dim varDays As Variant                  'The number of days inclusive.
Dim varWeekendDays As Variant     'The number of weekend days.
Dim dtmX As Date                          'Temporary storage for datetime.

' If the end date is earlier, swap the dates.
If endDate < startDate Then
    dtmX = startDate
    startDate = endDate
    endDate = dtmX
End If

' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", date1:=startDate, date2:=endDate) + 1

' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", date1:=startDate, date2:=endDate) _
    * ncNumberOfWeekendDays) + IIf(DatePart(Interval:="w", _
    Date:=startDate) = vbSunday, 1, 0) + IIf(DatePart(Interval:="w", Date:=endDate) = vbSaturday, 1, 0)

' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)

Weekdays_Exit:
    Exit Function

Weekdays_Error:
    Weekdays = -1
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Weekdays"
    Resume Weekdays_Exit

Please advise how to ignore holiday if holiday = 1 or holiday = 7.
Plus, in extended period of time, there could be more than one holidays, falling or not on weekend.

Body:
It is much simpler just to loop the dates and count:

Public Function DateDiffWorkdays( _
    ByVal datDate1 As Date, _
    ByVal datDate2 As Date, _
    Optional ByVal booWorkOnHolidays As Boolean) _
    As Long

'   Calculates the count of workdays between datDate1 and datDate2.
'   2014-10-03. Cactus Data ApS, CPH

    Dim aHolidays() As Date

    Dim lngDiff     As Long
    Dim lngSign     As Long
    Dim lngHoliday  As Long

    lngSign = Sgn(DateDiff("d", datDate1, datDate2))
    If lngSign <> 0 Then
        If booWorkOnHolidays = True Then
            ' Holidays are workdays.
        Else
            ' Retrieve array with holidays between datDate1 and datDate2.
            aHolidays = GetHolidays(datDate1, datDate2)
        End If

        Do Until DateDiff("d", datDate1, datDate2) = 0
            Select Case Weekday(datDate1)
                Case vbSaturday, vbSunday
                    ' Skip weekend.
                Case Else
                    ' Check for holidays to skip.
                    ' Ignore error when using LBound and UBound on an unassigned array.
                    On Error Resume Next
                    For lngHoliday = LBound(aHolidays) To UBound(aHolidays)
                        If Err.Number > 0 Then
                            ' No holidays between datDate1 and datDate2.
                        ElseIf DateDiff("d", datDate1, aHolidays(lngHoliday)) = 0 Then
                            ' This datDate1 hits a holiday.
                            ' Subtract one day before adding one after the loop.
                            lngDiff = lngDiff - lngSign
                            Exit For
                        End If
                    Next
                    On Error GoTo 0
                    lngDiff = lngDiff + lngSign
            End Select
            datDate1 = DateAdd("d", lngSign, datDate1)
        Loop
    End If

    DateDiffWorkdays = lngDiff

End Function

and the holidays function:

Public Function GetHolidays( _
    ByVal datDate1 As Date, _
    ByVal datDate2 As Date, _
    Optional ByVal booDesc As Boolean) _
    As Date()

'   Finds the count of holidays between datDate1 and datDate2.
'   The holidays are returned as an array of dates.
'   DAO objects are declared static to speed up repeated calls with identical date parameters.
'   2014-10-03. Cactus Data ApS, CPH

    ' The table that holds the holidays.
    Const cstrTable             As String = "tblHoliday"
    ' The field of the table that holds the dates of the holidays.
    Const cstrField             As String = "HolidayDate"
    ' Constants for the arrays.
    Const clngDimRecordCount    As Long = 2
    Const clngDimFieldOne       As Long = 0

    Static dbs              As DAO.Database
    Static rst              As DAO.Recordset

    Static datDate1Last     As Date
    Static datDate2Last     As Date

    Dim adatDays()  As Date
    Dim avarDays    As Variant

    Dim strSQL      As String
    Dim strDate1    As String
    Dim strDate2    As String
    Dim strOrder    As String
    Dim lngDays     As Long

    If DateDiff("d", datDate1, datDate1Last) <> 0 Or DateDiff("d", datDate2, datDate2Last) <> 0 Then
        ' datDate1 or datDate2 has changed since the last call.
        strDate1 = Format(datDate1, "\#yyyy\/mm\/dd\#")
        strDate2 = Format(datDate2, "\#yyyy\/mm\/dd\#")
        strOrder = Format(booDesc, "\A\s\c;\D\e\s\c")

        strSQL = "Select " & cstrField & " From " & cstrTable & " " & _
            "Where " & cstrField & " Between " & strDate1 & " And " & strDate2 & " " & _
            "Order By 1 " & strOrder

        Set dbs = CurrentDb
        Set rst = dbs.OpenRecordset(strSQL, dbOpenSnapshot)

        ' Save the current set of date parameters.
        datDate1Last = datDate1
        datDate2Last = datDate2
    End If

    lngDays = rst.RecordCount
    If lngDays = 0 Then
        ' Leave adatDays() as an unassigned array.
    Else
        ReDim adatDays(lngDays - 1)
        ' As repeated calls may happen, do a movefirst.
        rst.MoveFirst
        avarDays = rst.GetRows(lngDays)
        ' rst is now positioned at the last record.
        For lngDays = LBound(avarDays, clngDimRecordCount) To UBound(avarDays, clngDimRecordCount)
            adatDays(lngDays) = avarDays(clngDimFieldOne, lngDays)
        Next
    End If

    ' DAO objects are static.
    ' Set rst = Nothing
    ' Set dbs = Nothing

    GetHolidays = adatDays()

End Function


来源: stackexchange

问:
Anchor tag in navbar takes whole row - angular
I am trying to make a topbar and a sidebar.

This is the code for my top navbar:

```<code><header>
        <nav class="navbar navbar-expand-md  fixed-top">
            <a href="#" class="navbar-left"><img src="logo.svg" /></a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
             </button>
            <div class="collapse navbar-collapse" id="navbarsExampleDefault">
                <ul class="navbar-right ">
                    <img src="avatar.png">
                    <li class="nav-item dropdown ">
                        <a class="nav-link ">Hello</a>

                    </li>
                </ul>

            </div>
        </nav>
    </header>
</code>```

And then my sidebar :

```<code> <div class="container-fluid">

            <nav class="col-sm-3 col-md-2 d-none d-sm-block sidebar">
                <ul class="nav nav-pills flex-column">
                    <li class="nav-item collapsed active" data-toggle="collapse" data-target="#home" >
                        <a class="nav-link active" href="#"> <img src="homeIcon.png" /> Home <span class="sr-only">(current)</span></a>
                    </li>
                    <ul class="sub-menu collapse " id="home">

                        <li class="nav-item "><a class="nav-link" href="#" > FirstMember</a></li>
                        <li class="nav-item "><a class="nav-link" href="#"> Second</a></li>
                        <li class="nav-item "><a class="nav-link" href="#"> Third</a></li>
                        <li class="nav-item "><a class="nav-link" href="#"> Fourth</a></li>

                    </ul>
                    <li class="nav-item">
                        <a class="nav-link" href="#"><img src="secondElement.png" /> Second Element</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#"><img src="" /> History</a>
                    </li>

                </ul>

            </nav>

 <app-home></app-home>
</code>```

So in app.component.html I am writing my sidebar and navbar, and then  is the content.

The issue is that in the topbar.. the  where the logo stands, takes the whole row, which then pushes the button and the Hello on the next row.
Only the image inserted is smaller, but when I hover in the a href, it's in the whole row.

How do I fix this ?
And also, every element on the sidebar has an image as an icon, is it better that when the screen gets smaller, the text gets removed and only icons show, or do I make the sidebar appear as a dropdown on the top in smaller screens?

I am using angular5 and bootstrap4.
This is the css :

```<code>/* Move down content  */

body {
padding-top: 5.5rem;
background-color: #F4F4F4;

 }

.navbar {
background-color: #fff;
}

.nav.nav-link a {
color: #;
}

.sidebar {
position: fixed;
top: 69px;
bottom: 0;
left: 0;
z-index: 1000;
padding: 0;
overflow-x: hidden;
overflow-y: auto;
/* Scrollable contents if viewport is shorter than content. */
border-right: 1px solid #eee;
background-color: #
}

.sidebar li{
padding-left: 5px;
}
.sidebar .nav {
margin-bottom: 20px;

}
.sidebar .nav-item {
width: 100%;
}
.sidebar .nav-item+.nav-item {
margin-left: 0;
}
.sidebar .nav-link {
border-radius: 0;
}
.flex-column a {
color: #fff;
}

.dropdown{
font-weight: bold;
color:#;
}

.nav-pills .active{
 background-color: ;
 font-weight:bold;
}
.nav-pills .nav-link.active {
background-color: ;
color: #1C2058;

}
</code>```

I am using:

angular/cli: 1.5.0

Angular:  5.0.1

Node:8.9.1

bootstrap: ^4.0.0-alpha.6,

jquery: ^3.2.1,

答:
From your example your anchor isn't using .navbar-brand and instead uses .navbar-left, which if I remember is Bootstrap v3.  I can't find navbar-left as a class in v4 documentation:

```<code><a class="navbar-brand" href="#">
  <img src="logo.svg" />
</a>
</code>```

You're also using nav-item for the dropdown, which is also incorrect it should be nav-link dropdown.  I would get a new copy of your navbar from the v4 documentation and see if it works when you paste it in.

If it does, but just doesn't work in your application it might be due to ViewEncapsulation so you need to make sure your styles are either globally available (styles.scss) or they are in your navbar components SCSS file (navbar.component.scss or example.component.scss)

All you have left now is to comment out your custom CSS, and paste a fresh copy of the v4 navbar directly from the docs with no changes.  That should work immediately.  Then slowly start applying the custom changes until it breaks starting with just your branding.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a topbar and a sidebar.

This is the code for my top navbar:

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

             </button>

                        Hello

And then my sidebar :

                          Home (current)

 FirstMember

 Second

 Third

 Fourth

                         Second Element

                         History

 <app-home></app-home>

So in app.component.html I am writing my sidebar and navbar, and then  is the content.

The issue is that in the topbar.. the  where the logo stands, takes the whole row, which then pushes the button and the Hello on the next row.
Only the image inserted is smaller, but when I hover in the a href, it's in the whole row.

How do I fix this ?
And also, every element on the sidebar has an image as an icon, is it better that when the screen gets smaller, the text gets removed and only icons show, or do I make the sidebar appear as a dropdown on the top in smaller screens?

I am using angular5 and bootstrap4.
This is the css :

/* Move down content  */

body {
padding-top: 5.5rem;
background-color: #F4F4F4;

 }

.navbar {
background-color: #fff;
}

.nav.nav-link a {
color: #;
}

.sidebar {
position: fixed;
top: 69px;
bottom: 0;
left: 0;
z-index: 1000;
padding: 0;
overflow-x: hidden;
overflow-y: auto;
/* Scrollable contents if viewport is shorter than content. */
border-right: 1px solid #eee;
background-color: #
}

.sidebar li{
padding-left: 5px;
}
.sidebar .nav {
margin-bottom: 20px;

}
.sidebar .nav-item {
width: 100%;
}
.sidebar .nav-item+.nav-item {
margin-left: 0;
}
.sidebar .nav-link {
border-radius: 0;
}
.flex-column a {
color: #fff;
}

.dropdown{
font-weight: bold;
color:#;
}

.nav-pills .active{
 background-color: ;
 font-weight:bold;
}
.nav-pills .nav-link.active {
background-color: ;
color: #1C2058;

}

I am using:

angular/cli: 1.5.0

Angular:  5.0.1

Node:8.9.1

bootstrap: ^4.0.0-alpha.6,

jquery: ^3.2.1,

Body:
From your example your anchor isn't using .navbar-brand and instead uses .navbar-left, which if I remember is Bootstrap v3.  I can't find navbar-left as a class in v4 documentation:

<a class="navbar-brand" href="#">
  <img src="logo.svg" />
</a>

You're also using nav-item for the dropdown, which is also incorrect it should be nav-link dropdown.  I would get a new copy of your navbar from the v4 documentation and see if it works when you paste it in.

If it does, but just doesn't work in your application it might be due to ViewEncapsulation so you need to make sure your styles are either globally available (styles.scss) or they are in your navbar components SCSS file (navbar.component.scss or example.component.scss)

All you have left now is to comment out your custom CSS, and paste a fresh copy of the v4 navbar directly from the docs with no changes.  That should work immediately.  Then slowly start applying the custom changes until it breaks starting with just your branding.


问:
Image orientation when retrieving original image with readAsDataURL
I can't find any example for using FileReader.readAsDataURL and show the result image in a container with the right image orientation.

All the portrait images coming from my camera and iPhone devices have this issue. Only the portrait photos saved with adobe photoshop seem to not have this issue.

Here is one of the example system that I've found in the internet. My code is very similar:
http://www.onlywebpro.com/demo/file_reader/reader01.html

Notice when uploading this photo that it's loaded in landscape mode: http://www.rafaelsanches.com/IMG_3786.JPG

Notice that the image actually displays in landscape when using the browser to download it. When you save it to the disk and open with the finder it is previewed in portrait. (Probably the finder is clever to use the exif info)

Using exif.js I have discovered that the example image has an Orientation=8. The photos that are saved using photoshop have an Orientation=1.

Now, how do you guys suggest that I go about this? Should I plot it in a canvas and rotate depending on the exif information? Someone has a good tutorial about this? Have anyone faced this problem before?

答:
I actually had this problem today and resolved it...

After the line from the example where the image is created...

This is what I've done

```<code>var image = $(".uploaded");
                var img = new Image();

                img.src = e.target.result;

                if (img.complete) { // was cached
                    if (img.height < img.width) {
                        $(image).addClass("landscape").removeClass("portrait");

                    }
                    else {
                        $(image).addClass("portrait").removeClass("landscape");
                    }

                }
                else { // wait for decoding
                    img.onload = function () {
                        if (img.height < img.width) {
                            $(image).addClass("landscape").removeClass("portrait");

                        }
                        else {
                            $(image).addClass("portrait").removeClass("landscape");
                        }
                    }
                }
</code>```

Body:
I actually had this problem today and resolved it...

After the line from the example where the image is created...

This is what I've done

var image = $(".uploaded");
                var img = new Image();

                img.src = e.target.result;

                if (img.complete) { // was cached
                    if (img.height < img.width) {
                        $(image).addClass("landscape").removeClass("portrait");

                    }
                    else {
                        $(image).addClass("portrait").removeClass("landscape");
                    }

                }
                else { // wait for decoding
                    img.onload = function () {
                        if (img.height < img.width) {
                            $(image).addClass("landscape").removeClass("portrait");

                        }
                        else {
                            $(image).addClass("portrait").removeClass("landscape");
                        }
                    }
                }


问:
Ending OpenMP for prematurely
I have a problem with writing a routine in C++ using OpenMP for. The code of the routine is as follows:

```<code>int sudokuSolution [9][9];

bool solvep(int s[9][9], int row, int col) {
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if (isPossible(s,row,col,val)) {
                s[row][col] = val;
                if (solve(s, row + col / 9, (col + 1) % 9)) {
                    sudokuSolution[row][col] = val;
                    solution = true;
                }
            }
        }
    return solution;
}
</code>```

when running this routine without the parallel clause, everything works fine (i.e. routine returns true every time it's called). However, when I use the parallel for, it sometimes returns false. I wasn't able to figure out, why is this happening and the only way of removing this bug is from my perspective ending the whole parallel block prematurely after solution is set to true. However, if I did my research properly, there is no way to prematurely end a parallel block. Could you please suggest me an alternative?

EDIT: Adding minimal functioning example as requested:

```<code>#include <omp.h>
#include <iostream>
#include <list>
#include <chrono>

using namespace std;

bool solutionFound = false;
int sudoku [9][9] = { 5,7,0,9,0,0,0,0,8,
                      0,0,0,0,0,5,0,3,9,
                      0,0,0,0,0,0,2,0,4,
                      0,0,0,0,9,0,6,8,0,
                      0,0,0,8,0,2,0,0,0,
                      0,5,2,0,7,0,0,0,0,
                      6,0,5,0,0,0,0,0,0,
                      7,9,0,4,0,0,0,0,0,
                      2,0,0,0,0,9,0,7,6};

int sudokuSolution [9][9];

bool isPossible(int s[9][9], int row, int col, int val) {
    for(int i = 0; i < 9; i++) {
        if (s[row][i] == val)
            return false;
        if (s[i][col] == val)
            return false;
        if (s[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == val)
            return false;
    }
    return true;
}

bool solve(int s[9][9], int row, int col) {
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }

    for (int val = 1; val < 10; val++) {
        if (isPossible(s,row,col,val)){
            sudokuSolution[row][col] = val;
            s[row][col] = val;
            if (solve(s, row + col / 9, (col + 1) % 9))
                return true;
            sudokuSolution[row][col] = 0;
            s[row][col] = 0;
        }
    }
    return false;
}

bool solvep(int sa[9][9], int row, int col) {
    int s [9][9];
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 9; j++)
            s[i][j] = sa[i][j];
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if(!solutionFound) {
                if (isPossible(s,row,col,val)){
                    s[row][col] = val;
                    if (solve(s, row + col / 9, (col + 1) % 9)) {
                        sudokuSolution[row][col] = val;
                        solutionFound = true;
                        solution = true;
                    }
                }
            }
        }
    return solution;
}

int main() {
    for (int k = 0; k < 100; k++) {
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
                sudokuSolution[i][j] = sudoku[i][j];
        solutionFound = false;
        solvep(sudokuSolution,0,0);
        bool calcResult = solvep(sudoku,0,0);
        cout << calcResult;
    }
    return 0;
}
</code>```

答:
You have many race conditions in your code, both in the loop itself and the solve function. In code that is executed in parallel you must not write to to shared data (s, solution, sudokuSolution) and especially global variables (solutionFound). You will have to go back to your learning material and catch up with data races and the methods to protect against them.

With some experience it is easy to spot the issues in the loop itself. It's much harder to spot in called functions - which is why its so important to give a complete example in your question. Try to define your interfaces such that mutable no shared data is passed to functions. Conceptually you will have to have a copy of the board for each thread to perform backtracking in parallel.

Once you fix the issues with writing to the board, you can use atomic writes, a critical region or a reduction to "share" the solution. But you have to consider both sudokuSolution[row][col] and solution. Logically I suppose sudokuSolution[row][col] != 0 == solution.

Title: Ending OpenMP for prematurely

Body:
I have a problem with writing a routine in C++ using OpenMP for. The code of the routine is as follows:

int sudokuSolution [9][9];

bool solvep(int s[9][9], int row, int col) {
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if (isPossible(s,row,col,val)) {
                s[row][col] = val;
                if (solve(s, row + col / 9, (col + 1) % 9)) {
                    sudokuSolution[row][col] = val;
                    solution = true;
                }
            }
        }
    return solution;
}

when running this routine without the parallel clause, everything works fine (i.e. routine returns true every time it's called). However, when I use the parallel for, it sometimes returns false. I wasn't able to figure out, why is this happening and the only way of removing this bug is from my perspective ending the whole parallel block prematurely after solution is set to true. However, if I did my research properly, there is no way to prematurely end a parallel block. Could you please suggest me an alternative?

EDIT: Adding minimal functioning example as requested:

#include <omp.h>
#include <iostream>
#include <list>
#include <chrono>

using namespace std;

bool solutionFound = false;
int sudoku [9][9] = { 5,7,0,9,0,0,0,0,8,
                      0,0,0,0,0,5,0,3,9,
                      0,0,0,0,0,0,2,0,4,
                      0,0,0,0,9,0,6,8,0,
                      0,0,0,8,0,2,0,0,0,
                      0,5,2,0,7,0,0,0,0,
                      6,0,5,0,0,0,0,0,0,
                      7,9,0,4,0,0,0,0,0,
                      2,0,0,0,0,9,0,7,6};

int sudokuSolution [9][9];

bool isPossible(int s[9][9], int row, int col, int val) {
    for(int i = 0; i < 9; i++) {
        if (s[row][i] == val)
            return false;
        if (s[i][col] == val)
            return false;
        if (s[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == val)
            return false;
    }
    return true;
}

bool solve(int s[9][9], int row, int col) {
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }

    for (int val = 1; val < 10; val++) {
        if (isPossible(s,row,col,val)){
            sudokuSolution[row][col] = val;
            s[row][col] = val;
            if (solve(s, row + col / 9, (col + 1) % 9))
                return true;
            sudokuSolution[row][col] = 0;
            s[row][col] = 0;
        }
    }
    return false;
}

bool solvep(int sa[9][9], int row, int col) {
    int s [9][9];
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 9; j++)
            s[i][j] = sa[i][j];
    while(s[row][col] != 0) {
        col = (col + 1) % 9;
        row = row + col / 8;
        if(row == 9)
            return true;
    }
    bool solution = false;
    #pragma omp parallel for
        for (int val = 1; val < 10; val++) {
            if(!solutionFound) {
                if (isPossible(s,row,col,val)){
                    s[row][col] = val;
                    if (solve(s, row + col / 9, (col + 1) % 9)) {
                        sudokuSolution[row][col] = val;
                        solutionFound = true;
                        solution = true;
                    }
                }
            }
        }
    return solution;
}

int main() {
    for (int k = 0; k < 100; k++) {
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
                sudokuSolution[i][j] = sudoku[i][j];
        solutionFound = false;
        solvep(sudokuSolution,0,0);
        bool calcResult = solvep(sudoku,0,0);
        cout << calcResult;
    }
    return 0;
}


问:
Best way to parse command line args in Bash?
After several days of research, I still can't figure out the best method for parsing cmdline args in a .sh script.  According to my references the getopts cmd is the way to go since it "extracts and checks switches without disturbing the positional parameter variables.Unexpected switches, or switches that are missing arguments, are recognized and reportedas errors."

Positional params(Ex. 2 - $@, $#, etc)  apparently don't work well when spaces are involved but can recognize regular and long parameters(-p  and --longparam).  I noticed that both methods fail when passing parameters with nested quotes ("this is an Ex. of ""quotes"".").  Which one of these three code samples best illustrates the way to deal with cmdline args? The getopt function is not recommended by gurus, so I'm trying to avoid it!

Example 1:

```<code>#!/bin/bash
for i in "$@"
do
case $i in
    -p=*|--prefix=*)
    PREFIX=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`

    ;;
    -s=*|--searchpath=*)
    SEARCHPATH=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
    ;;
    -l=*|--lib=*)
    DIR=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
    ;;
    --default)
    DEFAULT=YES
    ;;
    *)
            # unknown option
    ;;
esac
done
exit 0
</code>```

Example 2:

```<code>#!/bin/bash
echo ‘number of arguments’
echo "\$#: $#"
echo ”

echo ‘using $num’
echo "\$0: $0"
if [ $# -ge 1 ];then echo "\$1: $1"; fi
if [ $# -ge 2 ];then echo "\$2: $2"; fi
if [ $# -ge 3 ];then echo "\$3: $3"; fi
if [ $# -ge 4 ];then echo "\$4: $4"; fi
if [ $# -ge 5 ];then echo "\$5: $5"; fi
echo ”

echo ‘using $@’
let i=1
for x in $@; do
echo "$i: $x"
let i=$i+1
done
echo ”

echo ‘using $*’
let i=1
for x in $*; do
echo "$i: $x"
let i=$i+1
done
echo ”

let i=1
echo ‘using shift’
while [ $# -gt 0 ]
do
echo "$i: $1"
let i=$i+1
shift
done

[/bash]

output:

bash> commandLineArguments.bash
number of arguments
$#: 0

using $num
$0: ./commandLineArguments.bash

using $@

using $*

using shift
#bash> commandLineArguments.bash  "abc def" g h i j*
</code>```

Example 3:

```<code>#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

exit 0
</code>```

答:
If you want to avoid using getopt you can use this nice quick approach:

Defining help with all options as ## comments (customise as you wish).

Define for each option a function with same name.

Copy the last five lines of this script to your script (the magic).

Example script: log.sh

#!/bin/sh
## $PROG 1.0 - Print logs [2017-10-01]
## Compatible with bash and dash/POSIX
##
## Usage: $PROG [OPTION...] [COMMAND]...
## Options:
##   -i, --log-info         Set log level to info (default)
##   -q, --log-quiet        Set log level to quiet
##   -l, --log MESSAGE      Log a message
## Commands:
##   -h, --help             Displays this help and exists
##   -v, --version          Displays output version and exists
## Examples:
##   $PROG -i myscrip-simple.sh > myscript-full.sh
##   $PROG -r myscrip-full.sh   > myscript-simple.sh
PROG=${0##*/}
LOG=info
die() { echo $@ >&2; exit 2; }

log_info() {
  LOG=info
}
log_quiet() {
  LOG=quiet
}
log() {
  [ $LOG = info ] && echo "$1"; return 1 ## number of args used
}
help() {
  grep "^##" "$0" | sed -e "s/^...//" -e "s/\$PROG/$PROG/g"; exit 0
}
version() {
  help | head -1
}

[ $# = 0 ] && help
while [ $# -gt 0 ]; do
  CMD=$(grep -m 1 -Po "^## *$1, --\K[^= ]*|^##.* --\K${1#--}(?:[= ])" log.sh | sed -e "s/-/_/g")
  if [ -z "$CMD" ]; then echo "ERROR: Command '$1' not supported"; exit 1; fi
  shift; eval "$CMD" $@ || shift $? 2> /dev/null
done
```

<h3>Testing</h3>

<p>Running this command:</p>

<pre class="lang-sh prettyprint-override"><code>./log.sh --log yep --log-quiet -l nop -i -l yes
</code>```

Produces this output:

```<code>yep
yes
</code>```

By the way: It's compatible with posix!

Body:
After several days of research, I still can't figure out the best method for parsing cmdline args in a .sh script.  According to my references the getopts cmd is the way to go since it "extracts and checks switches without disturbing the positional parameter variables.Unexpected switches, or switches that are missing arguments, are recognized and reportedas errors."

Positional params(Ex. 2 - $@, $#, etc)  apparently don't work well when spaces are involved but can recognize regular and long parameters(-p  and --longparam).  I noticed that both methods fail when passing parameters with nested quotes ("this is an Ex. of ""quotes"".").  Which one of these three code samples best illustrates the way to deal with cmdline args? The getopt function is not recommended by gurus, so I'm trying to avoid it!

Example 1:

#!/bin/bash
for i in "$@"
do
case $i in
    -p=*|--prefix=*)
    PREFIX=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`

    ;;
    -s=*|--searchpath=*)
    SEARCHPATH=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
    ;;
    -l=*|--lib=*)
    DIR=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
    ;;
    --default)
    DEFAULT=YES
    ;;
    *)
            # unknown option
    ;;
esac
done
exit 0

Example 2:

#!/bin/bash
echo ‘number of arguments’
echo "\$#: $#"
echo ”

echo ‘using $num’
echo "\$0: $0"
if [ $# -ge 1 ];then echo "\$1: $1"; fi
if [ $# -ge 2 ];then echo "\$2: $2"; fi
if [ $# -ge 3 ];then echo "\$3: $3"; fi
if [ $# -ge 4 ];then echo "\$4: $4"; fi
if [ $# -ge 5 ];then echo "\$5: $5"; fi
echo ”

echo ‘using $@’
let i=1
for x in $@; do
echo "$i: $x"
let i=$i+1
done
echo ”

echo ‘using $*’
let i=1
for x in $*; do
echo "$i: $x"
let i=$i+1
done
echo ”

let i=1
echo ‘using shift’
while [ $# -gt 0 ]
do
echo "$i: $1"
let i=$i+1
shift
done

[/bash]

output:

bash> commandLineArguments.bash
number of arguments
$#: 0

using $num
$0: ./commandLineArguments.bash

using $@

using $*

using shift
#bash> commandLineArguments.bash  "abc def" g h i j*

Example 3:

#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

exit 0

Body:
If you want to avoid using getopt you can use this nice quick approach:

Defining help with all options as ## comments (customise as you wish).

Define for each option a function with same name.

Copy the last five lines of this script to your script (the magic).

Example script: log.sh

#!/bin/sh
## $PROG 1.0 - Print logs [2017-10-01]
## Compatible with bash and dash/POSIX
##
## Usage: $PROG [OPTION...] [COMMAND]...
## Options:
##   -i, --log-info         Set log level to info (default)
##   -q, --log-quiet        Set log level to quiet
##   -l, --log MESSAGE      Log a message
## Commands:
##   -h, --help             Displays this help and exists
##   -v, --version          Displays output version and exists
## Examples:
##   $PROG -i myscrip-simple.sh > myscript-full.sh
##   $PROG -r myscrip-full.sh   > myscript-simple.sh
PROG=${0##*/}
LOG=info
die() { echo $@ >&2; exit 2; }

log_info() {
  LOG=info
}
log_quiet() {
  LOG=quiet
}
log() {
  [ $LOG = info ] && echo "$1"; return 1 ## number of args used
}
help() {
  grep "^##" "$0" | sed -e "s/^...//" -e "s/\$PROG/$PROG/g"; exit 0
}
version() {
  help | head -1
}

[ $# = 0 ] && help
while [ $# -gt 0 ]; do
  CMD=$(grep -m 1 -Po "^## *$1, --\K[^= ]*|^##.* --\K${1#--}(?:[= ])" log.sh | sed -e "s/-/_/g")
  if [ -z "$CMD" ]; then echo "ERROR: Command '$1' not supported"; exit 1; fi
  shift; eval "$CMD" $@ || shift $? 2> /dev/null
done

Testing

Running this command:

./log.sh --log yep --log-quiet -l nop -i -l yes

Produces this output:

yep
yes

By the way: It's compatible with posix!

ContentLicense: CC BY-SA 4.0


问:
how to fetch records based upon the order of rows of a column
So I am having below table /colums

Table A

```<code>filedName  newValue   OldValue
name        a           b
email       x           y
contactNo   123         432
name        aa          bb
email       xx          yy
contactNo   1234        4324
</code>```

I want the data based upon the name ,contact and email basis like the date should come like below

```<code>name --a
contact -123
email-x
name ---aa
contact--1234
email--xx
</code>```

This is basically the order of rows for the column field name.
Anyone please advice.

FYI:I had joined this table with few more table as well.

答:
A sort of hackish way is:</p>

```<code>SELECT *
FROM tableA
ORDER BY CASE CAST(filedName + '_' + newValue as varchar)
             WHEN 'name_a' THEN 1
             WHEN 'contactNo_123' THEN 2
             WHEN 'email_x' THEN 3
             WHEN 'name_aa' THEN 4
             WHEN 'contactNo_1234' THEN 5
             WHEN 'email_xx' THEN 6
             ELSE 7
         END
</code>```

Body:
So I am having below table /colums

Table A

filedName  newValue   OldValue
name        a           b
email       x           y
contactNo   123         432
name        aa          bb
email       xx          yy
contactNo   1234        4324

I want the data based upon the name ,contact and email basis like the date should come like below

name --a
contact -123
email-x
name ---aa
contact--1234
email--xx

This is basically the order of rows for the column field name.
Anyone please advice.

FYI:I had joined this table with few more table as well.

Body:
A sort of hackish way is:

SELECT *
FROM tableA
ORDER BY CASE CAST(filedName + '_' + newValue as varchar)
             WHEN 'name_a' THEN 1
             WHEN 'contactNo_123' THEN 2
             WHEN 'email_x' THEN 3
             WHEN 'name_aa' THEN 4
             WHEN 'contactNo_1234' THEN 5
             WHEN 'email_xx' THEN 6
             ELSE 7
         END


问:
Rspec: Run specific unit test on every model unless whitelisted
I have a multi-tenant SaaS app.  I run a tenant security test on every tenant model.

```<code>describe 'tenant security' do
  it "has only the current company's data" do
    set_tenant_company
    other_companys_data = create :model

    set_tenant_company
    this_companys_data = create :model

    expect(Model.all).to include this_companys_data
    expect(Model.all).not_to include other_companys_data
  end
end
</code>```

Is there a way to use meta programming to run this on every model? [Without explicitly coding anything into the unit test]  If so, is there a way to whitelist non-tenant models?

Tenant security is critical, and I don't want it inadvertantly overlooked.

答:
Base on Pedro's comments, and his question posted to the RSpec core team:

Create a shared example with test you want to implicitly include in each model.  The :unless condition is for white-listing models that should not include this test.

```<code>RSpec.shared_examples 'a tenant model' do
  it "has only the current company's data",unless: metadata[:not_a_tenant_model] == true do
    set_tenant_company
    other_companys_data = create subject.class.name.underscore.to_sym

    set_tenant_company
    this_companys_data = create subject.class.name.underscore.to_sym

    expect(subject.class.all).to include this_companys_data
    expect(subject.class.all).not_to include other_companys_data
  end
end
</code>```

Place the following line in your RSpec.configuration

```<code>RSpec.configure do |config|
  config.include_context 'a tenant model', type: :model
end
</code>```

This has the effect of placing the following in every model.

```<code>Rspec.describe TenantModel do
  it_behaves_like 'a tenant model'
end
</code>```

To whitelist a non-tenant model, just add the appropriate tag:

```<code>RSpec.decribe NonTenantModel, :not_a_tenant_model do
  # shared example will not be included
end
</code>```

Big thank you! to Pedro and the RSpec core team.

Body:
I have a multi-tenant SaaS app.  I run a tenant security test on every tenant model.

describe 'tenant security' do
  it "has only the current company's data" do
    set_tenant_company
    other_companys_data = create :model

    set_tenant_company
    this_companys_data = create :model

    expect(Model.all).to include this_companys_data
    expect(Model.all).not_to include other_companys_data
  end
end

Is there a way to use meta programming to run this on every model? [Without explicitly coding anything into the unit test]  If so, is there a way to whitelist non-tenant models?

Tenant security is critical, and I don't want it inadvertantly overlooked.

Body:
Base on Pedro's comments, and his question posted to the RSpec core team:

Create a shared example with test you want to implicitly include in each model.  The :unless condition is for white-listing models that should not include this test.

RSpec.shared_examples 'a tenant model' do
  it "has only the current company's data",unless: metadata[:not_a_tenant_model] == true do
    set_tenant_company
    other_companys_data = create subject.class.name.underscore.to_sym

    set_tenant_company
    this_companys_data = create subject.class.name.underscore.to_sym

    expect(subject.class.all).to include this_companys_data
    expect(subject.class.all).not_to include other_companys_data
  end
end

Place the following line in your RSpec.configuration

RSpec.configure do |config|
  config.include_context 'a tenant model', type: :model
end

This has the effect of placing the following in every model.

Rspec.describe TenantModel do
  it_behaves_like 'a tenant model'
end

To whitelist a non-tenant model, just add the appropriate tag:

RSpec.decribe NonTenantModel, :not_a_tenant_model do
  # shared example will not be included
end

Big thank you! to Pedro and the RSpec core team.


问:
Do I Have To Recreate Custom List Forms If I Recreate The List?
I had made a list and created a custom list form (Insert -> Sharepoint Controls -> Custom List Form).  Then, I completely deleted the list (but copied the custom list form) and then recreated it, having changed a few fields.  There is only one field I'm concerned with on my custom list form and it hasn't changed in name or datatype and the list name hasn't changed either.  Do I need to regenerate (and then customize) the Custom List Form or can I just use the copy I made and cut/paste it back into the list folder?</p>

答:
Well, no one answered and I have a solution that works well enough.  I just don't know if it's optimal:

Copy the old/current list GUID.

Delete and recreate the list.

Copy the new list GUID.

For each custom list form, find and replace the old list GUID with the new list GUID.

Remove/Update any references to the data parameters near the beginning of the list form web part.

Remove/Update any references to the parameters in the actual fields.

ContentLicense: CC BY-SA 2.5


问:
Why does system verilog max() and min() functions return a queue and not a single element?
I noticed this interesting thing about the max() and min() functions in SV LRM (1800-2012) 7.12 (Array manipulation methods). I tried out the max() and min() functions in a dummy SV file

```<code>int a[3] = {0,5,5};
int q[$];
int b;
q = a.max(); // legal
b = a.max(); // illegal
</code>```

The illegal statement error was

```<code>Incompatible complex type assignment
Type of source expression is incompatible with type of target expression.
Mismatching types cannot be used in assignments, initializations and
instantiations. The type of the target is 'int', while the type of the
source is 'int$[$]'.
</code>```

So I commented out the illegal statement and tested it. It compiled and ran fine but I was hoping to get some more insight as to why the function returns a queue and not a single element - I printed out the contents of q and the size, but the size is still 1 and 5 is being printed just once. Kind of redundant then to make the max() and min() functions return a queue ?

答:
It returns a queue to deal with empty queues and when the with () conditions have no matches. The the empty queue return is a a way to differentiate a true match from no matches.

Consider the below code. to find the minimum value of a that is greater than 5. a has data but none of its entries have above 5. b is empty, so it will return an empty. c will return 7.

```<code>int a[3] = '{0,5,5};
int b[$] = '{};
int c[4] = '{0,15,5,7};
int q[$];
q = a.min() with (item > 5); // no items >5, will return an empty queue
q = b.min();                 // queue is empty, will return an empty queue
q = c.min() with (item > 5); // will return a queue of size 1 with value 7
</code>```

Body:
I noticed this interesting thing about the max() and min() functions in SV LRM (1800-2012) 7.12 (Array manipulation methods). I tried out the max() and min() functions in a dummy SV file

int a[3] = {0,5,5};
int q[$];
int b;
q = a.max(); // legal
b = a.max(); // illegal

The illegal statement error was

Incompatible complex type assignment
Type of source expression is incompatible with type of target expression.
Mismatching types cannot be used in assignments, initializations and
instantiations. The type of the target is 'int', while the type of the
source is 'int$[$]'.

So I commented out the illegal statement and tested it. It compiled and ran fine but I was hoping to get some more insight as to why the function returns a queue and not a single element - I printed out the contents of q and the size, but the size is still 1 and 5 is being printed just once. Kind of redundant then to make the max() and min() functions return a queue ?

Body:
It returns a queue to deal with empty queues and when the with () conditions have no matches. The the empty queue return is a a way to differentiate a true match from no matches.

Consider the below code. to find the minimum value of a that is greater than 5. a has data but none of its entries have above 5. b is empty, so it will return an empty. c will return 7.

int a[3] = '{0,5,5};
int b[$] = '{};
int c[4] = '{0,15,5,7};
int q[$];
q = a.min() with (item > 5); // no items >5, will return an empty queue
q = b.min();                 // queue is empty, will return an empty queue
q = c.min() with (item > 5); // will return a queue of size 1 with value 7


问:
Match Character Whether or Not It Exists in Like Statement
I need a like expression that will match a character whether or not it exists.  It needs to match the following values:

..."value": "123456"...

..."value":  "123456"...

"...value":"123456"...

This like statement will almost work: LIKE '%value":%"123456"%'

But there are values like this one that would also match, but I don't want returned:

..."value":"99999", "other":"123456"...

A regex expression to do what I'm looking to do is 'value": *?"123456"'.  I need to do this in SQL Server 2008 and I don't believe there is good regex support in that version.  How can I match using a like statement?

答:
I don't think you can with the like operator.  You could exclude ones you could match, like if you want to make sure it just doesn't contain other:

```<code>[field] LIKE '%value":%"123456"%` AND [field] NOT LIKE '%"other"%'
</code>```

Otherwise I think you'd have to do some processing on the string.  You could write a UDF to take the string and parse it to find the value for 'value' and compare based on that:

```<code>dbo.fn_GetValue([field], 'value') = '123456'
</code>```

The function could find the index of '"' + @name + '"', find the next index of a quote, and the one after that, then get the string between those two quotes and return it.

Body:
I don't think you can with the like operator.  You could exclude ones you could match, like if you want to make sure it just doesn't contain other:

[field] LIKE '%value":%"123456"%` AND [field] NOT LIKE '%"other"%'

Otherwise I think you'd have to do some processing on the string.  You could write a UDF to take the string and parse it to find the value for 'value' and compare based on that:

dbo.fn_GetValue([field], 'value') = '123456'

The function could find the index of '"' + @name + '"', find the next index of a quote, and the one after that, then get the string between those two quotes and return it.


问:
Is print in Haskell a pure function?
Is print in Haskell a pure function; why or why not? I'm thinking it's not, because it does not always return the same value as pure functions should.

答: Yes, print is a pure function.  The value it returns has type IO (), which you can think of as a bunch of code that outputs the string you passed in.  For each string you pass in, it always returns the same code.

Title: Is print in Haskell a pure function?


问:
Is Conger's kappa available in Stata?
Is the modified version of kappa proposed by Conger (1980) available in Stata?  Tried to google it to no avail.</p>

答: This is an old question, but in case anyone is still looking--the SSC package kappaetc now calculates that, along with every other inter-rater statistic you could ever want.

Title: Is Conger's kappa available in Stata?


问:
Meteor - Excel File Upload without storing file on db
I would like the user to be able to upload a file through a file input and the client would send the file to the server and the server would parse the file without storing it in the database, is this possible?

Something like this:

```<code>    'change input': function(e, t) {
        let file = e.target.files[0];
        let extension = file.name.split(".").pop();
        if (['xlsb', 'xls', 'xlsx'].indexOf(extension) < 0) {
          Notify.show("error", `Invalid file extension`);
          return false;
        } else {
          Meteor.call("upload.factual.achievements", file, function(err, res){
            if(err){
              Notify.show("error", `There was an error : ${error.reason}.`);
            } else {
...
            }
          });

        }
      }
</code>```

答:
Strongly recommend using a package like ostrio:files https://files.veliov.com/

This will store your files to the filesystem by default and retain a pointer to the location in a Collection that you can query to return the image from the filesystem later

Body:
I would like the user to be able to upload a file through a file input and the client would send the file to the server and the server would parse the file without storing it in the database, is this possible?

Something like this:

    'change input': function(e, t) {
        let file = e.target.files[0];
        let extension = file.name.split(".").pop();
        if (['xlsb', 'xls', 'xlsx'].indexOf(extension) < 0) {
          Notify.show("error", `Invalid file extension`);
          return false;
        } else {
          Meteor.call("upload.factual.achievements", file, function(err, res){
            if(err){
              Notify.show("error", `There was an error : ${error.reason}.`);
            } else {
...
            }
          });

        }
      }


问:
Script to execute chmod continuously
I am working on Solaris servers. I am using an ADMIN user which has all the accesses while other colleagues are using a different user with limited access.
When others want to access the logs I have to manually give chmod 755 on the log folders and when a new file is generated I have to do chmod again.

Is there a way to write a script to run chmod continuously every 2 mins on some folders?

答:
You could consider setting the GUID bit on the containing directory, and setting the group ownership of the directory to a group that these other folks belong to.

That way, any files created in the directory will automatically and always inherit the group of the directory rather than that of the user creating them.

So, in concrete terms, if your log files are in /var/log/somewhere, you would do:

```<code>chmod g+s /var/log/somewhere
chgrp OTHERADMINSGROUP /var/log/somewhere
</code>```

Now test, by creating a file and looking at its group:

```<code>touch /var/log/somewhere/aFile
ls -l /var/log/somewhere/aFile
</code>```

You should see that the file belongs to OTHERADMINSGROUP rather than your own group.

Title: Script to execute chmod continuously

Body:
You could consider setting the GUID bit on the containing directory, and setting the group ownership of the directory to a group that these other folks belong to.

That way, any files created in the directory will automatically and always inherit the group of the directory rather than that of the user creating them.

So, in concrete terms, if your log files are in /var/log/somewhere, you would do:

chmod g+s /var/log/somewhere
chgrp OTHERADMINSGROUP /var/log/somewhere

Now test, by creating a file and looking at its group:

touch /var/log/somewhere/aFile
ls -l /var/log/somewhere/aFile

You should see that the file belongs to OTHERADMINSGROUP rather than your own group.


问:
For Each loop ending early and I can't figure out why
I am looking for some help regarding my For Each loop in Excel VBA.

```<code>Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!"))

For Each SingleCell In ListofCells

   If ActiveCell.Value = "!!End Measures!!" Then
        ActiveCell.Offset(1, 0).Select
        Exit For
    ElseIf ActiveCell.Value = "" Then
        ActiveCell.EntireRow.Delete
    End If
Next SingleCell
</code>```

For some reason this likes to exit the loop early for, as far as I can tell, absolutely no reason.  In my spreadsheet I'm looking to delete any unused rows from the ActiveCell down to where the entry-area ends, which I have denoted as "!!End Measures!!".  I have also tried:

```<code>Set ListofCells = Range(ActiveCell, ActiveCell.End(xlDown))
</code>```

and it as the same behavior.  Ending the loops many rows earlier than expected.

If I put 4 of these loops in a row then it works as intended....but I'm hoping to find out why this might be exiting early instead of having to do something weird like looping this 4 or 5 times.

Any help is greatly appreciated and if I can answer any questions or provide any more information I'd be happy to.

答:
If you are just trying to delete all the rows from the ActiveCell down to the row containing "!!End Measures!!", you can replace your existing code with the one line:

```<code>Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!").Offset(-1, 0)).EntireRow.Delete
</code>```

A slightly more robust version (which isn't dependent on ActiveCell, but simply deletes all rows between the "!!End Measures!!" and the previous non-blank cell) would be:

```<code>Dim EndMeasures As Range
Dim LastMeasure As Range
Set EndMeasures = Columns(3).Find("!!End Measures!!")
'Check that there are blank rows before deleting
If IsEmpty(EndMeasures.Offset(-1).Value) Then
    Set LastMeasure = EndMeasures.End(xlUp)
    Range(LastMeasure.Offset(1), EndMeasures.Offset(-1)).EntireRow.Delete
End If
</code>```

Body:
I am looking for some help regarding my For Each loop in Excel VBA.

Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!"))

For Each SingleCell In ListofCells

   If ActiveCell.Value = "!!End Measures!!" Then
        ActiveCell.Offset(1, 0).Select
        Exit For
    ElseIf ActiveCell.Value = "" Then
        ActiveCell.EntireRow.Delete
    End If
Next SingleCell

For some reason this likes to exit the loop early for, as far as I can tell, absolutely no reason.  In my spreadsheet I'm looking to delete any unused rows from the ActiveCell down to where the entry-area ends, which I have denoted as "!!End Measures!!".  I have also tried:

Set ListofCells = Range(ActiveCell, ActiveCell.End(xlDown))

and it as the same behavior.  Ending the loops many rows earlier than expected.

If I put 4 of these loops in a row then it works as intended....but I'm hoping to find out why this might be exiting early instead of having to do something weird like looping this 4 or 5 times.

Any help is greatly appreciated and if I can answer any questions or provide any more information I'd be happy to.

Body:
If you are just trying to delete all the rows from the ActiveCell down to the row containing "!!End Measures!!", you can replace your existing code with the one line:

Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!").Offset(-1, 0)).EntireRow.Delete

A slightly more robust version (which isn't dependent on ActiveCell, but simply deletes all rows between the "!!End Measures!!" and the previous non-blank cell) would be:

Dim EndMeasures As Range
Dim LastMeasure As Range
Set EndMeasures = Columns(3).Find("!!End Measures!!")
'Check that there are blank rows before deleting
If IsEmpty(EndMeasures.Offset(-1).Value) Then
    Set LastMeasure = EndMeasures.End(xlUp)
    Range(LastMeasure.Offset(1), EndMeasures.Offset(-1)).EntireRow.Delete
End If


问:
Python jsonpickle error: 'OrderedDict' object has no attribute '_OrderedDict__root'
I'm hitting this exception with jsonpickle, when trying to pickle a rather complex object that unfortunately I'm not sure how to describe here. I know that makes it tough to say much, but for what it's worth:

```<code>>>> frozen = jsonpickle.encode(my_complex_object_instance)
>>> thawed = jsonpickle.decode(frozen)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/jsonpickle/__init__.py",
  line 152, in decode
    return unpickler.decode(string, backend=backend, keys=keys)
      :
      :
  File "/Library/Python/2.7/site-packages/jsonpickle/unpickler.py",
  line 336, in _restore_from_dict
    instance[k] = value
  File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/packages/ordered_dict.py",
  line 49, in __setitem__
    root = self.__root
AttributeError: 'OrderedDict' object has no attribute '_OrderedDict__root'
</code>```

I don't find much of assistance when googling the error. I do see what looks like the same issue was resolved at some time past for simpler objects:

https://github.com/jsonpickle/jsonpickle/issues/33

The cited example in that report works for me:

```<code>>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict()))
OrderedDict()
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict(a=1)))
OrderedDict([(u'a', 1)])
</code>```

Has anyone ever run into this themselves and found a solution? I ask with the understanding that my case may be "differently idiosynchratic" than another known example.

答:
The requests module for me seems to be running into problems when I .decode(). After looking at the jsonpickle code a bit, I decided to fork it and change the following lines to see what was going on (and I ended up keeping a private copy of jsonpickle with the changes so I can move forward).

In jsonpickle/unpickler.py (in my version it's line 368), search for the if statement section in the method _restore_from_dict():

```<code>if (util.is_noncomplex(instance) or
    util.is_dictionary_subclass(instance)):
    instance[k] = value
else:
    setattr(instance, k, value)
</code>```

and change it to this (it will logERROR the ones that are failing and then you can either keep the code in place or change your OrderedDict's version that have __root)

```<code>if (util.is_noncomplex(instance) or
    util.is_dictionary_subclass(instance)):
    # Currently requests.adapters.HTTPAdapter is using a non-standard
    # version of OrderedDict which doesn't have a _OrderedDict__root
    # attribute
    try:
        instance[k] = value
    except AttributeError as e:
        import logging
        import pprint
        warnmsg = 'Unable to unpickle {}[{}]={}'.format(pprint.pformat(instance), pprint.pformat(k), pprint.pformat(value))
        logging.error(warnmsg)
else:
    setattr(instance, k, value)
</code>```

Body:
I'm hitting this exception with jsonpickle, when trying to pickle a rather complex object that unfortunately I'm not sure how to describe here. I know that makes it tough to say much, but for what it's worth:

>>> frozen = jsonpickle.encode(my_complex_object_instance)
>>> thawed = jsonpickle.decode(frozen)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/jsonpickle/__init__.py",
  line 152, in decode
    return unpickler.decode(string, backend=backend, keys=keys)
      :
      :
  File "/Library/Python/2.7/site-packages/jsonpickle/unpickler.py",
  line 336, in _restore_from_dict
    instance[k] = value
  File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/packages/ordered_dict.py",
  line 49, in __setitem__
    root = self.__root
AttributeError: 'OrderedDict' object has no attribute '_OrderedDict__root'

I don't find much of assistance when googling the error. I do see what looks like the same issue was resolved at some time past for simpler objects:

https://github.com/jsonpickle/jsonpickle/issues/33

The cited example in that report works for me:

>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict()))
OrderedDict()
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict(a=1)))
OrderedDict([(u'a', 1)])

Has anyone ever run into this themselves and found a solution? I ask with the understanding that my case may be "differently idiosynchratic" than another known example.

Body:
The requests module for me seems to be running into problems when I .decode(). After looking at the jsonpickle code a bit, I decided to fork it and change the following lines to see what was going on (and I ended up keeping a private copy of jsonpickle with the changes so I can move forward).

In jsonpickle/unpickler.py (in my version it's line 368), search for the if statement section in the method _restore_from_dict():

if (util.is_noncomplex(instance) or
    util.is_dictionary_subclass(instance)):
    instance[k] = value
else:
    setattr(instance, k, value)

and change it to this (it will logERROR the ones that are failing and then you can either keep the code in place or change your OrderedDict's version that have __root)

if (util.is_noncomplex(instance) or
    util.is_dictionary_subclass(instance)):
    # Currently requests.adapters.HTTPAdapter is using a non-standard
    # version of OrderedDict which doesn't have a _OrderedDict__root
    # attribute
    try:
        instance[k] = value
    except AttributeError as e:
        import logging
        import pprint
        warnmsg = 'Unable to unpickle {}[{}]={}'.format(pprint.pformat(instance), pprint.pformat(k), pprint.pformat(value))
        logging.error(warnmsg)
else:
    setattr(instance, k, value)


问:
pause viewmodel process for user input
I've been looking at a view examples of the typical "raise dialog from viewmodel" problem, noting 3 main solutions:

use attached behaviors

use a mediator pattern

use a service

I'm getting a bit bogged down though and struggling to find a solution that easily fits into my problem space - which is a very simple file copy problem:

My viewmodel is processing a loop (copying a list of files)

When a file already exists at the destination I need to raise a modal dialog to get confirmation to replace

The vm needs to wait for and receive confirmation before continuing

The "modal dialog" is actually not a new window but a hidden overlay in my MainWindow, as per http://www.codeproject.com/KB/WPF/wpfmodaldialog.aspx (thanks Ronald!)

I'm mostly there but the biggest struggles I have are:
- how to pause the loop in the viewmodel while it waits for input
- how to get input back to the viewmodel within the loop so it can carry on

So far I'm leaning towards the service solution because it seems a direct method call with a return that the vm must wait for. However, it does mean the service needs to tie directly to the view in order to make an element visible?

If anyone can post some simple code that deals directly with this problem I (and the net) would be very happy! Thanks!

答:
For example, you have a service called IDialogService with the following interface:

```<code>public interface IDialogService
{
   bool ConfirmAction(string title, string confirmationText);
}
</code>```

As you mentioned, in order for the service to be able to show the actual dialog it needs to have a reference to the view that will show the actual overlay element. But instead of directly referencing the view I prefer to reference it via an interface. Lets call it ICanShowDialog and it will have the following members:

```<code>public interface ICanShowDialog
{
   void ShowDialog(object dialogContent);
   void HideDialog();
}
</code>```

This interface will be implemented by your view that owns the dialog overlay (e.g. your main window).

Now the interesting part: suspending the code execution while the dialog is shown. First of all, I would recommend you not to use overlay elements but use usual windows if possible. Then you will not have that problem. You can style the dialog window so it will look just like the overlay element.
Anyway, if you still want to use overlay elements then you can do the following trick to suspend the code execution:

Here is pseudo code of the ConfirmAction method of the IDialogService inteface:

```<code>public bool ConfirmAction(string title, string confirmationText)
{
   ConfirmationDialogView dialogView = new ConfirmationDialogView(title, confirmationText);

   DialogShower.ShowDialog(dialogView); // DialogShower is of type ICanShowDialog

   while (!dialogView.ResultAvailable)
   {
      DispatcherUtils.DoEvents();
   }

   DialogShower.HideDialog();

   return dialogView.Result;
}
</code>```

Here is the code of DispatcherUtils.DoEvents() (that was taken from here: http://dedjo.blogspot.com/2007/08/how-to-doevents-in-wpf.html):

```<code>public static class DispatcherUtils
{
   public static void DoEvents()
   {
      DispatcherFrame f = new DispatcherFrame();
      Dispatcher.CurrentDispatcher.BeginInvoke(
         DispatcherPriority.Background,
         (SendOrPostCallback)delegate(object arg) {
             DispatcherFrame fr =  arg as DispatcherFrame;
             fr.Continue=True;
         }, f);
      Dispatcher.PushFrame(frame);
   }
}
</code>```

But I must warn you. Using DoEvents can result in some subtle bugs caused by inner dispatcher loops.

As an alternative to suspending the code execution while a dialog is shown you can use callbacks:

```<code>public interface IDialogService
{
   void ConfirmAction(string title, string confirmationText, Action<bool> dialogResultCallback);
}
</code>```

But it will not be so convenient to use.

Title: pause viewmodel process for user input

Body:
For example, you have a service called IDialogService with the following interface:

public interface IDialogService
{
   bool ConfirmAction(string title, string confirmationText);
}

As you mentioned, in order for the service to be able to show the actual dialog it needs to have a reference to the view that will show the actual overlay element. But instead of directly referencing the view I prefer to reference it via an interface. Lets call it ICanShowDialog and it will have the following members:

public interface ICanShowDialog
{
   void ShowDialog(object dialogContent);
   void HideDialog();
}

This interface will be implemented by your view that owns the dialog overlay (e.g. your main window).

Now the interesting part: suspending the code execution while the dialog is shown. First of all, I would recommend you not to use overlay elements but use usual windows if possible. Then you will not have that problem. You can style the dialog window so it will look just like the overlay element.
Anyway, if you still want to use overlay elements then you can do the following trick to suspend the code execution:

Here is pseudo code of the ConfirmAction method of the IDialogService inteface:

public bool ConfirmAction(string title, string confirmationText)
{
   ConfirmationDialogView dialogView = new ConfirmationDialogView(title, confirmationText);

   DialogShower.ShowDialog(dialogView); // DialogShower is of type ICanShowDialog

   while (!dialogView.ResultAvailable)
   {
      DispatcherUtils.DoEvents();
   }

   DialogShower.HideDialog();

   return dialogView.Result;
}

Here is the code of DispatcherUtils.DoEvents() (that was taken from here: http://dedjo.blogspot.com/2007/08/how-to-doevents-in-wpf.html):

public static class DispatcherUtils
{
   public static void DoEvents()
   {
      DispatcherFrame f = new DispatcherFrame();
      Dispatcher.CurrentDispatcher.BeginInvoke(
         DispatcherPriority.Background,
         (SendOrPostCallback)delegate(object arg) {
             DispatcherFrame fr =  arg as DispatcherFrame;
             fr.Continue=True;
         }, f);
      Dispatcher.PushFrame(frame);
   }
}

But I must warn you. Using DoEvents can result in some subtle bugs caused by inner dispatcher loops.

As an alternative to suspending the code execution while a dialog is shown you can use callbacks:

public interface IDialogService
{
   void ConfirmAction(string title, string confirmationText, Action<bool> dialogResultCallback);
}

But it will not be so convenient to use.


答:
Remove the whitespace in your compare with REPLACE():

```<code>WHERE REPLACE(column,' ','') LIKE '%"value":"123456"%'
</code>```

May need a double replace for tabs:

```<code>REPLACE(REPLACE(column,' ',''),'    ','')
</code>```

Title: Match Character Whether or Not It Exists in Like Statement

Body:
I need a like expression that will match a character whether or not it exists.  It needs to match the following values:

..."value": "123456"...

..."value":  "123456"...

"...value":"123456"...

This like statement will almost work: LIKE '%value":%"123456"%'

But there are values like this one that would also match, but I don't want returned:

..."value":"99999", "other":"123456"...

A regex expression to do what I'm looking to do is 'value": *?"123456"'.  I need to do this in SQL Server 2008 and I don't believe there is good regex support in that version.  How can I match using a like statement?

Body:
Remove the whitespace in your compare with REPLACE():

WHERE REPLACE(column,' ','') LIKE '%"value":"123456"%'

May need a double replace for tabs:

REPLACE(REPLACE(column,' ',''),'    ','')


问:
App development
I'm in a situation where I'm looking at building a company website and in-house app (for ipad/android) with basic functionality; pretty much just a portfolio. This is for the company I work for who (for many reasons, some of which I agree with, some I don't) don't particularly want to outsource this.

I've got a fairly basic knowledge of webdesign and would be able to put together a fairly decent website on my own however the app is what is causing me a slight headache as I'm not an expert at coding by any means. So my questions are:

1) Is it possible to build an app that isn't hosted on the app store? We have no requirement for people outside of the practice to have access to the app, so it'd only need to be an internal build. How (given that ios is so locked down) would I go about installing an app such as this, if I built one?

2) I've seen myriad app-building websites, some of which output code for both android and ios, others that (apparently) wrap them as some kind of hybrid so they run on either (though my understanding is that these may be refused by the app store?) and others that are just html5. Do you have any recommendations or experience of any of these sites?

3) I don't mind purchasing software to help get the job done. I'm in the process of mocking up a prototype in Adobe XD; but after that I'm fairly at a loss.

Any help would be much appreciated.

Kind regards,

Chris.

答:
Glad you're getting started in XD! That's always a great way to prototype!

App development requires knowledge of languages like Swift, C#, Objective-C, C++.
 However since you are familiar with basic web languages (html, css, js) I would recommend looking into Nativescript(https://www.nativescript.org/).

It's a platform that allows you to build an actual native app using web languages. Read the docs (https://docs.nativescript.org/), watch some tutorial videos(https://courses.nativescripting.com/courses/nativescript-with-angular-getting-started-guide/lectures/2692194), and you'll be up shortly. It uses xml but you'll catch on pretty quick if you haven't used it yet.

Best of luck m8

Cheers!

Title: App development


问:
How to test componentWillReceiveProps method in react component
I want to test the componentWillReceiveProps method and see the path for current web page. I tried to use the following code to test the method, but it always throw an error.

```<code>Invariant Violation: A <Router> may have only one child element
</code>```

I'm wondering what I should do to solve that error? Here is what I have tried so far.

```<code>class WrappedComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (!nextProps.user_id) {
      this.props.history.replace('/login');
    }
  }

  render() {
    return <div>WrappedComponent</div>
  }
}

describe('AuthenticationHOC', () => {
  describe('authenticationRequired', () => {
    let props;
    const shallowWrapper = () => {
      return shallow(
        <MemoryRouter>
          withRouter(authenticationRequired(<WrappedComponent {...props} />))
        </MemoryRouter>
      )
    }

    it('renders the wrapped component', () => {
      let wrapper = shallowWrapper()
      expect(wrapper.contains(<WrappedComponent {...props} />)).toBe(true)
    })

    describe("when user_id doesn't exist", () => {
      beforeEach(() => {
        props = {
          user_id: ''
        }
      });
      it('should go to the login page', () => {
        //how to test the method componentWillReceiveProps
        let wrapper = shallowWrapper().dive();
        wrapper.setProps({
          user_id: '12312412'
        });
      //  expect(spy.calledOnce).toBe(true);
        expect(window.href).toBe("/login");
      })
    })

    describe("when user_id do exist", () => {
      beforeEach(() => {
        props = {
          user_id: 'something'
        }
      });
      it('should not go to other page', () => {
        let wrapper = shallowWrapper();
        expect(window.href).toBe("/");
      })
    })
  })
</code>```

答:
You shouldn't mock componentWillReceiveProps as this is an implemntation detail that we don't care about.

Instead you will need to mock out history somehow (not sure, look at react-router docs maybe) or hopefully you can just check the current href as hopefully when you use history.replace it might just change the href immediately.

Use enzymes dive() to dive through your Higher order components and use setProps on the wrapper component.

You might need to chain dive() again depending on how many HOC's you have wrapped.

```<code>// TODO add tests that verify history.replace was called
describe("when user_id doesn't exist", () => {
  beforeEach(() => {
    props.user_id = ''
  });

  const wrapper = shallowWrapper().dive();
  const user_id = 'testId';

  wrapper.setProps({ user_id });

  expect(window.href).toBe('/login');
})
</code>```

Body:
I want to test the componentWillReceiveProps method and see the path for current web page. I tried to use the following code to test the method, but it always throw an error.

Invariant Violation: A <Router> may have only one child element

I'm wondering what I should do to solve that error? Here is what I have tried so far.

class WrappedComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (!nextProps.user_id) {
      this.props.history.replace('/login');
    }
  }

  render() {
    return
WrappedComponent

  }
}

describe('AuthenticationHOC', () => {
  describe('authenticationRequired', () => {
    let props;
    const shallowWrapper = () => {
      return shallow(
        <MemoryRouter>
          withRouter(authenticationRequired(<WrappedComponent {...props} />))
        </MemoryRouter>
      )
    }

    it('renders the wrapped component', () => {
      let wrapper = shallowWrapper()
      expect(wrapper.contains(<WrappedComponent {...props} />)).toBe(true)
    })

    describe("when user_id doesn't exist", () => {
      beforeEach(() => {
        props = {
          user_id: ''
        }
      });
      it('should go to the login page', () => {
        //how to test the method componentWillReceiveProps
        let wrapper = shallowWrapper().dive();
        wrapper.setProps({
          user_id: '12312412'
        });
      //  expect(spy.calledOnce).toBe(true);
        expect(window.href).toBe("/login");
      })
    })

    describe("when user_id do exist", () => {
      beforeEach(() => {
        props = {
          user_id: 'something'
        }
      });
      it('should not go to other page', () => {
        let wrapper = shallowWrapper();
        expect(window.href).toBe("/");
      })
    })
  })

Body:
You shouldn't mock componentWillReceiveProps as this is an implemntation detail that we don't care about.

Instead you will need to mock out history somehow (not sure, look at react-router docs maybe) or hopefully you can just check the current href as hopefully when you use history.replace it might just change the href immediately.

Use enzymes dive() to dive through your Higher order components and use setProps on the wrapper component.

You might need to chain dive() again depending on how many HOC's you have wrapped.

// TODO add tests that verify history.replace was called
describe("when user_id doesn't exist", () => {
  beforeEach(() => {
    props.user_id = ''
  });

  const wrapper = shallowWrapper().dive();
  const user_id = 'testId';

  wrapper.setProps({ user_id });

  expect(window.href).toBe('/login');
})


问:
Removing uneeded dictionary variables when using the Start 2010 workflow Action
I have a 2013 workflow that starts a number of 2010 workflows.  I am converting these over to the new HTTP calls, but I'm running into a problem.  It seems when you use the "Start 2010 Workflow" it creates a dictionary variable for that action.  I need to know if there is a way to delete those unneeded dictionary variables.  They are not in the local variable list so I cannot delete that way.  I need to delete them as they are pushing my variable count over 50 and I cannot publish the workflow.</p>

答: So Microsoft in its great wisdom decided that they were not going to give the user a way to delete the variables that are created when you use the "Start 2010 Workflow".  I have to say, they are geniuses at Microsoft to not give the user a way to delete variables that are no longer needed.  Here is a round about way of doing though if you need to do it.  Scroll down and the answer will be there.  https://social.msdn.microsoft.com/Forums/Lync/en-US/e9d7b2ba-593d-4524-93ee-a76a579fc6ff/deleting-coordination-action-output-variables-in-spd-2013?forum=sharepointcustomization</p>


问:
CMake: How to add a custom command that is only executed for one configuration?
I want to add a cmake custom command that is only executed when the custom target is build in the Debug configuration while using the Visual Studio multi-config generator. Is there a clean way to do this?

In order to implement this, I first tried wrapping the whole command list in a generator expression like this.

```<code>add_custom_command(
    ...
    COMMAND $<$<CONFIG:Debug>:cmake;-E;echo;foo>
)
</code>```

But this gives me a syntax error when the command is executed. After some trial-and-error I got the following hacky solution to work. This wraps each word of the command list in a generator expression like this.

```<code>add_custom_command(
    ...
    COMMAND $<IF:$<CONFIG:Debug>,cmake,echo>;$<IF:$<CONFIG:Debug>,-E, >;$<IF:$<CONFIG:Debug>,echo, >;$<IF:$<CONFIG:Debug>,foo, >
)
</code>```

This executes the cmake -E echo foo command when compiling the Debug configuration and the dummy command echo " " " " " " for all other configurations.

This is quite ugly and the dummy command must be changed depending on the host system. On Linux it could be ":" ":" ":" ":". So Is there a cleaner way to do this?

Thank you for your time!

答:
Here is my piece of code (tested on several single- and multi-configuration platforms):

CMakeLists.txt

cmake_minimum_required(VERSION 3.8)

project(DebugEchoFoo NONE)

string(
    APPEND _cmd
    "$<IF:$<CONFIG:Debug>,"
        "${CMAKE_COMMAND};-E;echo;foo,"
        "${CMAKE_COMMAND};-E;echo_append"
    ">"
)

add_custom_target(
    ${PROJECT_NAME}
    ALL
    COMMAND "${_cmd}"
    COMMAND_EXPAND_LISTS
)
```

Note: COMMAND_EXPAND_LISTS is keyword is only available with CMake version >= 3.8

Reference

Modern way to set compiler flags in cross-platform cmake project

Body:
I want to add a cmake custom command that is only executed when the custom target is build in the Debug configuration while using the Visual Studio multi-config generator. Is there a clean way to do this?

In order to implement this, I first tried wrapping the whole command list in a generator expression like this.

add_custom_command(
    ...
    COMMAND $<$<CONFIG:Debug>:cmake;-E;echo;foo>
)

But this gives me a syntax error when the command is executed. After some trial-and-error I got the following hacky solution to work. This wraps each word of the command list in a generator expression like this.

add_custom_command(
    ...
    COMMAND $<IF:$<CONFIG:Debug>,cmake,echo>;$<IF:$<CONFIG:Debug>,-E, >;$<IF:$<CONFIG:Debug>,echo, >;$<IF:$<CONFIG:Debug>,foo, >
)

This executes the cmake -E echo foo command when compiling the Debug configuration and the dummy command echo " " " " " " for all other configurations.

This is quite ugly and the dummy command must be changed depending on the host system. On Linux it could be ":" ":" ":" ":". So Is there a cleaner way to do this?

Thank you for your time!

Body:
Here is my piece of code (tested on several single- and multi-configuration platforms):

CMakeLists.txt

cmake_minimum_required(VERSION 3.8)

project(DebugEchoFoo NONE)

string(
    APPEND _cmd
    "$<IF:$<CONFIG:Debug>,"
        "${CMAKE_COMMAND};-E;echo;foo,"
        "${CMAKE_COMMAND};-E;echo_append"
    ">"
)

add_custom_target(
    ${PROJECT_NAME}
    ALL
    COMMAND "${_cmd}"
    COMMAND_EXPAND_LISTS
)

Note: COMMAND_EXPAND_LISTS is keyword is only available with CMake version >= 3.8

Reference

Modern way to set compiler flags in cross-platform cmake project


问:
Converting CIDR IP address ranges using ipaddress and output to a data frame
I have a dataframe with IPv4 and IPv6 CIDR IP address ranges (these can be split up if necessary) in a data frame. I am hoping to take those ranges and create a data frame with each address in the range, so I can join that with another data frame to do some filtering.

Using the ipaddress package, the function to expand a list is:

```<code>a = ip.ip_network('103.21.244.0/22')
    for x in a.hosts():
    print(x)
</code>```

This yields a list for just this IP range. Does anyone know how to put in a series of CIDR ranges so I don't have to perform the above n times? If I put a reference to the data frame in place of the IP address above, I get a ValueError stating that it doesn't appear to be an IPv4 or IPv6 network.

The secondary question, as a Python newbie, what do I need to do to get these expanded ranges into a list or data frame? I tried this:

```<code>a = ip.ip_network('103.21.244.0/22')
ip_list = [] #x for x in a.hosts()
for x in a.hosts():
    ip_list.append(x)
ip_list
</code>```

And ended up with:

```<code>[IPv4Address('103.21.244.1'),
 IPv4Address('103.21.244.2'),
 IPv4Address('103.21.244.3'),
 IPv4Address('103.21.244.4'),
 IPv4Address('103.21.244.5'),
 ...]
</code>```

I'm sure there is a better way than taking that output and regexing the IP addresses.

答:
```<code>a = ip.ip_network('103.21.244.0/22')
ip_list = [] #x for x in a.hosts()
for x in a.hosts():
    ip_list.append(x.compressed) #
ip_list
</code>```

Body:
I have a dataframe with IPv4 and IPv6 CIDR IP address ranges (these can be split up if necessary) in a data frame. I am hoping to take those ranges and create a data frame with each address in the range, so I can join that with another data frame to do some filtering.

Using the ipaddress package, the function to expand a list is:

a = ip.ip_network('103.21.244.0/22')
    for x in a.hosts():
    print(x)

This yields a list for just this IP range. Does anyone know how to put in a series of CIDR ranges so I don't have to perform the above n times? If I put a reference to the data frame in place of the IP address above, I get a ValueError stating that it doesn't appear to be an IPv4 or IPv6 network.

The secondary question, as a Python newbie, what do I need to do to get these expanded ranges into a list or data frame? I tried this:

a = ip.ip_network('103.21.244.0/22')
ip_list = [] #x for x in a.hosts()
for x in a.hosts():
    ip_list.append(x)
ip_list

And ended up with:

[IPv4Address('103.21.244.1'),
 IPv4Address('103.21.244.2'),
 IPv4Address('103.21.244.3'),
 IPv4Address('103.21.244.4'),
 IPv4Address('103.21.244.5'),
 ...]

I'm sure there is a better way than taking that output and regexing the IP addresses.