问:
How to count emails in subfolders of a shared mailbox?
I want to count the number of emails in seven subfolders of a shared mailbox.

I also want the date of the last email in these folders.

The shared mailbox looks like

```<code>>"Shared Mailbox Name"
>>Inbox
>>>Folder one
>>>>A
>>>>B
>>>>C
>>>Folder two
>>>>D
>>>>E
>>>>F
>>>>G
</code>```

I want the result to show number of emails of all these folders together and not one by one. A, B, C, D, E, F, G.

I managed to get the number of emails for one folder at a time.

```<code>
Type TmyCount
    item As Date
    count As Integer
End Type

Sub Steuerung()

    Dim objNS As Outlook.NameSpace
    Dim objFolder As Outlook.MAPIFolder
    Set objNS = GetNamespace("MAPI")
   Set objFolder = objNS.Folders("shared mailbox name") 'folders of your current account

    'Creates a new Excel workbook
    Dim oXL As Object
    Set oXL = CreateObject("Excel.Application")
    Set oWB = oXL.Workbooks.Add
    oWB.sheets(1).Cells(2, 1).Value = "Date/Day"

    'Creates a list to which folders to be counted can be appended
    Dim colList As Collection
    Set colList = New Collection

    Set objFolder = objFolder.Folders("Inbox")
    Set objFolder = objFolder.Folders("Folder one")
    Set objFolder = objFolder.Folders("A")
    'Set objFolder = objFolder.Folders("B")

    'Adds all subfolders of 'Inbound chargeback processing' to the list
    Dim subF As Outlook.MAPIFolder
    For Each subF In objFolder.Folders
        colList.Add subF
    Next subF

     'SampleCode to add new folders to the edit list
     Set objFolder = objNS.Folders("shared mailbox name") ' folders of your current account
     Set objFolder = objFolder.Folders("Inbox")
     Set objFolder = objFolder.Folders("A")
     'Set objFolder = objFolder.Folders("B")
     colList.Add objFolder

    '-----------------------------------------------------------------------------------------------------------------
    'Please enter folders to be processed above this line

    'Iterates over the folder list and counts all mails and enters the values in the Excel workbook
    Dim k As Integer
    For k = 1 To colList.count
        Call Arrayfüllen(colList.item(k), k)
    Next k

    oWB.sheets(1).Cells(2, 2 * k).Value = "ReklaSumme"
    oWB.sheets(1).Cells(2, 2 * k + 1).Value = "ScanSumme"

    Dim n As Integer
    n = 3

    Dim countRekla As Integer

    Dim countScan As Integer

    While oWB.sheets(1).Cells(n, 1) <> ""
        countScan = 0
        countRekla = 0

        For m = 2 To 2 * k - 2

            If m Mod 2 = 1 Then

                countScan = countScan + oWB.sheets(1).Cells(n, m).Value

            Else

                countRekla = countRekla + oWB.sheets(1).Cells(n, m).Value

            End If

        Next m

        oWB.sheets(1).Cells(n, 2 * k).Value = CStr(countRekla)
        oWB.sheets(1).Cells(n, 2 * k + 1).Value = CStr(countScan)

        n = n + 1
    Wend

    'Makes the Excel workbooks visible
    oXL.Visible = True

End Sub

Sub Arrayfüllen(objFolder As Outlook.MAPIFolder, position As Integer)
    'Fills the objFolder folder's messages into two different arrays depending on the sender

    Dim Message As Object

    Dim arraysizeRekla As Integer
    arraysizeRekla = 0
    Dim arraysizeScan As Integer
    arraysizeScan = 0

    Dim msgInhaltRekla() As String
    Dim msgInhaltScan() As String

    For Each Message In objFolder.Items
        'Iterates over all items in the folder
        If Message.Class = 43 Then
            'If the message is from then
            If Message.SenderName = "Jonas, Adamski" Then
                'If it is a sender, fill the date in the msgContentScan array
                ReDim Preserve msgInhaltScan(arraysizeScan)
                msgInhaltScan(arraysizeScan) = Format(Message.ReceivedTime, "dd.mm.yyyy")
                arraysizeScan = arraysizeScan + 1

            Else
                'Otherwise, fill the date in the msgContentRekla array
                ReDim Preserve msgInhaltRekla(arraysizeRekla)
                msgInhaltRekla(arraysizeRekla) = Format(Message.ReceivedTime, "dd.mm.yyyy")
                arraysizeRekla = arraysizeRekla + 1

            End If

        Else
            'Falls es sich um ein Terminobjekt etc. handelt
        End If
    Next

    Dim reklaErgebnis() As TmyCount
    reklaErgebnis = ArrayVerarbeiten(msgInhaltRekla)
    'reklaEregbnis is filled with the aggregated result from msg InhaltRekla
    Dim scanErgebnis() As TmyCount
    scanErgebnis = ArrayVerarbeiten(msgInhaltScan)
    'scanResult is filled with the aggregated result from msgContentScan

    'Creates the heading in the Excel document
    oWB.sheets(1).Cells(1, 2 * position).Value = objFolder.Name
    oWB.sheets(1).Cells(2, 2 * position).Value = "Rekla"
    oWB.sheets(1).Cells(2, 2 * position + 1).Value = "Scan"

    Dim j As Integer

    If IsArrayEmpty(reklaErgebnis) = False Then
        'If array reklaResult is not empty

        For i = 0 To UBound(reklaErgebnis)
            'Go through the whole array

            j = 3
            While oWB.sheets(1).Cells(j, 1).Value <> reklaErgebnis(i).item And oWB.sheets(1).Cells(j, 1).Value <> vbNullString
                'Find suitable date or navigate to the end
                j = j + 1
            Wend

            If oWB.sheets(1).Cells(j, 1).Value <> reklaErgebnis(i).item Then
                'Empty line at the end
                oWB.sheets(1).Cells(j, 1).Value = reklaErgebnis(i).item
                oWB.sheets(1).Cells(j, 2 * position).Value = reklaErgebnis(i).count

            Else
                'Date line found
                oWB.sheets(1).Cells(j, 2 * position).Value = reklaErgebnis(i).count
            End If

        Next

    End If

    If IsArrayEmpty(scanErgebnis) = False Then
        'If Array scanResult is not empty

        For i = 0 To UBound(scanErgebnis)

            j = 3
            While oWB.sheets(1).Cells(j, 1).Value <> scanErgebnis(i).item And oWB.sheets(1).Cells(j, 1).Value <> vbNullString
                'Find suitable date or navigate to the end
                j = j + 1
            Wend

            If oWB.sheets(1).Cells(j, 1).Value <> scanErgebnis(i).item Then
                'Empty line at the end
                oWB.sheets(1).Cells(j, 1).Value = scanErgebnis(i).item
                oWB.sheets(1).Cells(j, 2 * position + 1).Value = scanErgebnis(i).count

            Else
                'Date line found
                oWB.sheets(1).Cells(j, 2 * position + 1).Value = scanErgebnis(i).count
            End If

        Next

    End If

End Sub
Function ArrayVerarbeiten(ByRef msgInhalt() As String) As TmyCount()
    'Aggregates msgContent by the dates, counting the occurrences

    Dim icount As Integer
    Dim acount() As TmyCount
    Dim i As Integer, index As Integer

    If IsStringArrayEmpty(msgInhalt) Then
        'If msgContent is not initialized, an uninitialized item is returned
        ArrayVerarbeiten = acount
        Exit Function
    End If

    icount = -1
    For i = 0 To UBound(msgInhalt)
        index = IsInArray(icount, acount, msgInhalt(i))
        If index < 0 Then
            icount = icount + 1
            ReDim Preserve acount(icount)
            acount(icount).item = msgInhalt(i)
            acount(icount).count = 1
        Else
            acount(index).count = acount(index).count + 1
        End If
    Next

    ArrayVerarbeiten = acount

End Function

Function IsInArray(icount As Integer, acount() As TmyCount, ele As String) As Integer
    'Prüft, ob ele in account enthalten ist
    'Prüft nur die Elemente an den Stellen < icount

    Dim i As Integer
    IsInArray = -1
    For i = 0 To icount
        If acount(i).item = ele Then
            IsInArray = i
            Exit Function
        End If
    Next
End Function

Function IsArrayEmpty(anArray() As TmyCount) As Boolean
    'Checks whether a TmyCount array has not been initialized

    Dim i As Integer

    On Error Resume Next
        i = UBound(anArray, 1)
    Select Case (Err.Number)
        Case 9
            IsArrayEmpty = True
        Case Else
            IsArrayEmpty = False
    End Select
End Function

Function IsStringArrayEmpty(anArray() As String) As Boolean
    'Checks whether a string array is uninitialized

    Dim i As Integer

    On Error Resume Next
    i = UBound(anArray, 1)
    Select Case (Err.Number)
        Case 9
           IsStringArrayEmpty = True
        Case Else
            IsStringArrayEmpty = False
    End Select
End Function```

**And this is the code to iterate over all folder recursively.**

    Private Sub processFolder(ByVal oParent As Outlook.MAPIFolder)

        Dim oFolder As Outlook.MAPIFolder
        Dim oMail As Outlook.MailItem

        Debug.Print(oParent.Items.Count)

        For Each oMail In oParent.Items

        'Get your data here ...

        Next

        If (oParent.Folders.Count > 0) Then
            For Each oFolder In oParent.Folders
                processFolder oFolder
            Next
        End If
End Sub
```

答:
You can use the following code to get the latest item:</p>
```<code>Sub Sample()
    Dim objNS As NameSpace
    Dim objFolder As MAPIFolder
    Dim myItems As Items
    Dim myItem As MailItem

    Set objNS = GetNamespace("MAPI")
    Set objFolder = objNS.GetDefaultFolder(olFolderInbox)

    Set myItems = objFolder.Items
    myItems.Sort "ReceivedTime", True

    If myItems.Count > 0 Then
        Set myItem = myItems.Item(1)

        Debug.Print myItem.ReceivedTime
    Else
        Msgbox "This folder doesn't have any emails/items"
    End If
End Sub
</code>```

Body:
I want to count the number of emails in seven subfolders of a shared mailbox.

I also want the date of the last email in these folders.

The shared mailbox looks like

>"Shared Mailbox Name"
>>Inbox
>>>Folder one
>>>>A
>>>>B
>>>>C
>>>Folder two
>>>>D
>>>>E
>>>>F
>>>>G

I want the result to show number of emails of all these folders together and not one by one. A, B, C, D, E, F, G.

I managed to get the number of emails for one folder at a time.

Type TmyCount
    item As Date
    count As Integer
End Type

Sub Steuerung()

    Dim objNS As Outlook.NameSpace
    Dim objFolder As Outlook.MAPIFolder
    Set objNS = GetNamespace("MAPI")
   Set objFolder = objNS.Folders("shared mailbox name") 'folders of your current account

    'Creates a new Excel workbook
    Dim oXL As Object
    Set oXL = CreateObject("Excel.Application")
    Set oWB = oXL.Workbooks.Add
    oWB.sheets(1).Cells(2, 1).Value = "Date/Day"

    'Creates a list to which folders to be counted can be appended
    Dim colList As Collection
    Set colList = New Collection

    Set objFolder = objFolder.Folders("Inbox")
    Set objFolder = objFolder.Folders("Folder one")
    Set objFolder = objFolder.Folders("A")
    'Set objFolder = objFolder.Folders("B")

    'Adds all subfolders of 'Inbound chargeback processing' to the list
    Dim subF As Outlook.MAPIFolder
    For Each subF In objFolder.Folders
        colList.Add subF
    Next subF

     'SampleCode to add new folders to the edit list
     Set objFolder = objNS.Folders("shared mailbox name") ' folders of your current account
     Set objFolder = objFolder.Folders("Inbox")
     Set objFolder = objFolder.Folders("A")
     'Set objFolder = objFolder.Folders("B")
     colList.Add objFolder

    '-----------------------------------------------------------------------------------------------------------------
    'Please enter folders to be processed above this line

    'Iterates over the folder list and counts all mails and enters the values in the Excel workbook
    Dim k As Integer
    For k = 1 To colList.count
        Call Arrayfüllen(colList.item(k), k)
    Next k

    oWB.sheets(1).Cells(2, 2 * k).Value = "ReklaSumme"
    oWB.sheets(1).Cells(2, 2 * k + 1).Value = "ScanSumme"

    Dim n As Integer
    n = 3

    Dim countRekla As Integer

    Dim countScan As Integer

    While oWB.sheets(1).Cells(n, 1) <> ""
        countScan = 0
        countRekla = 0

        For m = 2 To 2 * k - 2

            If m Mod 2 = 1 Then

                countScan = countScan + oWB.sheets(1).Cells(n, m).Value

            Else

                countRekla = countRekla + oWB.sheets(1).Cells(n, m).Value

            End If

        Next m

        oWB.sheets(1).Cells(n, 2 * k).Value = CStr(countRekla)
        oWB.sheets(1).Cells(n, 2 * k + 1).Value = CStr(countScan)

        n = n + 1
    Wend

    'Makes the Excel workbooks visible
    oXL.Visible = True

End Sub

Sub Arrayfüllen(objFolder As Outlook.MAPIFolder, position As Integer)
    'Fills the objFolder folder's messages into two different arrays depending on the sender

    Dim Message As Object

    Dim arraysizeRekla As Integer
    arraysizeRekla = 0
    Dim arraysizeScan As Integer
    arraysizeScan = 0

    Dim msgInhaltRekla() As String
    Dim msgInhaltScan() As String

    For Each Message In objFolder.Items
        'Iterates over all items in the folder
        If Message.Class = 43 Then
            'If the message is from then
            If Message.SenderName = "Jonas, Adamski" Then
                'If it is a sender, fill the date in the msgContentScan array
                ReDim Preserve msgInhaltScan(arraysizeScan)
                msgInhaltScan(arraysizeScan) = Format(Message.ReceivedTime, "dd.mm.yyyy")
                arraysizeScan = arraysizeScan + 1

            Else
                'Otherwise, fill the date in the msgContentRekla array
                ReDim Preserve msgInhaltRekla(arraysizeRekla)
                msgInhaltRekla(arraysizeRekla) = Format(Message.ReceivedTime, "dd.mm.yyyy")
                arraysizeRekla = arraysizeRekla + 1

            End If

        Else
            'Falls es sich um ein Terminobjekt etc. handelt
        End If
    Next

    Dim reklaErgebnis() As TmyCount
    reklaErgebnis = ArrayVerarbeiten(msgInhaltRekla)
    'reklaEregbnis is filled with the aggregated result from msg InhaltRekla
    Dim scanErgebnis() As TmyCount
    scanErgebnis = ArrayVerarbeiten(msgInhaltScan)
    'scanResult is filled with the aggregated result from msgContentScan

    'Creates the heading in the Excel document
    oWB.sheets(1).Cells(1, 2 * position).Value = objFolder.Name
    oWB.sheets(1).Cells(2, 2 * position).Value = "Rekla"
    oWB.sheets(1).Cells(2, 2 * position + 1).Value = "Scan"

    Dim j As Integer

    If IsArrayEmpty(reklaErgebnis) = False Then
        'If array reklaResult is not empty

        For i = 0 To UBound(reklaErgebnis)
            'Go through the whole array

            j = 3
            While oWB.sheets(1).Cells(j, 1).Value <> reklaErgebnis(i).item And oWB.sheets(1).Cells(j, 1).Value <> vbNullString
                'Find suitable date or navigate to the end
                j = j + 1
            Wend

            If oWB.sheets(1).Cells(j, 1).Value <> reklaErgebnis(i).item Then
                'Empty line at the end
                oWB.sheets(1).Cells(j, 1).Value = reklaErgebnis(i).item
                oWB.sheets(1).Cells(j, 2 * position).Value = reklaErgebnis(i).count

            Else
                'Date line found
                oWB.sheets(1).Cells(j, 2 * position).Value = reklaErgebnis(i).count
            End If

        Next

    End If

    If IsArrayEmpty(scanErgebnis) = False Then
        'If Array scanResult is not empty

        For i = 0 To UBound(scanErgebnis)

            j = 3
            While oWB.sheets(1).Cells(j, 1).Value <> scanErgebnis(i).item And oWB.sheets(1).Cells(j, 1).Value <> vbNullString
                'Find suitable date or navigate to the end
                j = j + 1
            Wend

            If oWB.sheets(1).Cells(j, 1).Value <> scanErgebnis(i).item Then
                'Empty line at the end
                oWB.sheets(1).Cells(j, 1).Value = scanErgebnis(i).item
                oWB.sheets(1).Cells(j, 2 * position + 1).Value = scanErgebnis(i).count

            Else
                'Date line found
                oWB.sheets(1).Cells(j, 2 * position + 1).Value = scanErgebnis(i).count
            End If

        Next

    End If

End Sub
Function ArrayVerarbeiten(ByRef msgInhalt() As String) As TmyCount()
    'Aggregates msgContent by the dates, counting the occurrences

    Dim icount As Integer
    Dim acount() As TmyCount
    Dim i As Integer, index As Integer

    If IsStringArrayEmpty(msgInhalt) Then
        'If msgContent is not initialized, an uninitialized item is returned
        ArrayVerarbeiten = acount
        Exit Function
    End If

    icount = -1
    For i = 0 To UBound(msgInhalt)
        index = IsInArray(icount, acount, msgInhalt(i))
        If index < 0 Then
            icount = icount + 1
            ReDim Preserve acount(icount)
            acount(icount).item = msgInhalt(i)
            acount(icount).count = 1
        Else
            acount(index).count = acount(index).count + 1
        End If
    Next

    ArrayVerarbeiten = acount

End Function

Function IsInArray(icount As Integer, acount() As TmyCount, ele As String) As Integer
    'Prüft, ob ele in account enthalten ist
    'Prüft nur die Elemente an den Stellen < icount

    Dim i As Integer
    IsInArray = -1
    For i = 0 To icount
        If acount(i).item = ele Then
            IsInArray = i
            Exit Function
        End If
    Next
End Function

Function IsArrayEmpty(anArray() As TmyCount) As Boolean
    'Checks whether a TmyCount array has not been initialized

    Dim i As Integer

    On Error Resume Next
        i = UBound(anArray, 1)
    Select Case (Err.Number)
        Case 9
            IsArrayEmpty = True
        Case Else
            IsArrayEmpty = False
    End Select
End Function

Function IsStringArrayEmpty(anArray() As String) As Boolean
    'Checks whether a string array is uninitialized

    Dim i As Integer

    On Error Resume Next
    i = UBound(anArray, 1)
    Select Case (Err.Number)
        Case 9
           IsStringArrayEmpty = True
        Case Else
            IsStringArrayEmpty = False
    End Select
End Function```

**And this is the code to iterate over all folder recursively.**

    Private Sub processFolder(ByVal oParent As Outlook.MAPIFolder)

        Dim oFolder As Outlook.MAPIFolder
        Dim oMail As Outlook.MailItem

        Debug.Print(oParent.Items.Count)

        For Each oMail In oParent.Items

        'Get your data here ...

        Next

        If (oParent.Folders.Count > 0) Then
            For Each oFolder In oParent.Folders
                processFolder oFolder
            Next
        End If
End Sub

Body:
You can use the following code to get the latest item:

Sub Sample()
    Dim objNS As NameSpace
    Dim objFolder As MAPIFolder
    Dim myItems As Items
    Dim myItem As MailItem

    Set objNS = GetNamespace("MAPI")
    Set objFolder = objNS.GetDefaultFolder(olFolderInbox)

    Set myItems = objFolder.Items
    myItems.Sort "ReceivedTime", True

    If myItems.Count > 0 Then
        Set myItem = myItems.Item(1)

        Debug.Print myItem.ReceivedTime
    Else
        Msgbox "This folder doesn't have any emails/items"
    End If
End Sub


来源: stackexchange

问:
Glitch in hover state when links are broken into multiple CSS columns
When there is a list of links and you apply the 'column-count' CSS property to the container and you hover slightly below the last link in the first column (link 3 in the example) then the hover state will apply to the first link in the second column instead.

.two-column {
  column-count: 2;
  column-gap: 2.5rem;
  width: 200px;
}

a:hover {
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="two-column">

  <li>

      Link 1

  </li>

  <li>

      Link 2

  </li>

  <li>

      Link 3

  </li>

  <li>

      Link 4

  </li>

  <li>

      Link 5

  </li>

</ul></code>```

I have also made a pen of the issue here codepen.

Edit:
You can see it happening in this GIF. Tested in Chrome 92 on macOS Big Sur, this doesn't seem to be a problem on Windows.

答:
As a workaround for this bug, you can add a 1px tall element to cover the bottom of the column to prevent hover events:

.two-column {
  column-count: 2;
  column-gap: 2.5rem;
  width: 200px;
  position: relative;
}

/* Hack for Chrome column hover bug */
.two-column::after {
  content: '';
  height: 1px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
}

a:hover {
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="two-column">

  <li>

      Link 1

  </li>

  <li>

      Link 2

  </li>

  <li>

      Link 3

  </li>

  <li>

      Link 4

  </li>

  <li>

      Link 5

  </li>

</ul></code>```

ContentLicense: CC BY-SA 4.0

Body:
When there is a list of links and you apply the 'column-count' CSS property to the container and you hover slightly below the last link in the first column (link 3 in the example) then the hover state will apply to the first link in the second column instead.

.two-column {
  column-count: 2;
  column-gap: 2.5rem;
  width: 200px;
}

a:hover {
  text-decoration: none;
}

      Link 1

      Link 2

      Link 3

      Link 4

      Link 5

I have also made a pen of the issue here codepen.

Edit:
You can see it happening in this GIF. Tested in Chrome 92 on macOS Big Sur, this doesn't seem to be a problem on Windows.

Body:
As a workaround for this bug, you can add a 1px tall element to cover the bottom of the column to prevent hover events:

.two-column {
  column-count: 2;
  column-gap: 2.5rem;
  width: 200px;
  position: relative;
}

/* Hack for Chrome column hover bug */
.two-column::after {
  content: '';
  height: 1px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
}

a:hover {
  text-decoration: none;
}

<ul class="two-column">

  <li>
    <a href="#">
      Link 1
    </a>
  </li>

  <li>
    <a href="#">
      Link 2
    </a>
  </li>

  <li>
    <a href="#">
      Link 3
    </a>
  </li>

  <li>
    <a href="#">
      Link 4
    </a>
  </li>

  <li>
    <a href="#">
      Link 5
    </a>
  </li>

</ul>


问:
Flutter - DragBox Feedback animate to original position
I want to show the animation of feedback of draggable when it is not accepted by the DropTarget.Flutter doesn't show the feedback. Is there any way we can show that or control it. Like this example, I want to achieve this effect. I somehow achieve this effect but it is not proper accurate returning to the original offset. It is moving ahead to its original position.

Animation effect I want.

Here is my Code, I have one drag box when I lift it to a certain position and leave him from there and it should animate back to original position, but it is returning to some other Offset like this.

```<code>import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: DragBox()),
    );
  }
}

class DragBox extends StatefulWidget {
  DragBox({
    Key key,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _MyDragBox();
  }
}

class _MyDragBox extends State<DragBox> with TickerProviderStateMixin {
  GlobalKey _globalKey = new GlobalKey();
  AnimationController _controller;
  Offset begin;
  Offset cancelledOffset;
  Offset _offsetOfWidget;
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((s) {
      _afeteLayout();
    });
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
  }

  void _afeteLayout() {
    final RenderBox box = _globalKey.currentContext.findRenderObject();
    Offset offset = -box.globalToLocal(Offset(0.0, 0.0));
    _offsetOfWidget = offset;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Center(
          child: Draggable(
            key: _globalKey,
            onDraggableCanceled: (v, o) {
              setState(() {
                cancelledOffset = o;
              });
              _controller.forward();
            },
            feedback: Container(
              color: Colors.red,
              height: 50,
              width: 50,
            ),
            child: Container(
              color: Colors.red,
              height: 50,
              width: 50,
            ),
          ),
        ),
        _controller.isAnimating
            ? SlideTransition(
                position: Tween<Offset>(
                        begin: cancelledOffset * 0.01,
                        end: _offsetOfWidget * 0.01)
                    .animate(_controller)
                      ..addStatusListener((status) {
                        if (status == AnimationStatus.completed) {
                          _controller.stop();
                        } else {
                          _controller.reverse();
                        }
                      }),
                child: Container(
                  color: Colors.red,
                  height: 50,
                  width: 50,
                ),
              )
            : Container(
                child: Text('data'),
              )
      ],
    );
  }
}
</code>```

答:
A simple way to solve this problem is to create a widget that overrides Draggable and make it a child of an AnimatedPositioned. Here is the example:

import 'package:flutter/material.dart';

class XDraggable extends StatefulWidget {
  const XDraggable(
      {Key? key,
      required this.child,
      required this.original_x,
      required this.original_y,
      this.animation_speed = 200})
      : super(key: key);
  final Widget child;
  final double original_x;
  final double original_y;
  final double animation_speed;

  @override
  _XDraggableState createState() => _XDraggableState();
}

class _XDraggableState extends State<XDraggable> {
  double x = 200;
  double y = 200;

  int animation_speed = 0;

  @override
  void initState() {
    x = widget.original_x;
    y = widget.original_y;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedPositioned(
      left: x,
      top: y,
      duration: Duration(milliseconds: animation_speed),
      child: Draggable(
        onDragUpdate: (details) => {
          setState(() {
            animation_speed = 0;
            x = x + details.delta.dx;
            y = y + details.delta.dy;
          }),
        },
        onDragEnd: (details) {
          setState(() {
            animation_speed = 200;
            x = widget.original_x;
            y = widget.original_y;
          });
        },
        child: widget.child,
        feedback: SizedBox(),
      ),
    );
  }
}

```
<p>Then, just use the widget as a Stack child:</p>
<pre class="lang-dart prettyprint-override"><code>...
child: Stack(
            fit: StackFit.expand,
            children: [
              XDraggable(
                original_x: 20,
                original_y: 20,
                child: Container(
                  height: 50.0,
                  width: 50.0,
                  color: Colors.green,
                ),
              )
            ],
          ),
...
</code>```

Body:
I want to show the animation of feedback of draggable when it is not accepted by the DropTarget.Flutter doesn't show the feedback. Is there any way we can show that or control it. Like this example, I want to achieve this effect. I somehow achieve this effect but it is not proper accurate returning to the original offset. It is moving ahead to its original position.

Animation effect I want.

Here is my Code, I have one drag box when I lift it to a certain position and leave him from there and it should animate back to original position, but it is returning to some other Offset like this.

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: DragBox()),
    );
  }
}

class DragBox extends StatefulWidget {
  DragBox({
    Key key,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _MyDragBox();
  }
}

class _MyDragBox extends State<DragBox> with TickerProviderStateMixin {
  GlobalKey _globalKey = new GlobalKey();
  AnimationController _controller;
  Offset begin;
  Offset cancelledOffset;
  Offset _offsetOfWidget;
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((s) {
      _afeteLayout();
    });
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
  }

  void _afeteLayout() {
    final RenderBox box = _globalKey.currentContext.findRenderObject();
    Offset offset = -box.globalToLocal(Offset(0.0, 0.0));
    _offsetOfWidget = offset;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Center(
          child: Draggable(
            key: _globalKey,
            onDraggableCanceled: (v, o) {
              setState(() {
                cancelledOffset = o;
              });
              _controller.forward();
            },
            feedback: Container(
              color: Colors.red,
              height: 50,
              width: 50,
            ),
            child: Container(
              color: Colors.red,
              height: 50,
              width: 50,
            ),
          ),
        ),
        _controller.isAnimating
            ? SlideTransition(
                position: Tween<Offset>(
                        begin: cancelledOffset * 0.01,
                        end: _offsetOfWidget * 0.01)
                    .animate(_controller)
                      ..addStatusListener((status) {
                        if (status == AnimationStatus.completed) {
                          _controller.stop();
                        } else {
                          _controller.reverse();
                        }
                      }),
                child: Container(
                  color: Colors.red,
                  height: 50,
                  width: 50,
                ),
              )
            : Container(
                child: Text('data'),
              )
      ],
    );
  }
}

Body:
A simple way to solve this problem is to create a widget that overrides Draggable and make it a child of an AnimatedPositioned. Here is the example:

import 'package:flutter/material.dart';

class XDraggable extends StatefulWidget {
  const XDraggable(
      {Key? key,
      required this.child,
      required this.original_x,
      required this.original_y,
      this.animation_speed = 200})
      : super(key: key);
  final Widget child;
  final double original_x;
  final double original_y;
  final double animation_speed;

  @override
  _XDraggableState createState() => _XDraggableState();
}

class _XDraggableState extends State<XDraggable> {
  double x = 200;
  double y = 200;

  int animation_speed = 0;

  @override
  void initState() {
    x = widget.original_x;
    y = widget.original_y;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedPositioned(
      left: x,
      top: y,
      duration: Duration(milliseconds: animation_speed),
      child: Draggable(
        onDragUpdate: (details) => {
          setState(() {
            animation_speed = 0;
            x = x + details.delta.dx;
            y = y + details.delta.dy;
          }),
        },
        onDragEnd: (details) {
          setState(() {
            animation_speed = 200;
            x = widget.original_x;
            y = widget.original_y;
          });
        },
        child: widget.child,
        feedback: SizedBox(),
      ),
    );
  }
}

Then, just use the widget as a Stack child:

...
child: Stack(
            fit: StackFit.expand,
            children: [
              XDraggable(
                original_x: 20,
                original_y: 20,
                child: Container(
                  height: 50.0,
                  width: 50.0,
                  color: Colors.green,
                ),
              )
            ],
          ),
...


问:
Best Practises of @Repository in Spring boot framework
I have a Spring boot application which has a UserRepository but I have not annotated that repository with @Repository but still my application works fine.

Why @Repository annotation is optional in Spring boot and what is the best practise that should we annotate it or not in repository classes.

答:
I assume you have somewhere implicitly or explicitly a EnableJpaRepositories annotation which scans all Spring repositories and your repositories are extending CrudRepository or other Spring Data base classes.

The annotation is only needed when defining you own repositories without using Spring Data mechanism. Note, that Repository is just a special Component, latter should also do it to have DI enabled, so this is more for better recognizing the purpose of the class.


问:
Google API Node.js Library - Grant Role to service account at project level

Goal

Assign a role dialogflow.admin to a service account I created for a project using the Node.js Client library for Google APIs.

Issue

When I try to update my service accounts IAM Policy and add a role to the service account. I get an error that the role is not supported for this resource type.

I am trying to give my service account the Dialogflow API Admin Role roles/dialogflow.admin

The method in the Node.js client library I am using is iam.projects.serviceAccounts.setIamPolicy.

I have already managed to create the service account with this Node.js client library with a function shown here.

```<code>async function createServiceAccount(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    var request = {
        name: "projects/"+projectID,
        resource: {
        "accountId": serviceAccountID,
        "serviceAccount": {
            "description" : "Service Account for project: "+projectID+" for DialogFlow authentication with VA",
            "displayName": "VA Dialogflow Service Account "+projectID
        }
      },

      auth: authClient,
    };

    await iam.projects.serviceAccounts.create(request, function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
       console.log(JSON.stringify(response, null, 2));
    });
}
</code>```

after this function runs, and I am sure the service account is created, I run my function that is meant to set the roles of this service account.

```<code>async function setServiceAccountRoles(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    var request = {
        resource_: "projects/"+projectID+"/serviceAccounts/"+serviceAccountID,
        resource: {
            policy: {
                bindings: [
                    {
                        // role: "projects/"+projectID+"roles/dialogflow.admin",
                        role: "roles/dialogflow.admin",
                        "members": [
                            "serviceAccount:"+serviceAccountID
                        ]
                    }
                    ],
                    version: 1
            }
        },

      auth: authClient,
    };

    await iam.projects.serviceAccounts.setIamPolicy(request, function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
       console.log(JSON.stringify(response, null, 2));
    });
}
</code>```

Error

When I run this function I am give this error:

```<code>  code: 400,
  errors: [
    {
      message: 'Role roles/dialogflow.admin is not supported for this resource.',
      domain: 'global',
      reason: 'badRequest'
    }
  ]
</code>```

I have used these following resources to get this far:
https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/setIamPolicy

https://cloud.google.com/iam/docs/reference/rest/v1/Policy

https://cloud.google.com/iam/docs/granting-changing-revoking-access#granting_access_to_a_service_account_for_a_resource

Alternative methods.

I have tried changing the role to a project specific path like this:

```<code>async function setServiceAccountRoles(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    var request = {
        resource_: "projects/"+projectID+"/serviceAccounts/"+serviceAccountID,
        resource: {
            policy: {
                bindings: [
                    {
                        role: "projects/"+projectID+"roles/dialogflow.admin",
                        "members": [
                            "serviceAccount:"+serviceAccountID
                        ]
                    }
                    ],
                    version: 1
            }
        },

      auth: authClient,
    };

    await iam.projects.serviceAccounts.setIamPolicy(request, function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
       console.log(JSON.stringify(response, null, 2));
    });
}
</code>```

however, with this I get the error : message: "Role (projects/va-9986d601/roles/dialogflow.admin) does not exist in the resource's hierarchy.",

Is it possible that the only way to update my service account's roles and permission is through the console or gcloud commands? If so, is there any recommended ways of running said gcloud commands through the node.js client library or from a node application itself?

答:
You are trying to set an IAM policy on the service account. That is used to grant other identities access to the service account itself.

You should modify the IAM binding for the project and not for the service account.

Use the getIamPolicy and setIamPolicy. Examples are included with the documentation.

WARNING: be very careful writing code that modifies a project's bindings. If you overwrite the bindings you can easily lock yourself out of your project. Then you would need to open a paid support ticket with Google Cloud Support. Practice with a throw away project.

Body:
Goal

Assign a role dialogflow.admin to a service account I created for a project using the Node.js Client library for Google APIs.

Issue

When I try to update my service accounts IAM Policy and add a role to the service account. I get an error that the role is not supported for this resource type.

I am trying to give my service account the Dialogflow API Admin Role roles/dialogflow.admin

The method in the Node.js client library I am using is iam.projects.serviceAccounts.setIamPolicy.

I have already managed to create the service account with this Node.js client library with a function shown here.

async function createServiceAccount(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    var request = {
        name: "projects/"+projectID,
        resource: {
        "accountId": serviceAccountID,
        "serviceAccount": {
            "description" : "Service Account for project: "+projectID+" for DialogFlow authentication with VA",
            "displayName": "VA Dialogflow Service Account "+projectID
        }
      },

      auth: authClient,
    };

    await iam.projects.serviceAccounts.create(request, function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
       console.log(JSON.stringify(response, null, 2));
    });
}

after this function runs, and I am sure the service account is created, I run my function that is meant to set the roles of this service account.

async function setServiceAccountRoles(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    var request = {
        resource_: "projects/"+projectID+"/serviceAccounts/"+serviceAccountID,
        resource: {
            policy: {
                bindings: [
                    {
                        // role: "projects/"+projectID+"roles/dialogflow.admin",
                        role: "roles/dialogflow.admin",
                        "members": [
                            "serviceAccount:"+serviceAccountID
                        ]
                    }
                    ],
                    version: 1
            }
        },

      auth: authClient,
    };

    await iam.projects.serviceAccounts.setIamPolicy(request, function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
       console.log(JSON.stringify(response, null, 2));
    });
}

Error

When I run this function I am give this error:

  code: 400,
  errors: [
    {
      message: 'Role roles/dialogflow.admin is not supported for this resource.',
      domain: 'global',
      reason: 'badRequest'
    }
  ]

I have used these following resources to get this far:
https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/setIamPolicy

https://cloud.google.com/iam/docs/reference/rest/v1/Policy

https://cloud.google.com/iam/docs/granting-changing-revoking-access#granting_access_to_a_service_account_for_a_resource

Alternative methods.

I have tried changing the role to a project specific path like this:

async function setServiceAccountRoles(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    var request = {
        resource_: "projects/"+projectID+"/serviceAccounts/"+serviceAccountID,
        resource: {
            policy: {
                bindings: [
                    {
                        role: "projects/"+projectID+"roles/dialogflow.admin",
                        "members": [
                            "serviceAccount:"+serviceAccountID
                        ]
                    }
                    ],
                    version: 1
            }
        },

      auth: authClient,
    };

    await iam.projects.serviceAccounts.setIamPolicy(request, function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
       console.log(JSON.stringify(response, null, 2));
    });
}

however, with this I get the error : message: "Role (projects/va-9986d601/roles/dialogflow.admin) does not exist in the resource's hierarchy.",

Is it possible that the only way to update my service account's roles and permission is through the console or gcloud commands? If so, is there any recommended ways of running said gcloud commands through the node.js client library or from a node application itself?


问:
Objectify - can we set a startAt(cursor) for QueryKeys? Or how to iterate over many Keys query?
I'm trying to iterate over 1000 keys of an entity at a time using this code but unlike Query, QueryKeys does not have a startAt() method for me to set it's cursor:

```<code>QueryKeys<Car> queryKeys = ofy().load().type(Car.class)
    .limit(1000)
     .keys();

// queryKeys has no startAt()
queryKeys = queryKeys.startAt(cursor)
</code>```

Is there a way to loop through keys with QueryKeys just like Query?

The reason I want to loop through keys is that I need to delete those entities from the Datastore. I might be deleting 100k - 1 million entities of a single entity type and wanted to do it in chunks because I am afraid that loading that many keys may slow things down too much or maybe error out somehow.

答:
You'll want to set the cursor before calling keys, e.g. objectify.get().load().type(Car.class).setStartCursor(...).limit(1000).keys().

Also, you are best to use the cursor from the previous query instead of relying on starting the query again to avoid skipping over tombstones as noted at https://cloud.google.com/datastore/docs/best-practices#deletions .

Body:
I'm trying to iterate over 1000 keys of an entity at a time using this code but unlike Query, QueryKeys does not have a startAt() method for me to set it's cursor:

QueryKeys<Car> queryKeys = ofy().load().type(Car.class)
    .limit(1000)
     .keys();

// queryKeys has no startAt()
queryKeys = queryKeys.startAt(cursor)

Is there a way to loop through keys with QueryKeys just like Query?

The reason I want to loop through keys is that I need to delete those entities from the Datastore. I might be deleting 100k - 1 million entities of a single entity type and wanted to do it in chunks because I am afraid that loading that many keys may slow things down too much or maybe error out somehow.


问:
node.js mongodb .. the (immutable) field '_id' was found to have been altered
I have some problem when I try to upsert my object with new ones(parsed from xml file),but I got the following error:

```<code> MongoError: exception: After applying the update to the document {_id: ObjectId('55be3c8f79bae4f80c6b17f8') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('55be5f15ae
5597401724aab3')
</code>```

Here is my code:

```<code>xmlFile.product_list.product.forEach(function (product) {

                    var productEntity = new Product({
                        product_id: parseInt(product.id),
                        parent_id: parseInt(product.parent_id),
                        sku: product.sku,
                        title: product.title,
                        pricenormal: parseFloat(product.price_normal),
                        pricewholesale: parseFloat(product.price_wholesale),
                        pricewholesalelarge: parseFloat(product.price_wholesale_large),
                        pricesale: parseFloat(product.price_sale),
                        weight: parseFloat(product.weight),
                        volume: parseFloat(product.volume),
                        unittype: product.unit_type,
                        status: product.status,
                        datecreating: product.datecreating,
                        sp: product.sp,
                        guaranteeext: product.guarantee_ext,
                        used: product.used,
                        statusfull: product.status_full,
                        description: null,
                        url: null
                    });
                    items.push(productEntity);

                });

items.forEach(function (product) { //update or create new products

                    Product.findOneAndUpdate({product_id: product.product_id}, product, {upsert: true}, function (err) {
                        if (err)  return updateDBCallback(err);
                        updateDBCallback(null, 'saved');

                    });

                });
</code>```

I tried to use hints like:

```<code>                //product._id = mongoose.Types.ObjectId(); //doesn't work
                //delete product._id // doesn't delete _id from product
</code>```

but they didn't help.
So I don't want to update my product._id , I just want to update the other fields.

答:
I got this error (in the Java driver) when my check for an _id was a String instead of an ObjectId.

Wrap your query appropriately:

```<code>myCoolCollection.findOneAndUpdate(Filters.eq("_id", new ObjectId(e.id)), ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some problem when I try to upsert my object with new ones(parsed from xml file),but I got the following error:

 MongoError: exception: After applying the update to the document {_id: ObjectId('55be3c8f79bae4f80c6b17f8') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('55be5f15ae
5597401724aab3')

Here is my code:

xmlFile.product_list.product.forEach(function (product) {

                    var productEntity = new Product({
                        product_id: parseInt(product.id),
                        parent_id: parseInt(product.parent_id),
                        sku: product.sku,
                        title: product.title,
                        pricenormal: parseFloat(product.price_normal),
                        pricewholesale: parseFloat(product.price_wholesale),
                        pricewholesalelarge: parseFloat(product.price_wholesale_large),
                        pricesale: parseFloat(product.price_sale),
                        weight: parseFloat(product.weight),
                        volume: parseFloat(product.volume),
                        unittype: product.unit_type,
                        status: product.status,
                        datecreating: product.datecreating,
                        sp: product.sp,
                        guaranteeext: product.guarantee_ext,
                        used: product.used,
                        statusfull: product.status_full,
                        description: null,
                        url: null
                    });
                    items.push(productEntity);

                });

items.forEach(function (product) { //update or create new products

                    Product.findOneAndUpdate({product_id: product.product_id}, product, {upsert: true}, function (err) {
                        if (err)  return updateDBCallback(err);
                        updateDBCallback(null, 'saved');

                    });

                });

I tried to use hints like:

                //product._id = mongoose.Types.ObjectId(); //doesn't work
                //delete product._id // doesn't delete _id from product

but they didn't help.
So I don't want to update my product._id , I just want to update the other fields.

Body:
I got this error (in the Java driver) when my check for an _id was a String instead of an ObjectId.

Wrap your query appropriately:

myCoolCollection.findOneAndUpdate(Filters.eq("_id", new ObjectId(e.id)), ...


问:
How to add columns to existing table
I am very new to SQL coding, I am using SQL Developer as the software to code.
I have a question, which I have tried to google and figure out but am having trouble.
I create a table called patvisit (patient visit) from two datasets Patient and visit. So I run the code below to create the new table patvisit. However, how do I add new columns with values into patvisit table without dropping the table and rerunning it. For example, I run the code below and create the table patvisit after I make the table I forget that I also wanted to add address that was in the patient table. Now what I would do is drop the patvisit table and then re-run the below code and add another column a.address. But is there a way to use the ALTER or ADD rules to be able to add a new column to an existing table? I tried looking for example codes online but I don't seem to get it. would appreciate any assistance/advise.

create table pativisit as
select distinct a.patientId, b.visit_no, b.visit_code, a.admit_date, a.discharge_date
from Patient a
inner join visit b
on a.visit_no=b.visit_no;

Thank you!

答:
Check out this link on using the SQL ALTER TABLEstatement to ad a column:
https://www.w3schools.com/sql/sql_alter.asp

Title: How to add columns to existing table


问:
R function to add column to dataframes using purrr::map
I'm creating a huge dataframe containing data from multiple .csv files with prices of different colours per day.

I want to add a column containing the name of the .csv file that each dataframe is created from. So eg. if the file is called "GRAY.csv" I want the resulting dataframe to add a new column "name" with each observation being "GRAY".

To create the dataframe I am using the map_df() function from the purrr package.

```<code>data_folder <- "data"
csv_files <- dir(data_folder, pattern = "[A-Z]\\.csv")

df <- csv_files %>%
  map_df(~ read_csv(file.path(data_folder, .)))
</code>```

What I get

```<code>df

## # A tibble: 3,175 × 2
##    date       price
##    <date>     <dbl>
##  1 2010-01-04  7.64
##  2 2010-01-05  7.66
##  3 2010-01-06  7.53
##  4 2010-01-07  7.52
##  5 2010-01-04  10.57
##  6 2010-01-05  10.50
##  7 2010-01-06  10.42
##  8 2010-01-07  10.52
##  9 2010-01-04  6.48
## 10 2010-01-05  6.35
## # … with 3,165 more rows
</code>```

What I want

```<code>df

## # A tibble: 3,175 × 3
##    date       price  name
##    <date>     <dbl>  <chr>
##  1 2010-01-04  7.64   GRAY
##  2 2010-01-05  7.66   GRAY
##  3 2010-01-06  7.53   GRAY
##  4 2010-01-07  7.52   GRAY
##  5 2010-01-04  10.57  BLUE
##  6 2010-01-05  10.50  BLUE
##  7 2010-01-06  10.42  BLUE
##  8 2010-01-07  10.52  BLUE
##  9 2010-01-04  6.48   RED
## 10 2010-01-05  6.35   RED
## # … with 3,165 more rows
</code>```

How do I add this name column?

答:
Before merging everything into one data frame, modify each individual data frame to have this name column, and then merge the data frames at the end using purrr::reduce().

```<code>library(tidyverse)
csv_files %>%
  map(
    ~ read_csv(file.path(data_folder, .x)) %>%
      mutate(name = str_remove(.x, "\\.csv"))
  ) %>%
  reduce(bind_rows)
</code>```

Body:
I'm creating a huge dataframe containing data from multiple .csv files with prices of different colours per day.

I want to add a column containing the name of the .csv file that each dataframe is created from. So eg. if the file is called "GRAY.csv" I want the resulting dataframe to add a new column "name" with each observation being "GRAY".

To create the dataframe I am using the map_df() function from the purrr package.

data_folder <- "data"
csv_files <- dir(data_folder, pattern = "[A-Z]\\.csv")

df <- csv_files %>%
  map_df(~ read_csv(file.path(data_folder, .)))

What I get

df

## # A tibble: 3,175 × 2
##    date       price
##    <date>     <dbl>
##  1 2010-01-04  7.64
##  2 2010-01-05  7.66
##  3 2010-01-06  7.53
##  4 2010-01-07  7.52
##  5 2010-01-04  10.57
##  6 2010-01-05  10.50
##  7 2010-01-06  10.42
##  8 2010-01-07  10.52
##  9 2010-01-04  6.48
## 10 2010-01-05  6.35
## # … with 3,165 more rows

What I want

df

## # A tibble: 3,175 × 3
##    date       price  name
##    <date>     <dbl>  <chr>
##  1 2010-01-04  7.64   GRAY
##  2 2010-01-05  7.66   GRAY
##  3 2010-01-06  7.53   GRAY
##  4 2010-01-07  7.52   GRAY
##  5 2010-01-04  10.57  BLUE
##  6 2010-01-05  10.50  BLUE
##  7 2010-01-06  10.42  BLUE
##  8 2010-01-07  10.52  BLUE
##  9 2010-01-04  6.48   RED
## 10 2010-01-05  6.35   RED
## # … with 3,165 more rows

How do I add this name column?

Body:
Before merging everything into one data frame, modify each individual data frame to have this name column, and then merge the data frames at the end using purrr::reduce().

library(tidyverse)
csv_files %>%
  map(
    ~ read_csv(file.path(data_folder, .x)) %>%
      mutate(name = str_remove(.x, "\\.csv"))
  ) %>%
  reduce(bind_rows)


问:
Question on jsLint error: "Don't make functions within a loop"
I'm reading DOM Scripting by Jeremy Keith and testing the code in jsLint

In the code sample here it i'm getting an error that says ""Don't make functions within a loop".

When I try to fix it, I seem to be losing the scope of this

I need to see an example of how to fix this error.

Here is the jsfiddle: http://jsfiddle.net/pkdsleeper/ejvMj/

Thanks In Advance

sleeper

答:
One way to do it is like this where you define local functions outside the loop:

```<code>(function highlightRows() {

    "use strict";

    if (!document.getElementById || !document.getElementsByTagName) { return false; }

    function handleMouseOver () {
        this.style.backgroundColor = "crimson";
        this.style.color = "#ffffff";
    }

    function handleMouseOut() {
        this.style.backgroundColor = "transparent";
        this.style.color = "#000000";
    }

    var tbl = document.getElementById("tbl_example"), // get the table
        rows = tbl.getElementsByTagName("tr"), // get all the table rows
        i,
        current_row;

    // loop through rows adding style info to the mouseover/mouseout events
    for (i = 0; i < rows.length; i++) {
        current_row = rows[i];

        // cancel highlight of th row
        if (current_row.parentNode.tagName === "THEAD") {
            continue;
        }

        current_row.onmouseover = handleMouseOver;
        current_row.onmouseout = handleMouseOut;
    }
}())
</code>```

Working in a jsFiddle: http://jsfiddle.net/jfriend00/aKfWs/.

Body:
One way to do it is like this where you define local functions outside the loop:

(function highlightRows() {

    "use strict";

    if (!document.getElementById || !document.getElementsByTagName) { return false; }

    function handleMouseOver () {
        this.style.backgroundColor = "crimson";
        this.style.color = "#ffffff";
    }

    function handleMouseOut() {
        this.style.backgroundColor = "transparent";
        this.style.color = "#000000";
    }

    var tbl = document.getElementById("tbl_example"), // get the table
        rows = tbl.getElementsByTagName("tr"), // get all the table rows
        i,
        current_row;

    // loop through rows adding style info to the mouseover/mouseout events
    for (i = 0; i < rows.length; i++) {
        current_row = rows[i];

        // cancel highlight of th row
        if (current_row.parentNode.tagName === "THEAD") {
            continue;
        }

        current_row.onmouseover = handleMouseOver;
        current_row.onmouseout = handleMouseOut;
    }
}())

Working in a jsFiddle: http://jsfiddle.net/jfriend00/aKfWs/.


问:
How to implement greater than or less than query parameters for FastAPI
I'd like to build an endpoint that looks like /cities?population__gt=100000 to get all cities with a population greater than 100,000.

What's the best way to do this in FastAPI? I'd prefer not to have to enumerate all the possible operators for a given field, likeso:

@app.get("/cities")
def get_city(
    population: int = None,
    population_gt: int = None,
    population_gte: int = None,
    population_lt: int = None,
    population_lte: int = None):
    return ...
```

答:
One way to implement this is to pass the operator (i.e., gt, lt, etc), and have a separate function for each operation, which you can call if an operator is received. Example below. You can adjust/add functions as required.

def gt(population):
    return f"operator: gt, population: {population}"

def gte(population):
    return f"operator: gte, population: {population}"

def lt(population):
    return f"operator: lt, population: {population}"

def lte(population):
    return f"operator: lte, population: {population}"

operators = {"gt": gt, "gte": gte, "lt": lt, "lte": lte}

@app.get("/cities")
def get_city(population: int = None, operator: str = None):
    if operator in operators:
        result = operators[operator](population)
        return result
    else:
        return "Operator Not Found!"
```
<h2>Update</h2>
<p>Since you mentioned that this needs to be done for more than one parameters, I would then suggest using an approach similar to this, where you could pass the operator within the value of each key and extract it later on server side, for example:</p>
```/cities?population=~gt~100000&population=~lt~500000&size=~eq~100000
```
<p>You could have operators similar to the link above, i.e., "Equals": <code>~eq~</code>, "Greater than": <code>~gt~</code>, "Greater than equals":<code> ~gteq~</code>, and so on.</p>
<p>To receive multiple values for a query parameter, such as the <code>population</code> in the example URL given above, in order to perform operations such as <code>where population is greater than <number> and less than <number></code>, you could declare a query parameter with a type of <code>List</code> and explicitly use <code>Query</code>, as described here and explained in the documentation.</p>
<p>The below example provides the logic behind this approach using the <code>population</code> parameter, as well as shows how to extract the operator and the actual value on server side. It is then up to you to define the rest of the parameters needed, as well as how to handle these data; for example, using a similar approach to the one above (having a function for each operation), or constructing the query you are about to pass to your database as you loop through the data.</p>
<pre class="lang-py prettyprint-override"><code>import re
pattern = "~(.*?)~"

@app.get("/cities")
def get_city(population: List[str] = Query(None)):
    pop_qs = {}

    for p in population:
        try:
            pop_opr = re.search(pattern, p).group(1)
            pop_no_str = re.sub(r"^~.*?~", "", p)
        except:
            return "Invalid data received"
        try:
            pop_no = int(pop_no_str)
            pop_qs.update({pop_opr : pop_no})
        except ValueError:
            return f"Cannot convert '{pop_no_str}' to Integer."

    return pop_qs
</code>```

Body:
One way to implement this is to pass the operator (i.e., gt, lt, etc), and have a separate function for each operation, which you can call if an operator is received. Example below. You can adjust/add functions as required.

def gt(population):
    return f"operator: gt, population: {population}"

def gte(population):
    return f"operator: gte, population: {population}"

def lt(population):
    return f"operator: lt, population: {population}"

def lte(population):
    return f"operator: lte, population: {population}"

operators = {"gt": gt, "gte": gte, "lt": lt, "lte": lte}

@app.get("/cities")
def get_city(population: int = None, operator: str = None):
    if operator in operators:
        result = operators[operator](population)
        return result
    else:
        return "Operator Not Found!"

Update

Since you mentioned that this needs to be done for more than one parameters, I would then suggest using an approach similar to this, where you could pass the operator within the value of each key and extract it later on server side, for example:

/cities?population=~gt~100000&population=~lt~500000&size=~eq~100000

You could have operators similar to the link above, i.e., "Equals": ~eq~, "Greater than": ~gt~, "Greater than equals": ~gteq~, and so on.

To receive multiple values for a query parameter, such as the population in the example URL given above, in order to perform operations such as where population is greater than <number> and less than <number>, you could declare a query parameter with a type of List and explicitly use Query, as described here and explained in the documentation.

The below example provides the logic behind this approach using the population parameter, as well as shows how to extract the operator and the actual value on server side. It is then up to you to define the rest of the parameters needed, as well as how to handle these data; for example, using a similar approach to the one above (having a function for each operation), or constructing the query you are about to pass to your database as you loop through the data.

import re
pattern = "~(.*?)~"

@app.get("/cities")
def get_city(population: List[str] = Query(None)):
    pop_qs = {}

    for p in population:
        try:
            pop_opr = re.search(pattern, p).group(1)
            pop_no_str = re.sub(r"^~.*?~", "", p)
        except:
            return "Invalid data received"
        try:
            pop_no = int(pop_no_str)
            pop_qs.update({pop_opr : pop_no})
        except ValueError:
            return f"Cannot convert '{pop_no_str}' to Integer."

    return pop_qs


问:
SQL - How to Multiply Prior Row value to Current Row
Can this be done and if so what is the best approach. I tried Over(Partition) but cannot figure out how to add the prior columns. Should I use IF BEGIN ENDS and just walk through it row by row for running balance? Any assistance on initial direction would be appreciated.

```<code>CREATE TABLE [dbo].[PStatement](
[ID] [int],
[Source] [nvarchar](255),
[PaymentNumber] [int],
[PaymentAmt] [money],
[RBalance] [money],
[CBalance] [money],
[AllocationPercent] [float]
</code>```

)

With the following values:

```<code>INSERT INTO PStatement (ID, [Source], PaymentNumber, PaymentAmt, RBalance, CBalance, AllocationPercent)
VALUES (1, N'SR', 1, 0, 7500, 10000, .75)
,(2, N'ER', 1, 0, 2500, 10000, .25)
,(3, N'SR', 2, 50, 0, 11000, 0)
,(4, N'ER', 2, 75, 0, 11000, .0)
,(5, N'SR', 3, 50, 0, 12000, 0)
,(6, N'ER', 3, 75, 0, 12000, .0)
</code>```

I need to take the CBalance from the prior row, subtract the sum of the current rows PaymentAmt and multiple that amount by the prior rows AllocationPercentage and then add back the PaymentAmt based on PaymentNumber and Source.

So Row 3 RBalance is $11000 - ($50 + $75) (from current row) * .75 (from prior row) + 50 (from current row), AllocationPercent is RBalance/CBalance.

So Row 4 is $11000 - ($50 + $75) * .25 + 75

The end table would look like this:

答:
Here is how I got it to work.</p>
```<code>DECLARE @MyCursor CURSOR;
DECLARE @id INT, @Source NVARCHAR(255), @CBalance MONEY, @RBalance MONEY, @PaymentAmt MONEY, @AllocationPercent decimal(18,10), @PaymentNumber INT, @Amount MONEY;
BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT ID FROM PStatement ORDER BY Source, PaymentNumber
    OPEN @MyCursor
    FETCH NEXT FROM @MyCursor
    INTO @id

    WHILE @@FETCH_STATUS = 0
    BEGIN
      SELECT @Source = Source, @PaymentNumber = PaymentNumber, @CBalance = CBalance, @PaymentAmt = PaymentAmt  FROM PStatement WHERE ID = @id
          IF(@PaymentNumber = 1)
            BEGIN
            UPDATE PStatement SET AllocationPercent = RBalance/ CAST(CBalance AS decimal(18, 10))  WHERE (ID = @id)
            SET @AllocationPercent = (SELECT AllocationPercent FROM PStatement WHERE (ID = @id))
            END
        ELSE
            BEGIN
            SET @PaymentAmt = (SELECT SUM(PaymentAmt) FROM PStatement WHERE (PaymentNumber = @PaymentNumber))
            SET @RBalance = ((@CBalance -  @PaymentAmt) * @AllocationPercent) + @PaymentAmt

            UPDATE PStatement SET RBalance = @RBalance WHERE (ID = @id)
            UPDATE PStatement SET AllocationPercent = RBalance/ CAST(CBalance AS decimal(18, 10))  WHERE (ID = @id)

            SET @AllocationPercent = (SELECT AllocationPercent FROM PStatement WHERE (ID = @id))

        END

      FETCH NEXT FROM @MyCursor
      INTO @id

    END;

    CLOSE @MyCursor ;
    DEALLOCATE @MyCursor;
END;
</code>```

Body:
Can this be done and if so what is the best approach. I tried Over(Partition) but cannot figure out how to add the prior columns. Should I use IF BEGIN ENDS and just walk through it row by row for running balance? Any assistance on initial direction would be appreciated.

CREATE TABLE [dbo].[PStatement](
[ID] [int],
[Source] [nvarchar](255),
[PaymentNumber] [int],
[PaymentAmt] [money],
[RBalance] [money],
[CBalance] [money],
[AllocationPercent] [float]

)

With the following values:

INSERT INTO PStatement (ID, [Source], PaymentNumber, PaymentAmt, RBalance, CBalance, AllocationPercent)
VALUES (1, N'SR', 1, 0, 7500, 10000, .75)
,(2, N'ER', 1, 0, 2500, 10000, .25)
,(3, N'SR', 2, 50, 0, 11000, 0)
,(4, N'ER', 2, 75, 0, 11000, .0)
,(5, N'SR', 3, 50, 0, 12000, 0)
,(6, N'ER', 3, 75, 0, 12000, .0)

I need to take the CBalance from the prior row, subtract the sum of the current rows PaymentAmt and multiple that amount by the prior rows AllocationPercentage and then add back the PaymentAmt based on PaymentNumber and Source.

So Row 3 RBalance is $11000 - ($50 + $75) (from current row) * .75 (from prior row) + 50 (from current row), AllocationPercent is RBalance/CBalance.

So Row 4 is $11000 - ($50 + $75) * .25 + 75

The end table would look like this:

Body:
Here is how I got it to work.

DECLARE @MyCursor CURSOR;
DECLARE @id INT, @Source NVARCHAR(255), @CBalance MONEY, @RBalance MONEY, @PaymentAmt MONEY, @AllocationPercent decimal(18,10), @PaymentNumber INT, @Amount MONEY;
BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT ID FROM PStatement ORDER BY Source, PaymentNumber
    OPEN @MyCursor
    FETCH NEXT FROM @MyCursor
    INTO @id

    WHILE @@FETCH_STATUS = 0
    BEGIN
      SELECT @Source = Source, @PaymentNumber = PaymentNumber, @CBalance = CBalance, @PaymentAmt = PaymentAmt  FROM PStatement WHERE ID = @id
          IF(@PaymentNumber = 1)
            BEGIN
            UPDATE PStatement SET AllocationPercent = RBalance/ CAST(CBalance AS decimal(18, 10))  WHERE (ID = @id)
            SET @AllocationPercent = (SELECT AllocationPercent FROM PStatement WHERE (ID = @id))
            END
        ELSE
            BEGIN
            SET @PaymentAmt = (SELECT SUM(PaymentAmt) FROM PStatement WHERE (PaymentNumber = @PaymentNumber))
            SET @RBalance = ((@CBalance -  @PaymentAmt) * @AllocationPercent) + @PaymentAmt

            UPDATE PStatement SET RBalance = @RBalance WHERE (ID = @id)
            UPDATE PStatement SET AllocationPercent = RBalance/ CAST(CBalance AS decimal(18, 10))  WHERE (ID = @id)

            SET @AllocationPercent = (SELECT AllocationPercent FROM PStatement WHERE (ID = @id))

        END

      FETCH NEXT FROM @MyCursor
      INTO @id

    END;

    CLOSE @MyCursor ;
    DEALLOCATE @MyCursor;
END;


问:
Vuetify - TypeError: Cannot read properties of undefined (reading 'trim')
This Problem occur at v-data-table of Vuetify.

This stop throwing error when remove the "show-select" option from below code.

Sometimes this component display correctly when I change and update other component.

I tried to rebuild, re-deploy, remove v-slot scope and so on.
But does not disappear this error.

Why does it occurr? Please help me...

<template>

      <v-data-table
        :headers="headers"
        :items="items"
        :items-per-page="per"
        :page.sync="page"
        item-key="no"
        show-select
        disable-sort
        hide-default-footer
        @input="selectedRow"
      >
        <template v-for="header in headers" #[`item.${header.value}`]="props">
          <template v-if="header.type === 'test'">
            {{ props.item[header.value] | toTestFormat }}
          </template>
          <template v-else>
            {{ props.item[header.value] }}
          </template>
        </template>
      </v-data-table>

      <v-pagination
        v-model="page"
        :length="pageCount"
        total-visible="5"
        @input="clickPage"
      >
      </v-pagination>

</template>

```
<p>Error detail is the below.</p>
<pre class="lang-sh prettyprint-override"><code>TypeError: Cannot read properties of undefined (reading 'trim')
    at VueComponent.getIcon (vuetify.js?ce5b:17220:1)
    at Proxy.render (vuetify.js?ce5b:17349:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4070:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)
    at mountComponent (vue.runtime.esm.js?2b0e:4088:1)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8459:1)
    at init (vue.runtime.esm.js?2b0e:3137:1)
    at createComponent (vue.runtime.esm.js?2b0e:6022:1)

TypeError: Cannot read properties of undefined (reading 'trim')
    at VueComponent.getIcon (vuetify.js?ce5b:17220:1)
    at Proxy.render (vuetify.js?ce5b:17349:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4070:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at Watcher.run (vue.runtime.esm.js?2b0e:4570:1)
    at flushSchedulerQueue (vue.runtime.esm.js?2b0e:4326:1)
    at Array.eval (vue.runtime.esm.js?2b0e:1989:1)
    at flushCallbacks (vue.runtime.esm.js?2b0e:1915:1)
</code>```

答: I didn't test this, but i think this happens because when you have show-select the table renders a checkbox in your header. And since you are making a v-for in all headers this will contain the checkbox and the line {{ props.item[header.value] }} will probably fail, so instead of the v-else use v-else-if="header.value != 'data-table-select'"

Body:
This Problem occur at v-data-table of Vuetify.

This stop throwing error when remove the "show-select" option from below code.

Sometimes this component display correctly when I change and update other component.

I tried to rebuild, re-deploy, remove v-slot scope and so on.
But does not disappear this error.

Why does it occurr? Please help me...

<template>

      <v-data-table
        :headers="headers"
        :items="items"
        :items-per-page="per"
        :page.sync="page"
        item-key="no"
        show-select
        disable-sort
        hide-default-footer
        @input="selectedRow"
      >
        <template v-for="header in headers" #[`item.${header.value}`]="props">
          <template v-if="header.type === 'test'">
            {{ props.item[header.value] | toTestFormat }}
          </template>
          <template v-else>
            {{ props.item[header.value] }}
          </template>
        </template>
      </v-data-table>

      <v-pagination
        v-model="page"
        :length="pageCount"
        total-visible="5"
        @input="clickPage"
      >
      </v-pagination>

</template>

Error detail is the below.

TypeError: Cannot read properties of undefined (reading 'trim')
    at VueComponent.getIcon (vuetify.js?ce5b:17220:1)
    at Proxy.render (vuetify.js?ce5b:17349:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4070:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)
    at mountComponent (vue.runtime.esm.js?2b0e:4088:1)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8459:1)
    at init (vue.runtime.esm.js?2b0e:3137:1)
    at createComponent (vue.runtime.esm.js?2b0e:6022:1)

TypeError: Cannot read properties of undefined (reading 'trim')
    at VueComponent.getIcon (vuetify.js?ce5b:17220:1)
    at Proxy.render (vuetify.js?ce5b:17349:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4070:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at Watcher.run (vue.runtime.esm.js?2b0e:4570:1)
    at flushSchedulerQueue (vue.runtime.esm.js?2b0e:4326:1)
    at Array.eval (vue.runtime.esm.js?2b0e:1989:1)
    at flushCallbacks (vue.runtime.esm.js?2b0e:1915:1)


问:
Python pandas how to use a lamda function to convert duplicated code in 1 line
I have a pandas python code like this:

```<code>def mul3(df):
    df['mul31'] = df['tpx1'].values * df['tqy1'].values * df['vtin1'].values * df[
        'slife1'].values
    df['mul32'] = df['tpx2'].values * df['tqy2'].values * df['vtin2'].values * df[
        'slife1'].values
    df['mul33'] = df['tpx3'].values * df['tqy3'].values * df['vtin3'].values * df[
        'slife1'].values
    df['mul34'] = df['tpx4'].values * df['tqy4'].values * df['vtin4'].values * df[
        'slife1'].values
    df['mul35'] = df['tpx5'].values * df['tqy5'].values * df['vtin5'].values * df[
        'slife1'].values
    return df
</code>```

Is there anyway I can use a lamda function to replace it to 1 line code?
Any friend can help?

答:
Not a one-liner but much more readable</p>
```<code>func = lambda df, num : df[f'tpx{num}'].values * df[f'tqy{num}'].values * df[f'vtin{num}'].values * df[f'slife1'].values
for i in range(5):
    df[f'mul3{i}'] = func(df, i)
</code>```

Body:
I have a pandas python code like this:

def mul3(df):
    df['mul31'] = df['tpx1'].values * df['tqy1'].values * df['vtin1'].values * df[
        'slife1'].values
    df['mul32'] = df['tpx2'].values * df['tqy2'].values * df['vtin2'].values * df[
        'slife1'].values
    df['mul33'] = df['tpx3'].values * df['tqy3'].values * df['vtin3'].values * df[
        'slife1'].values
    df['mul34'] = df['tpx4'].values * df['tqy4'].values * df['vtin4'].values * df[
        'slife1'].values
    df['mul35'] = df['tpx5'].values * df['tqy5'].values * df['vtin5'].values * df[
        'slife1'].values
    return df

Is there anyway I can use a lamda function to replace it to 1 line code?
Any friend can help?

Body:
Not a one-liner but much more readable

func = lambda df, num : df[f'tpx{num}'].values * df[f'tqy{num}'].values * df[f'vtin{num}'].values * df[f'slife1'].values
for i in range(5):
    df[f'mul3{i}'] = func(df, i)


问:
Custom Execution Strategy With Entity Framework Core
I have a .Net Core 3.1 Windows Service running using EF Core with a custom ExecutionStrategy.  This strategy has some logic in ShouldRetryOn() to perform time based logging when exceptions occur.  It is working well form the perspective of issuing the warnings when I want them.

What I would like to know is if there is a way from within the ExecutionStrategy to know if the retry attempt succeeds.  Let's assume I have a MaxRetryCount of 10, but after 3 retries it was successful, I would like to know about the success.

I did look into the Execute and ExcecuteAsync methods but they are only called once so there doesn't seem to be a way to tie into them.  I didn't see anything else in the ExecutionStrategy that I could leverage to be notified.

答:
I made a related post on github to the EF team.

To know if the operation succeeded in general (with or without
retries), you can override Execute and ExecuteAsync, call their base
methods, and if those base methods haven't raised any exception, then
the operation succeeded.


问:
Does Azure allow App need OpenGL, any way to go around?
I was hoping to host a remote app on Azure Virtual Machine, that was developed on top of VTK using python. Every time, I got crash message says "vtkWin32OpenGLRenderWindow...GL version2.1 with the gpu_shader4 extension is not supported by your graphic driver".
I tried windows server 2016 and windows 10 Virtual machine, same crash.

Is that Azure does not support to run app need OpenGl support?  Unless renting super expensive N virtual machine?

Any advise how to get my app run on normal cost virtual machine without revising my program too much?

答:
I finally got it to work for a program called PsychoPy that wants OpenGL 2.0 for everything.  I had to use the system wide install script "systemwidedeploy.cmd" at the top of the 7zip file "mesa3d-21.3.5-release-msvc.7z" to install it as detailed below.  It's already compiled, and you just have to download it and 7unzip it. Opengl Extensions Viewer reports the version as 3.3.  (How can I get the version through powershell?)

"OpenGL in a virtual machine - Thomas Schwery" https://thomas.inf3.ch/2019-06-12-opengl-kvm-mesa3d/index.html

Here's some relevant code from the install script.  It looks like there's a couple extra dll files to copy.

```<code>@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x86\libgallium_wgl.dll" copy "%mesaloc%\x86\libgallium_wgl.dll" "%windir%\SysWOW64\mesadrv.dll"
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x64\libgallium_wgl.dll" copy "%mesaloc%\x64\libgallium_wgl.dll" "%windir%\System32\mesadrv.dll"

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x86\libglapi.dll" copy "%mesaloc%\x86\libglapi.dll" "%windir%\SysWOW64"
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x64\libglapi.dll" copy "%mesaloc%\x64\libglapi.dll" "%windir%\System32"

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x86\dxil.dll" copy "%mesaloc%\x86\dxil.dll" "%windir%\SysWOW64"
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x64\dxil.dll" copy "%mesaloc%\x64\dxil.dll" "%windir%\System32"

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DLL" /t REG_SZ /d "mesadrv.dll" /f
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DriverVersion" /t REG_DWORD /d "1" /f
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Flags" /t REG_DWORD /d "1" /f
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Version" /t REG_DWORD /d "2" /f

@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DLL" /t REG_SZ /d "mesadrv.dll" /f
@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DriverVersion" /t REG_DWORD /d "1" /f
@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Flags" /t REG_DWORD /d "1" /f
@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Version" /t REG_DWORD /d "2" /f
</code>```

Body:
I finally got it to work for a program called PsychoPy that wants OpenGL 2.0 for everything.  I had to use the system wide install script "systemwidedeploy.cmd" at the top of the 7zip file "mesa3d-21.3.5-release-msvc.7z" to install it as detailed below.  It's already compiled, and you just have to download it and 7unzip it. Opengl Extensions Viewer reports the version as 3.3.  (How can I get the version through powershell?)

"OpenGL in a virtual machine - Thomas Schwery" https://thomas.inf3.ch/2019-06-12-opengl-kvm-mesa3d/index.html

Here's some relevant code from the install script.  It looks like there's a couple extra dll files to copy.

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x86\libgallium_wgl.dll" copy "%mesaloc%\x86\libgallium_wgl.dll" "%windir%\SysWOW64\mesadrv.dll"
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x64\libgallium_wgl.dll" copy "%mesaloc%\x64\libgallium_wgl.dll" "%windir%\System32\mesadrv.dll"

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x86\libglapi.dll" copy "%mesaloc%\x86\libglapi.dll" "%windir%\SysWOW64"
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x64\libglapi.dll" copy "%mesaloc%\x64\libglapi.dll" "%windir%\System32"

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x86\dxil.dll" copy "%mesaloc%\x86\dxil.dll" "%windir%\SysWOW64"
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 IF EXIST "%mesaloc%\x64\dxil.dll" copy "%mesaloc%\x64\dxil.dll" "%windir%\System32"

@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DLL" /t REG_SZ /d "mesadrv.dll" /f
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DriverVersion" /t REG_DWORD /d "1" /f
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Flags" /t REG_DWORD /d "1" /f
@IF /I %PROCESSOR_ARCHITECTURE%==AMD64 REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Version" /t REG_DWORD /d "2" /f

@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DLL" /t REG_SZ /d "mesadrv.dll" /f
@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "DriverVersion" /t REG_DWORD /d "1" /f
@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Flags" /t REG_DWORD /d "1" /f
@REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\OpenGLDrivers\MSOGL" /v "Version" /t REG_DWORD /d "2" /f


问:
How does this variable parameters list function call works?
When a program needs to communicate using Microsoft RPC developers typically write a IDL definition for all methods, for example:

```<code>error_status_t rpcMyInterfaceGetFile( [in] const GUID fileId, [out] BYTE_PIPE filePipe );
</code>```

which is compiled by MIDL compiler and produces a wrapper function:

```<code>/* [fault_status][comm_status] */ error_status_t rpcMyInterfacerGetFile(
/* [in] */ handle_t IDL_handle,
/* [in] */ const GUID fileId,
/* [out] */ BYTE_PIPE filePipe)
{
    CLIENT_CALL_RETURN _RetVal;
    _RetVal = NdrClientCall2(
              ( PMIDL_STUB_DESC  )&IMyInterfaceRpc_StubDesc,
              (PFORMAT_STRING) &MyInterfaceRpc__MIDL_ProcFormatString.Format[SomeNumberHere],
              ( unsigned char * )&IDL_handle);
    return ( error_status_t  )_RetVal.Simple;
}
</code>```

Here the call is forwarded to NdrClientCall2() RPC runtime function that is declared to have ... as the third parameter and does actual job. MyInterfaceRpc__MIDL_ProcFormatString is just a sequence of hardcoded bytes generated by MIDL, so the second parameter is a start of a subsection in that array declared in the same .c file as the wrapper function and having static storage duration.

How do the parameters (fileId and filePipe) get passed into NdrClientCall2()? I don't see them being passed. How do they happen to get from the wrapper to NdrClientCall2()?

答: Well, not quite sure but reading between the lines in the MSDN doc (which says that the last argument is Pointer to the client-side calling stack) it sounds like the NdrClientCall2 function can take the STUB_DESC structure, figure out what the argument types and sizes are, extract them from the stack, do the work of calling the remote interface and then write the results back into the proper locations on the stack (for OUT parameters).

Body:
When a program needs to communicate using Microsoft RPC developers typically write a IDL definition for all methods, for example:

error_status_t rpcMyInterfaceGetFile( [in] const GUID fileId, [out] BYTE_PIPE filePipe );

which is compiled by MIDL compiler and produces a wrapper function:

/* [fault_status][comm_status] */ error_status_t rpcMyInterfacerGetFile(
/* [in] */ handle_t IDL_handle,
/* [in] */ const GUID fileId,
/* [out] */ BYTE_PIPE filePipe)
{
    CLIENT_CALL_RETURN _RetVal;
    _RetVal = NdrClientCall2(
              ( PMIDL_STUB_DESC  )&IMyInterfaceRpc_StubDesc,
              (PFORMAT_STRING) &MyInterfaceRpc__MIDL_ProcFormatString.Format[SomeNumberHere],
              ( unsigned char * )&IDL_handle);
    return ( error_status_t  )_RetVal.Simple;
}

Here the call is forwarded to NdrClientCall2() RPC runtime function that is declared to have ... as the third parameter and does actual job. MyInterfaceRpc__MIDL_ProcFormatString is just a sequence of hardcoded bytes generated by MIDL, so the second parameter is a start of a subsection in that array declared in the same .c file as the wrapper function and having static storage duration.

How do the parameters (fileId and filePipe) get passed into NdrClientCall2()? I don't see them being passed. How do they happen to get from the wrapper to NdrClientCall2()?


问:
Docker nginx reverse proxy gives "502 Bad Gateway"
I'm trying to have a docker container with nginx work as reverse proxy to other docker containers and I keep getting "Bad Gateway" on locations other other than the base location '/'.

I have the following server block:

```<code>server {

  listen 80;

  location / {
    proxy_pass "http://game2048:8080";
  }

  location /game {
    proxy_pass "http://game:9999";
  }

}
</code>```

It works for http://localhost but not for http://localhost/game which gives "Bad Gateway" in the browser and this on the nginx container:

```<code>[error] 7#7: *6 connect() failed (111: Connection refused)
while connecting to upstream, client: 172.17.0.1, server: ,
request: "GET /game HTTP/1.1", upstream: "http://172.17.0.4:9999/game",
host: "localhost"
</code>```

I use the official nginx docker image and put my own configuration on it. You can test it and see all details here:
https://github.com/jollege/ngprox1

Any ideas what goes wrong?

NB: I have set local hostname entries on docker host to match those names:

```<code>127.0.1.1       game2048
127.0.1.1       game
</code>```

答:
You have to declare an external network if the container you are pointing to is defined in another docker-compose.yml file:

```<code>version: "3"

services:
  webserver:
    image: nginx:1.17.4-alpine
    container_name: ${PROJECT_NAME}-webserver
    depends_on:
      - drupal
    restart: unless-stopped
    ports:
      - 80:80
    volumes:
      - ./docroot:/var/www/html
      - ./nginx-conf:/etc/nginx/conf.d
      - certbot-etc:/etc/letsencrypt
    networks:
      - internal
      - my-passwords

networks:
  my-passwords:
    external: true
    name: my-passwords_default
</code>```

nginx.conf:

```<code>server {
    listen          80;
    server_name     test2.com www.test2.com;
    location / {
        proxy_pass  http://my-passwords:3000/;
    }
}
</code>```

Body:
I'm trying to have a docker container with nginx work as reverse proxy to other docker containers and I keep getting "Bad Gateway" on locations other other than the base location '/'.

I have the following server block:

server {

  listen 80;

  location / {
    proxy_pass "http://game2048:8080";
  }

  location /game {
    proxy_pass "http://game:9999";
  }

}

It works for http://localhost but not for http://localhost/game which gives "Bad Gateway" in the browser and this on the nginx container:

[error] 7#7: *6 connect() failed (111: Connection refused)
while connecting to upstream, client: 172.17.0.1, server: ,
request: "GET /game HTTP/1.1", upstream: "http://172.17.0.4:9999/game",
host: "localhost"

I use the official nginx docker image and put my own configuration on it. You can test it and see all details here:
https://github.com/jollege/ngprox1

Any ideas what goes wrong?

NB: I have set local hostname entries on docker host to match those names:

127.0.1.1       game2048
127.0.1.1       game

Body:
You have to declare an external network if the container you are pointing to is defined in another docker-compose.yml file:

version: "3"

services:
  webserver:
    image: nginx:1.17.4-alpine
    container_name: ${PROJECT_NAME}-webserver
    depends_on:
      - drupal
    restart: unless-stopped
    ports:
      - 80:80
    volumes:
      - ./docroot:/var/www/html
      - ./nginx-conf:/etc/nginx/conf.d
      - certbot-etc:/etc/letsencrypt
    networks:
      - internal
      - my-passwords

networks:
  my-passwords:
    external: true
    name: my-passwords_default

nginx.conf:

server {
    listen          80;
    server_name     test2.com www.test2.com;
    location / {
        proxy_pass  http://my-passwords:3000/;
    }
}


问:
Flutter - setState not updating inner Stateful Widget
Basically I am trying to make an app whose content will be updated with an async function that takes information from a website, but when I do try to set the new state, it doesn't reload the new content. If I debug the app, it shows that the current content is the new one, but after "rebuilding" the whole widget, it doesn't show the new info.

Edit: loadData ( ) method, basically read a URL with http package, the URL contains a JSON file whose content changes every 5 minutes with new news. For example a .json file with sports real-time scoreboards whose scores are always changing, so the content should always change with new results.

```<code>class mainWidget extends StatefulWidget
{
  State<StatefulWidget> createState() => new mainWidgetState();
}

class mainWidgetState extends State<mainWidget>
{

  List<Widget> _data;
  Timer timer;

  Widget build(BuildContext context) {
     return new ListView(
              children: _data);
  }

  @override
  void initState() {
    super.initState();
    timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async {
      String s = await loadData();
      this.setState(() {
        _data = <Widget> [new childWidget(s)];
      });
      });
  }
}

class childWidget extends StatefulWidget {
  childWidget(String s){
    _title = s;
  }

  Widget _title;

  createState() => new childState();
}

class childState extends State<gameCardS> {

  Widget _title;

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(onTap: foo(),
       child: new Card(child: new Text(_title));

  }

  initState()
  {
    super.initState();
    _title = widget._title;
  }
}
</code>```

答:
In my case, it was just defining the state as a class property and not a local variable in the build method

Doing this -

  List<Task> tasks = [
    Task('Buy milk'),
    Task('Buy eggs'),
    Task('Buy bread'),
  ];
  @override
  Widget build(BuildContext context) {

    return ListView.builder(
      itemBuilder: (context, index) => TaskTile(
...
```
<p>instead of this -</p>
<pre class="lang-dart prettyprint-override"><code> @override
  Widget build(BuildContext context) {
  List<Task> tasks = [
    Task('Buy milk'),
    Task('Buy eggs'),
    Task('Buy bread'),
  ];

    return ListView.builder(
      itemBuilder: (context, index) => TaskTile(
...
</code>```

Body:
Basically I am trying to make an app whose content will be updated with an async function that takes information from a website, but when I do try to set the new state, it doesn't reload the new content. If I debug the app, it shows that the current content is the new one, but after "rebuilding" the whole widget, it doesn't show the new info.

Edit: loadData ( ) method, basically read a URL with http package, the URL contains a JSON file whose content changes every 5 minutes with new news. For example a .json file with sports real-time scoreboards whose scores are always changing, so the content should always change with new results.

class mainWidget extends StatefulWidget
{
  State<StatefulWidget> createState() => new mainWidgetState();
}

class mainWidgetState extends State<mainWidget>
{

  List<Widget> _data;
  Timer timer;

  Widget build(BuildContext context) {
     return new ListView(
              children: _data);
  }

  @override
  void initState() {
    super.initState();
    timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async {
      String s = await loadData();
      this.setState(() {
        _data = <Widget> [new childWidget(s)];
      });
      });
  }
}

class childWidget extends StatefulWidget {
  childWidget(String s){
    _title = s;
  }

  Widget _title;

  createState() => new childState();
}

class childState extends State<gameCardS> {

  Widget _title;

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(onTap: foo(),
       child: new Card(child: new Text(_title));

  }

  initState()
  {
    super.initState();
    _title = widget._title;
  }
}

Body:
In my case, it was just defining the state as a class property and not a local variable in the build method

Doing this -

  List<Task> tasks = [
    Task('Buy milk'),
    Task('Buy eggs'),
    Task('Buy bread'),
  ];
  @override
  Widget build(BuildContext context) {

    return ListView.builder(
      itemBuilder: (context, index) => TaskTile(
...

instead of this -

 @override
  Widget build(BuildContext context) {
  List<Task> tasks = [
    Task('Buy milk'),
    Task('Buy eggs'),
    Task('Buy bread'),
  ];

    return ListView.builder(
      itemBuilder: (context, index) => TaskTile(
...


问:
How can I create a column containing the maximum across columns in SQL Server
I have a table CHA with many columns. There are two sets of 5 columns containing numeric data. I am looking to aggregate this data.

Select for the table below:

```<code>SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
              DMD1, DMD0, DMD2, DMD3, DMD4, DRC1, DRC0, DRC2, DRC3, DRC4, CHG0
FROM            Reporter.CHA
</code>```

I am looking to add some aggregate functions DMD_Min, DMD_Max, etc.

I have the following syntax for the new value, but I keep getting an error.

```<code>(SELECT MIN(MIN_DMD) FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
</code>```

Can anyone proved a better method for finding the row by row aggregate across columns?

Edit:

The error I am seeing in SQL server is:

Error in FROM clause: near 'Values'

Error in FROM clause: near ')'

Unable to parse query text.

This happens when I try to update the query from the select statement above to add in the DMD_MIN column as below:

```<code>SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL,
JobTitle, [Function], MGR, MonthNum, DMD1, DMD0, DMD2, DMD3, DMD4,
DRC1, DRC0, DRC2, DRC3, DRC4, CHG0,
(SELECT MIN(MIN_DMD) FROM (VALUES
(DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
FROM            Reporter.Compare_HA_Unpivot
</code>```

答:
You are very close to the answer, just need to put your query into an APPLY clause. APPLY will unpivot the data into 1 column, then you can run aggregates like MIN()/MAX() across all 5 data points.

Unpivot with APPLY then Aggregate

```<code>SELECT B.MIN_DMD
    ,B.MAX_DMD
    ,A.*
FROM Reporter.CHA AS A
CROSS APPLY (
        SELECT MIN_DMD = MIN(DMD)
                ,MAX_DMD = MAX(DMD)
        FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)
        ) AS DTA(DMD)
    ) AS B
</code>```

Alternatively, if you need to know which DMD column contains the highest value, you can use TOP (1) to calculate something like MIN()

TOP (1) from Unpivot with APPLY

```<code>SELECT B.DMD_ID
    ,B.DMD_VAL
    ,A.*
FROM Reporter.CHA AS A
CROSS APPLY (
        SELECT TOP (1) *
        FROM (
            VALUES (0,DMD0), (1,DMD1), (2,DMD2), (3,DMD3), (4,DMD4)
        ) AS DTA(DMD_ID,DMD_VAL)
        ORDER BY DMD_VAL
    ) AS B
</code>```

Body:
I have a table CHA with many columns. There are two sets of 5 columns containing numeric data. I am looking to aggregate this data.

Select for the table below:

SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
              DMD1, DMD0, DMD2, DMD3, DMD4, DRC1, DRC0, DRC2, DRC3, DRC4, CHG0
FROM            Reporter.CHA

I am looking to add some aggregate functions DMD_Min, DMD_Max, etc.

I have the following syntax for the new value, but I keep getting an error.

(SELECT MIN(MIN_DMD) FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD

Can anyone proved a better method for finding the row by row aggregate across columns?

Edit:

The error I am seeing in SQL server is:

Error in FROM clause: near 'Values'

Error in FROM clause: near ')'

Unable to parse query text.

This happens when I try to update the query from the select statement above to add in the DMD_MIN column as below:

SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL,
JobTitle, [Function], MGR, MonthNum, DMD1, DMD0, DMD2, DMD3, DMD4,
DRC1, DRC0, DRC2, DRC3, DRC4, CHG0,
(SELECT MIN(MIN_DMD) FROM (VALUES
(DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
FROM            Reporter.Compare_HA_Unpivot

Body:
You are very close to the answer, just need to put your query into an APPLY clause. APPLY will unpivot the data into 1 column, then you can run aggregates like MIN()/MAX() across all 5 data points.

Unpivot with APPLY then Aggregate

SELECT B.MIN_DMD
    ,B.MAX_DMD
    ,A.*
FROM Reporter.CHA AS A
CROSS APPLY (
        SELECT MIN_DMD = MIN(DMD)
                ,MAX_DMD = MAX(DMD)
        FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)
        ) AS DTA(DMD)
    ) AS B

Alternatively, if you need to know which DMD column contains the highest value, you can use TOP (1) to calculate something like MIN()

TOP (1) from Unpivot with APPLY

SELECT B.DMD_ID
    ,B.DMD_VAL
    ,A.*
FROM Reporter.CHA AS A
CROSS APPLY (
        SELECT TOP (1) *
        FROM (
            VALUES (0,DMD0), (1,DMD1), (2,DMD2), (3,DMD3), (4,DMD4)
        ) AS DTA(DMD_ID,DMD_VAL)
        ORDER BY DMD_VAL
    ) AS B