问:
Advanced filters is returning a single duplicate name at both the beginning and end of the created list?
I am attempting to combine four separate list of name into a single list without showing any duplicates. The code below uses the advanced filters to first filter for unique names from each of the four list and then combine them into a single name list. It then again uses advanced filters on the newly created consolidated name list to double check for duplicates and then writes the final list of unique names.

My issue is that the final name list is showing a single duplicate name that appears at both the beginning and at the end list.

```<code>Option Explicit

Sub CreateUniqueList()
Dim lastrow As Long

ActiveSheet.Range("d:d").Clear
ActiveSheet.Range("x:x").Clear

    ActiveSheet.Range("g13:g36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("D2"), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row + 1

    ActiveSheet.Range("i13:i36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("d" & lastrow), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row + 1

    ActiveSheet.Range("k13:k36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("d" & lastrow), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row + 1

    ActiveSheet.Range("m13:m36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("d" & lastrow), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row

    ActiveSheet.Range("d2:d" & lastrow).AdvancedFilter xlFilterCopy, , ActiveSheet.Range("x2"), True

ActiveSheet.Range("d:d").Clear

End Sub
</code>```

I'm sure it is a simple mistake but for the life of me I can't figure it out.

答:
Copy Unique Values From Columns

AdvancedFilter will copy the headers, so if the first row is 1, and 1 is found somewhere below, it will remain a duplicate. An idea would be to copy the range from column D to X right before your last AdvancedFilter action and apply a RemoveDuplicates instead.

But I've opted for a faster solution using data structures i.e. writing the whole source range to an array, writing the unique values from the designated columns of the source range to a dictionary, writing the values from the dictionary to another array, and finally, writing the values from the array to the destination range. Also, there is no need for a helper column.

Option Explicit

Sub CreateUniqueList()

    ' Source
    Const sName As String = "Sheet1"
    Const srgAddress As String = "G13:M36"
    Dim sCols As Variant: sCols = Array(1, 3, 5, 7)
    ' Destination
    Const dName As String = "Sheet1"
    Const dfCellAddress As String = "X2"
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Return the values from the source range ('srg')
    ' in the 2D one-based source array ('sData').
    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim srg As Range: Set srg = sws.Range(srgAddress)
    Dim sData As Variant: sData = srg.Value

    ' Return the unique values from the designated columns ('sCols')
    ' of the source array in a dictionary ('dict')
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    Dim c As Long
    For c = LBound(sCols) To UBound(sCols)
        DictAddColumn dict, sData, sCols(c)
    Next c
    Erase sData

    ' Return the values from the dictionary
    ' in the 2D one-based one-column destination array ('dData').
    Dim dData As Variant: dData = GetColumnDictKeys(dict)
    Set dict = Nothing
    Dim drCount As Long: drCount = UBound(dData, 1)

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    With dws.Range(dfCellAddress)
        ' Write the result.
        .Resize(drCount).Value = dData
        ' Clear below.
        .Resize(dws.Rows.Count - .Row - drCount + 1) _
            .Offset(drCount).ClearContents
    End With

    MsgBox "Unique list created.", vbInformation

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Adds the unique values from a column ('sColumnIndex')
'               of a 2D array ('sData') to an existing dictionary ('dDict').
' Remarks:      Error values and blanks are excluded.
' Remarks:      'ByRef' indicates that the dictionary in the calling procedure
'               will be modified.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub DictAddColumn( _
        ByRef dDict As Object, _
        ByVal sData As Variant, _
        Optional ByVal sColumnIndex As Variant, _
        Optional ByVal DoCount As Boolean = False)
    Const ProcName As String = "DictAddColumn"
    On Error GoTo ClearError

    Dim sKey As Variant
    Dim sr As Long
    For sr = LBound(sData, 1) To UBound(sData, 1)
        sKey = sData(sr, sColumnIndex)
        If Not IsError(sKey) Then
            If Len(CStr(sKey)) > 0 Then
                If DoCount Then
                    dDict(sKey) = dDict(sKey) + 1
                Else
                    dDict(sKey) = Empty
                End If
            End If
        End If
    Next sr

ProcExit:
    Exit Sub
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the keys from a dictionary ('sDict')
'               in a 2D one-based one-column array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetColumnDictKeys( _
    ByVal sDict As Object) _
As Variant
    Const ProcName As String = "GetColumnDictKeys"
    On Error GoTo ClearError

    Dim dData As Variant: ReDim dData(1 To sDict.Count, 1 To 1)

    Dim sKey As Variant
    Dim dr As Long

    For Each sKey In sDict.Keys
        dr = dr + 1
        dData(dr, 1) = sKey
    Next sKey

    GetColumnDictKeys = dData

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
```
<h2>EDIT</h2>
<ul>
<li>This solution copies the complete ranges' values and applies <code>RemoveDuplicates</code>.</li>
</ul>
<pre class="lang-vb prettyprint-override"><code>Sub CreateUniqueListCopyByAssignment()
' without helper column

    Const cCount As Long = 4

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim srg As Range: Set srg = ws.Range("G13:G36")
    Dim rCount As Long: rCount = srg.Rows.Count
    Dim drg As Range: Set drg = ws.Range("X2").Resize(rCount)

    Application.ScreenUpdating = False

    ws.Range("X2:X" & ws.Rows.Count).Clear

    Dim c As Long
    For c = 0 To cCount - 1
        drg.Offset(c * rCount).Value = srg.Offset(, c * 2).Value
    Next c

    drg.Resize(rCount * cCount).RemoveDuplicates 1, xlNo

    Application.ScreenUpdating = True

End Sub
</code>```

This solution is similar to yours, but it applies RemoveDuplicates near the end, mentioned at the top of this post. I think these ranges are too small to harvest the power of AdvancedFilter.

Sub CreateUniqueListQuickFix()
' with helper column
    Application.ScreenUpdating = False

    With ActiveSheet

        Dim rCount As Long: rCount = .Rows.Count
        Dim lr As Long

        .Range("X2:X" & rCount).Clear

        .Range("g13:g36").AdvancedFilter xlFilterCopy, , .Range("D2"), True

        lr = Cells(rCount, "D").End(xlUp).Row + 1
        .Range("i13:i36").AdvancedFilter xlFilterCopy, , .Range("D" & lr), True

        lr = Cells(rCount, "D").End(xlUp).Row + 1
        .Range("k13:k36").AdvancedFilter xlFilterCopy, , .Range("D" & lr), True

        lr = Cells(rCount, "D").End(xlUp).Row + 1
        .Range("m13:m36").AdvancedFilter xlFilterCopy, , .Range("D" & lr), True

        lr = Cells(rCount, "D").End(xlUp).Row
        .Range("D2:D" & lr).RemoveDuplicates 1, xlNo
        lr = Cells(rCount, "D").End(xlUp).Row
        .Range("D2:D" & lr).Copy .Range("X2")
        .Range("D2:D" & lr).Clear

    End With

    Application.ScreenUpdating = True

End Sub
```

Body:
I am attempting to combine four separate list of name into a single list without showing any duplicates. The code below uses the advanced filters to first filter for unique names from each of the four list and then combine them into a single name list. It then again uses advanced filters on the newly created consolidated name list to double check for duplicates and then writes the final list of unique names.

My issue is that the final name list is showing a single duplicate name that appears at both the beginning and at the end list.

Option Explicit

Sub CreateUniqueList()
Dim lastrow As Long

ActiveSheet.Range("d:d").Clear
ActiveSheet.Range("x:x").Clear

    ActiveSheet.Range("g13:g36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("D2"), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row + 1

    ActiveSheet.Range("i13:i36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("d" & lastrow), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row + 1

    ActiveSheet.Range("k13:k36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("d" & lastrow), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row + 1

    ActiveSheet.Range("m13:m36").AdvancedFilter xlFilterCopy, , ActiveSheet.Range("d" & lastrow), True

lastrow = Cells(Rows.Count, "d").End(xlUp).Row

    ActiveSheet.Range("d2:d" & lastrow).AdvancedFilter xlFilterCopy, , ActiveSheet.Range("x2"), True

ActiveSheet.Range("d:d").Clear

End Sub

I'm sure it is a simple mistake but for the life of me I can't figure it out.

Body:
Copy Unique Values From Columns

AdvancedFilter will copy the headers, so if the first row is 1, and 1 is found somewhere below, it will remain a duplicate. An idea would be to copy the range from column D to X right before your last AdvancedFilter action and apply a RemoveDuplicates instead.

But I've opted for a faster solution using data structures i.e. writing the whole source range to an array, writing the unique values from the designated columns of the source range to a dictionary, writing the values from the dictionary to another array, and finally, writing the values from the array to the destination range. Also, there is no need for a helper column.

Option Explicit

Sub CreateUniqueList()

    ' Source
    Const sName As String = "Sheet1"
    Const srgAddress As String = "G13:M36"
    Dim sCols As Variant: sCols = Array(1, 3, 5, 7)
    ' Destination
    Const dName As String = "Sheet1"
    Const dfCellAddress As String = "X2"
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Return the values from the source range ('srg')
    ' in the 2D one-based source array ('sData').
    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim srg As Range: Set srg = sws.Range(srgAddress)
    Dim sData As Variant: sData = srg.Value

    ' Return the unique values from the designated columns ('sCols')
    ' of the source array in a dictionary ('dict')
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    Dim c As Long
    For c = LBound(sCols) To UBound(sCols)
        DictAddColumn dict, sData, sCols(c)
    Next c
    Erase sData

    ' Return the values from the dictionary
    ' in the 2D one-based one-column destination array ('dData').
    Dim dData As Variant: dData = GetColumnDictKeys(dict)
    Set dict = Nothing
    Dim drCount As Long: drCount = UBound(dData, 1)

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    With dws.Range(dfCellAddress)
        ' Write the result.
        .Resize(drCount).Value = dData
        ' Clear below.
        .Resize(dws.Rows.Count - .Row - drCount + 1) _
            .Offset(drCount).ClearContents
    End With

    MsgBox "Unique list created.", vbInformation

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Adds the unique values from a column ('sColumnIndex')
'               of a 2D array ('sData') to an existing dictionary ('dDict').
' Remarks:      Error values and blanks are excluded.
' Remarks:      'ByRef' indicates that the dictionary in the calling procedure
'               will be modified.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub DictAddColumn( _
        ByRef dDict As Object, _
        ByVal sData As Variant, _
        Optional ByVal sColumnIndex As Variant, _
        Optional ByVal DoCount As Boolean = False)
    Const ProcName As String = "DictAddColumn"
    On Error GoTo ClearError

    Dim sKey As Variant
    Dim sr As Long
    For sr = LBound(sData, 1) To UBound(sData, 1)
        sKey = sData(sr, sColumnIndex)
        If Not IsError(sKey) Then
            If Len(CStr(sKey)) > 0 Then
                If DoCount Then
                    dDict(sKey) = dDict(sKey) + 1
                Else
                    dDict(sKey) = Empty
                End If
            End If
        End If
    Next sr

ProcExit:
    Exit Sub
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the keys from a dictionary ('sDict')
'               in a 2D one-based one-column array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetColumnDictKeys( _
    ByVal sDict As Object) _
As Variant
    Const ProcName As String = "GetColumnDictKeys"
    On Error GoTo ClearError

    Dim dData As Variant: ReDim dData(1 To sDict.Count, 1 To 1)

    Dim sKey As Variant
    Dim dr As Long

    For Each sKey In sDict.Keys
        dr = dr + 1
        dData(dr, 1) = sKey
    Next sKey

    GetColumnDictKeys = dData

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function

EDIT

This solution copies the complete ranges' values and applies RemoveDuplicates.

Sub CreateUniqueListCopyByAssignment()
' without helper column

    Const cCount As Long = 4

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim srg As Range: Set srg = ws.Range("G13:G36")
    Dim rCount As Long: rCount = srg.Rows.Count
    Dim drg As Range: Set drg = ws.Range("X2").Resize(rCount)

    Application.ScreenUpdating = False

    ws.Range("X2:X" & ws.Rows.Count).Clear

    Dim c As Long
    For c = 0 To cCount - 1
        drg.Offset(c * rCount).Value = srg.Offset(, c * 2).Value
    Next c

    drg.Resize(rCount * cCount).RemoveDuplicates 1, xlNo

    Application.ScreenUpdating = True

End Sub

This solution is similar to yours, but it applies RemoveDuplicates near the end, mentioned at the top of this post. I think these ranges are too small to harvest the power of AdvancedFilter.

Sub CreateUniqueListQuickFix()
' with helper column
    Application.ScreenUpdating = False

    With ActiveSheet

        Dim rCount As Long: rCount = .Rows.Count
        Dim lr As Long

        .Range("X2:X" & rCount).Clear

        .Range("g13:g36").AdvancedFilter xlFilterCopy, , .Range("D2"), True

        lr = Cells(rCount, "D").End(xlUp).Row + 1
        .Range("i13:i36").AdvancedFilter xlFilterCopy, , .Range("D" & lr), True

        lr = Cells(rCount, "D").End(xlUp).Row + 1
        .Range("k13:k36").AdvancedFilter xlFilterCopy, , .Range("D" & lr), True

        lr = Cells(rCount, "D").End(xlUp).Row + 1
        .Range("m13:m36").AdvancedFilter xlFilterCopy, , .Range("D" & lr), True

        lr = Cells(rCount, "D").End(xlUp).Row
        .Range("D2:D" & lr).RemoveDuplicates 1, xlNo
        lr = Cells(rCount, "D").End(xlUp).Row
        .Range("D2:D" & lr).Copy .Range("X2")
        .Range("D2:D" & lr).Clear

    End With

    Application.ScreenUpdating = True

End Sub


来源: stackexchange

问:
Why does my button not work after adding a template?(Worked Before)
and thank you. I have been making a website. I put a template on the submit button to make it look nicer. Ever since it has only worked when I press it in a specific spot, and even then it doesn't work all the time. When pressed it logs you into flask-login with my Flask-Sqlalchemy database, and redirects to a logged in page.

Here is the button, and form:

@import url("https://fonts.googleapis.com/css?family=Montserrat");
body {
  background: #2f2f31;
  transform: rotateX(0.003deg);
  height: 100vh;
  color: #fff;
}
.a {
  position: absolute;
  left: 50%;
  top: 90%;
  transform: translate(-50%, -50%);
  color: #cecd24;
  text-decoration: none;
  font-size: 1.2em;
  display: inline-block;
  font-family: Montserrat;
  text-transform: uppercase;
  padding: 0.3em 1.2em;
  border: 2px solid #cecd24;
  transition: 0.02s 0.2s cubic-bezier(0.1, 0, 0.1, 1);
}
.a::before {
  content: "";
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
  right: 100%;
  bottom: 0;
  background: #cecd24;
  transition: 0.3s 0.2s cubic-bezier(0.1, 0, 0.1, 1), left 0.3s cubic-bezier(0.1, 0, 0.1, 1);
  z-index: -1;
}
.a::after {
  content: "";
  display: inline-block;
  background-image: url("https://image.flaticon.com/icons/png/128/109/109617.png");
  position: absolute;
  top: 0;
  left: calc(100% - 3em);
  right: 3em;
  bottom: 0;
  background-size: 1.5em;
  background-repeat: no-repeat;
  background-position: center;
  transition: right 0.3s cubic-bezier(0.1, 0, 0.1, 1);
}
.a:hover {
  padding: 0.5em 3.5em 0.5em 0.5em;
}
.a:hover::before {
  left: calc(100% - 3em);
  right: 0;
  transition: 0.3s cubic-bezier(0.1, 0, 0.1, 1), left 0.3s 0.2s cubic-bezier(0.1, 0, 0.1, 1);
}
.a:hover::after {
  right: 0;
  transition: right 0.3s 0.2s cubic-bezier(0.1, 0, 0.1, 1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" onclick="onclick">
  <div class="top"></div>
  <div class="bottom"></div>
  <div class="center">
    <h2>Please Sign In</h2>
    <form method='post'>
      <input type="email" name="email_login" placeholder="email"/>
      <input type="username" name="username_login" placeholder="username">
      <input type="password" name="password_login" placeholder="password"/>
      <select  name='remember'>
                <option value="remember"> Remember Me</option>
                <option value="don't">Don't remember. Database has a bad memory</option>
        </select>
        <button class="a" type="submit" name="submit" id="submit">Submit</button>
    </form>
    <h2> </h2>
  </div>
</div></code>```

NOTE: It was originally SCSS, but I compiled it with an online compiler to use it with flask easily.
I can also add the flask code it is connected to if needed!

Any help would be appreciated. Thank You!

答: For whatever reason, the code kind of magically started working again. I didn't change anything, but now when I press the button it works. Thank you everyone for your help!</p>

ContentLicense: CC BY-SA 4.0

Body:
and thank you. I have been making a website. I put a template on the submit button to make it look nicer. Ever since it has only worked when I press it in a specific spot, and even then it doesn't work all the time. When pressed it logs you into flask-login with my Flask-Sqlalchemy database, and redirects to a logged in page.

Here is the button, and form:

@import url("https://fonts.googleapis.com/css?family=Montserrat");
body {
  background: #2f2f31;
  transform: rotateX(0.003deg);
  height: 100vh;
  color: #fff;
}
.a {
  position: absolute;
  left: 50%;
  top: 90%;
  transform: translate(-50%, -50%);
  color: #cecd24;
  text-decoration: none;
  font-size: 1.2em;
  display: inline-block;
  font-family: Montserrat;
  text-transform: uppercase;
  padding: 0.3em 1.2em;
  border: 2px solid #cecd24;
  transition: 0.02s 0.2s cubic-bezier(0.1, 0, 0.1, 1);
}
.a::before {
  content: "";
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
  right: 100%;
  bottom: 0;
  background: #cecd24;
  transition: 0.3s 0.2s cubic-bezier(0.1, 0, 0.1, 1), left 0.3s cubic-bezier(0.1, 0, 0.1, 1);
  z-index: -1;
}
.a::after {
  content: "";
  display: inline-block;
  background-image: url("https://image.flaticon.com/icons/png/128/109/109617.png");
  position: absolute;
  top: 0;
  left: calc(100% - 3em);
  right: 3em;
  bottom: 0;
  background-size: 1.5em;
  background-repeat: no-repeat;
  background-position: center;
  transition: right 0.3s cubic-bezier(0.1, 0, 0.1, 1);
}
.a:hover {
  padding: 0.5em 3.5em 0.5em 0.5em;
}
.a:hover::before {
  left: calc(100% - 3em);
  right: 0;
  transition: 0.3s cubic-bezier(0.1, 0, 0.1, 1), left 0.3s 0.2s cubic-bezier(0.1, 0, 0.1, 1);
}
.a:hover::after {
  right: 0;
  transition: right 0.3s 0.2s cubic-bezier(0.1, 0, 0.1, 1);
}

Please Sign In

    <form method='post'>
      <input type="email" name="email_login" placeholder="email"/>
      <input type="username" name="username_login" placeholder="username">
      <input type="password" name="password_login" placeholder="password"/>
      <select  name='remember'>
                <option value="remember"> Remember Me</option>
                <option value="don't">Don't remember. Database has a bad memory</option>
        </select>
        <button class="a" type="submit" name="submit" id="submit">Submit</button>
    </form>

NOTE: It was originally SCSS, but I compiled it with an online compiler to use it with flask easily.
I can also add the flask code it is connected to if needed!

Any help would be appreciated. Thank You!


问:
Problem with code compatibility with Python 3.9 - "TypeError: a bytes-like object is required, not 'str'"
While trying to run a telemetry python application on Python 3.9, it fails with the error "TypeError: a bytes-like object is required, not 'str'"

Attempting to fix the code by changing 'r' to 'rb' (and 'w' to 'wb') as suggested elsewhere results in a different error.

Unfortunately, I can't figure this one out.  Can anyone help me identify the problem here?  I'm very new to this.  Thanks in advance.

```<code>  def __init__(self):
    try:
      with open(STATUS_FILE, 'r') as sfd:
        self.st_data = pickle.loads(sfd.read())
    except IOError:
      self.st_data = dict(seq=0, timestamp=int(time.time()), rx_packets=0, tx_packets=0)

    self.st_data['seq'] = (self.st_data['seq'] % 999) + 1

  def __repr__(self):
    return "%s %s" % (self.__class__, self.st_data)

  def save(self):
    self.st_data['timestamp'] = int(time.time())
    try:
      with open(STATUS_FILE, 'w') as sfd:
        sfd.write(pickle.dumps(self.st_data))
    except IOError as err:
      print(err)
</code>```

答:
Using binary file modes is the correct thing to do.  Making your code into a reproducible example with those changes works.  Make sure to delete any STATUS_FILE created by the original non-working code:

STATUS_FILE = 'test.pkl'   # defined missing variable

class Test:                # added shown methods to a class
    def __init__(self):
        try:
         with open(STATUS_FILE, 'rb') as sfd:  # use binary mode
            self.st_data = pickle.loads(sfd.read())
        except IOError:
            self.st_data = dict(seq=0, timestamp=int(time.time()), rx_packets=0, tx_packets=0)

        self.st_data['seq'] = (self.st_data['seq'] % 999) + 1

    def __repr__(self):
        return "%s %s" % (self.__class__, self.st_data)

    def save(self):
        self.st_data['timestamp'] = int(time.time())
        try:
            with open(STATUS_FILE, 'wb') as sfd:   # use binary mode
                sfd.write(pickle.dumps(self.st_data))
        except IOError as err:
            print(err)

t = Test()   # instantiate class, read from save file if present
print(t)     # view the result
t.save()     # create the save file
```
<p>Output from multiple runs.  Sequence increments and timestamp changes.</p>
<pre class="lang-none prettyprint-override"><code><class '__main__.Test'> {'seq': 1, 'timestamp': 1644104029, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 2, 'timestamp': 1644104029, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 3, 'timestamp': 1644104030, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 4, 'timestamp': 1644104030, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 5, 'timestamp': 1644104031, 'rx_packets': 0, 'tx_packets': 0}
</code>```

Body:
While trying to run a telemetry python application on Python 3.9, it fails with the error "TypeError: a bytes-like object is required, not 'str'"

Attempting to fix the code by changing 'r' to 'rb' (and 'w' to 'wb') as suggested elsewhere results in a different error.

Unfortunately, I can't figure this one out.  Can anyone help me identify the problem here?  I'm very new to this.  Thanks in advance.

  def __init__(self):
    try:
      with open(STATUS_FILE, 'r') as sfd:
        self.st_data = pickle.loads(sfd.read())
    except IOError:
      self.st_data = dict(seq=0, timestamp=int(time.time()), rx_packets=0, tx_packets=0)

    self.st_data['seq'] = (self.st_data['seq'] % 999) + 1

  def __repr__(self):
    return "%s %s" % (self.__class__, self.st_data)

  def save(self):
    self.st_data['timestamp'] = int(time.time())
    try:
      with open(STATUS_FILE, 'w') as sfd:
        sfd.write(pickle.dumps(self.st_data))
    except IOError as err:
      print(err)

Body:
Using binary file modes is the correct thing to do.  Making your code into a reproducible example with those changes works.  Make sure to delete any STATUS_FILE created by the original non-working code:

STATUS_FILE = 'test.pkl'   # defined missing variable

class Test:                # added shown methods to a class
    def __init__(self):
        try:
         with open(STATUS_FILE, 'rb') as sfd:  # use binary mode
            self.st_data = pickle.loads(sfd.read())
        except IOError:
            self.st_data = dict(seq=0, timestamp=int(time.time()), rx_packets=0, tx_packets=0)

        self.st_data['seq'] = (self.st_data['seq'] % 999) + 1

    def __repr__(self):
        return "%s %s" % (self.__class__, self.st_data)

    def save(self):
        self.st_data['timestamp'] = int(time.time())
        try:
            with open(STATUS_FILE, 'wb') as sfd:   # use binary mode
                sfd.write(pickle.dumps(self.st_data))
        except IOError as err:
            print(err)

t = Test()   # instantiate class, read from save file if present
print(t)     # view the result
t.save()     # create the save file

Output from multiple runs.  Sequence increments and timestamp changes.

<class '__main__.Test'> {'seq': 1, 'timestamp': 1644104029, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 2, 'timestamp': 1644104029, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 3, 'timestamp': 1644104030, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 4, 'timestamp': 1644104030, 'rx_packets': 0, 'tx_packets': 0}
<class '__main__.Test'> {'seq': 5, 'timestamp': 1644104031, 'rx_packets': 0, 'tx_packets': 0}


问:
turn several line function into a one liner list format
I am learning and I am trying to make this code nicer and learn more in pythonic way! I wanna turn this code into a one line code inside list (list comprehension). e.g., [here goes the new implementation]</p>
```<code>def main():
    inp = input()
    x = []
    x_tm = ''
    for i in range( 0, len(inp)):
        if inp[i] == ',':
            x.append(x_tm)
            x_tm = ""
            continue
        if inp[i] ==" ":
            continue
        x_tm += inp[i]
    x.append(inp)

</code>```

答:
There is a built-in function called "split" that does what you wrote.

```<code>def main():
inp = input("Enter text: ").split(",")
print(inp)
</code>```

If you want to write the function yourself it would look something like this:

```<code>def main():
inp = input("Enter text: ")
temp = ""
words = []
for ltr in inp:
    if ltr == ",":
        words.append(temp)
        temp = ""
    else:
        temp += ltr
if len(temp):
    words.append(temp)
print(words)
</code>```

Body:
I am learning and I am trying to make this code nicer and learn more in pythonic way! I wanna turn this code into a one line code inside list (list comprehension). e.g., [here goes the new implementation]

def main():
    inp = input()
    x = []
    x_tm = ''
    for i in range( 0, len(inp)):
        if inp[i] == ',':
            x.append(x_tm)
            x_tm = ""
            continue
        if inp[i] ==" ":
            continue
        x_tm += inp[i]
    x.append(inp)

Body:
There is a built-in function called "split" that does what you wrote.

def main():
inp = input("Enter text: ").split(",")
print(inp)

If you want to write the function yourself it would look something like this:

def main():
inp = input("Enter text: ")
temp = ""
words = []
for ltr in inp:
    if ltr == ",":
        words.append(temp)
        temp = ""
    else:
        temp += ltr
if len(temp):
    words.append(temp)
print(words)


问:
Possible to have "mouseover for X seconds" functionality using jQuery?
I currently have several elements in a row that have a mouseover event that fires some animation.  My problem is that if someone mouses over several of the elements in quick succession the animation gets a little frantic.

I'm curious if there is a way to have a mouseover event that only fires if the mouse is over an element for a certain amount of time (say 250 milliseconds).  Can this be done with jQuery?

答:
I would suggest you use setTimeout for this:

```<code>(function ($) {
    var t;
    $('ul li').hover(function() {
        var that = this;
        window.clearTimeout(t);
        t = window.setTimeout(function () {
            $(that).animate({opacity: .5}, 'slow').animate({opacity: 1});
          }, 250);
    });
}(jQuery));
</code>```

If there are multiple items activated in rapid succession the timeout will override the timeout-id thus preventing the first item that should not start from animating.

It does not require any arcane plugin (although hoverIntent may provide some nice additional features you may want to use) and window.setTimeout is supported everywhere.

UPDATE

I updated the code sample to work.. was writing this from memory yesterday and didn't get the setTimeout call quite right.. Also see this jsFiddle for reference.

The issue I see with this is that it will execute the hover animation even if you leave the . So you could also add a $('ul').mouseleave(function() { window.clearTimeout(t) }); to prevent that.

greetings Daniel

ContentLicense: CC BY-SA 3.0

Body:
I would suggest you use setTimeout for this:

(function ($) {
    var t;
    $('ul li').hover(function() {
        var that = this;
        window.clearTimeout(t);
        t = window.setTimeout(function () {
            $(that).animate({opacity: .5}, 'slow').animate({opacity: 1});
          }, 250);
    });
}(jQuery));

If there are multiple items activated in rapid succession the timeout will override the timeout-id thus preventing the first item that should not start from animating.

It does not require any arcane plugin (although hoverIntent may provide some nice additional features you may want to use) and window.setTimeout is supported everywhere.

UPDATE

I updated the code sample to work.. was writing this from memory yesterday and didn't get the setTimeout call quite right.. Also see this jsFiddle for reference.

The issue I see with this is that it will execute the hover animation even if you leave the . So you could also add a $('ul').mouseleave(function() { window.clearTimeout(t) }); to prevent that.

greetings Daniel


问:
Want to write mongodb query that all the numbers that are not between particular range
Below query i have written to get range between 400 to 800

```<code>db.products.find({$and: [{price: {$gt: 400}}, {price: {$lt: 800}}]});
</code>```

But how to get values that are not between range of 400 to 800

```<code>db.products.find({$and: [{price: {$lt: 400}}, {price: {$gt: 800}}]});
</code>```

why above query not shown any result?

Thanks

答:
Simple $or will do the job:

(price cannot be <400 & >800 at the same time ,
but can be <400 or >800 at the same time)

```<code>db.collection.find({
  $or: [
    {
      "price": {
        $lt: 400
      }
    },
    {
      "price": {
        $gt: 800
      }
    }
  ]
})
</code>```

playground

Body:
Below query i have written to get range between 400 to 800

db.products.find({$and: [{price: {$gt: 400}}, {price: {$lt: 800}}]});

But how to get values that are not between range of 400 to 800

db.products.find({$and: [{price: {$lt: 400}}, {price: {$gt: 800}}]});

why above query not shown any result?

Thanks

Body:
Simple $or will do the job:

(price cannot be <400 & >800 at the same time ,
but can be <400 or >800 at the same time)

db.collection.find({
  $or: [
    {
      "price": {
        $lt: 400
      }
    },
    {
      "price": {
        $gt: 800
      }
    }
  ]
})

playground


问:
Understanding capture by reference in C++ lamdba functions
I thought I understood how capture by reference works in C++ until I faced this situation:

auto inrcrementer = []() {
    int counter = 0;
    return [&counter]() {
        return counter++;
    };
};

int main() {
    auto inc = inrcrementer();
    cout << inc() << ", " << inc() << ", " << inc() << ", " << endl;

    return 0;
}
```
<p>I was expecting this to return <code>0, 1, 2</code> but it returns <code>0, 32765, 32765</code>. Why?</p>
<p>Moreover, if I change it to this:</p>
<pre class="lang-cpp prettyprint-override"><code>auto inrcrementer = []() {
    int counter = 0;
    return [counter]() mutable {
        return counter++;
    };
};

int main() {
    auto inc = inrcrementer();
    cout << inc() << ", " << inc() << ", " << inc() << ", " << endl;

    return 0;
}
</code>```

It is fixed and it returns as expected. What is the difference between the two?

答:
After expanding the outer lambda, your first example can be written as sth like this:

```<code>struct incrementer
{
   auto operator()()
   {
     int counter = 0;
     return [&counter]() { return counter++;}
   }
};
</code>```

As it's become more visible now counter is a local variable and the inner lambda operates on a reference to local object, a dangling one at the call site.

The second example can be expanded to sth like this:

```<code>struct incrementer
{
   auto operator()()
   {
     int counter = 0;
     struct inner
     {
       inner(int cnt) : mcnt{cnt}();
       int operator()() { return mcnt++; }
       int mcnt;
     };
     return inner{counter};
   }
};
</code>```

Basically, the lifetime of the counter needs to be preserved for the entire lifetime of the lambda, one way or another.

Yet another way is to store the counter in the outer lambda, e.g.

```<code>auto inrcrementer = [counter=0]() mutable {
    return [&counter]()  {
        return counter++;
    };
};
</code>```

This is fine as long as the inner one does not outlive the outer one.

Body:
I thought I understood how capture by reference works in C++ until I faced this situation:

auto inrcrementer = []() {
    int counter = 0;
    return [&counter]() {
        return counter++;
    };
};

int main() {
    auto inc = inrcrementer();
    cout << inc() << ", " << inc() << ", " << inc() << ", " << endl;

    return 0;
}

I was expecting this to return 0, 1, 2 but it returns 0, 32765, 32765. Why?

Moreover, if I change it to this:

auto inrcrementer = []() {
    int counter = 0;
    return [counter]() mutable {
        return counter++;
    };
};

int main() {
    auto inc = inrcrementer();
    cout << inc() << ", " << inc() << ", " << inc() << ", " << endl;

    return 0;
}

It is fixed and it returns as expected. What is the difference between the two?

Body:
After expanding the outer lambda, your first example can be written as sth like this:

struct incrementer
{
   auto operator()()
   {
     int counter = 0;
     return [&counter]() { return counter++;}
   }
};

As it's become more visible now counter is a local variable and the inner lambda operates on a reference to local object, a dangling one at the call site.

The second example can be expanded to sth like this:

struct incrementer
{
   auto operator()()
   {
     int counter = 0;
     struct inner
     {
       inner(int cnt) : mcnt{cnt}();
       int operator()() { return mcnt++; }
       int mcnt;
     };
     return inner{counter};
   }
};

Basically, the lifetime of the counter needs to be preserved for the entire lifetime of the lambda, one way or another.

Yet another way is to store the counter in the outer lambda, e.g.

auto inrcrementer = [counter=0]() mutable {
    return [&counter]()  {
        return counter++;
    };
};

This is fine as long as the inner one does not outlive the outer one.


问:
Go Install Binary name
go build allow to precise binary name with the -o command line option.
go install doesn't, but it deploy the binary and cache package compilation.

How to either change the binary name with go install? or cache compilation with go build?

A simple answer would be "use go install with correct package name", but please, where is the option I am missing?

答:
In GO 1.6+ you can rename your main file to whatever you want.

Example :

mv main.go myApp.go

Then just run
go install myApp.go

Your myApp is ready to exec, and the location is in $GOROOT/bin

Title: Go Install Binary name


问:
.htaccess to beautify a url
There are several articles about this but I cannot make it work.

I have the following urls:

```<code> 1. /index.php
 2. /index.php?lg=el
 3. /index.php?lg=en
 4. /index.php?lg=el#anchor
 5. /index.php?lg=en#anchor
 6. /index.php?ct=1&lg=el
 7. /index.php?ct=1&lg=el#anchor
 8. /index.php?ct=1&lg=en
 9. /index.php?ct=1&lg=en#anchor
10. /index.php?ct=2&lg=el
11. /index.php?ct=2&lg=el#anchor
12. /index.php?ct=3&lg=el
13. /index.php?ct=3&lg=el#anchor
14. /index.php?ct=4&lg=el
15. /index.php?ct=4&lg=el#anchor
16. /index.php?ct=5&lg=el
17. /index.php?ct=5&lg=el#anchor
18. /index.php?ct=2&lg=en
19. /index.php?ct=2&lg=en#anchor
20. /index.php?ct=3&lg=en
21. /index.php?ct=3&lg=en#anchor
22. /index.php?ct=4&lg=en
23. /index.php?ct=4&lg=en#anchor
24. /index.php?ct=5&lg=en
25. /index.php?ct=5&lg=en#anchor
</code>```

and similar ones without the "index.php".
The "ct" variable should be converted based on the following array (index from 1):

```<code>[company,history,news,measurements,contact]
</code>```

I want to convert them to:

```<code> 1. /
 2. /el
 3. /en
 4. /el#anchor
 5. /en#anchor
 6. /el/company
 7. /el/company#anchor
 8. /en/company
 9. /en/company#anchor
10. /el/history
11. /el/history#anchor
12. /el/news
13. /el/news#anchor
14. /el/measurements
15. /el/measurements#anchor
16. /el/contact
17. /el/contact#anchor
18. /en/history
19. /en/history#anchor
20. /en/news
21. /en/news#anchor
22. /en/measurements
23. /en/measurements#anchor
24. /en/contact
25. /en/contact#anchor
</code>```

I have tried the following syntax in .htaccess:

```<code>RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(\/)?([a-z]{2})?(\/)?((?:company|history|news|measurements|contact))?(#[\w\-]+)?$ $1index.php?ct=$4&lg=$2$5 [L,QSA]
</code>```

but I cannot get the expected result.

Any ideas?

答:
```<code>6. /el/company
7. /el/company#anchor
</code>```

The #anchor (aka. the fragment identifier) is not passed to the server, so it's not part of the URL rewriting process. #anchor is used by the client-side code and it is present on the client-side URL, so there is nothing to do in this respect. So, #6 and #7 (and other similar URLs) are in fact "the same" as regards the server request.

The trick is converting the 2nd path segment into a number 1..5, which you don't appear to be doing in your attempt.

If you are OK with the ct URL parameter always being present (except on requests for the root), but empty when not required (ie. ct=), rather than being totally absent, then you could do it like the following in a single rule:

```<code>DirectoryIndex index.php

RewriteEngine On

# HTTP to HTTPS redirect
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Rewrite "pretty" URL
RewriteCond 1$2 ^(\d)company [OR]
RewriteCond 2$2 ^(\d)history [OR]
RewriteCond 3$2 ^(\d)news [OR]
RewriteCond 4$2 ^(\d)measurements [OR]
RewriteCond 5$2 ^(\d)contact [OR]
RewriteCond $2 ^$
RewriteRule ^(el|en)(?:/(company|history|news|measurements|contact))?$ index.php?ct=%1&lg=$1 [L]
</code>```

Since you only appear to have two languages I've used simple alternation to match just these two. ie. (el|en). If you do have many language codes then consider changing this to [a-z]{2} instead. However, it is preferable to be specific and list the languages to avoid potential conflicts.

There's no need for the filesystem check (to check that the request does not map to a file) since you don't have files of the form /en/contact. If you did then the rewrite would not be possible with the filesystem check anyway.

The RewriteBase directive is not required here.

The "number" (array index) that the 2nd path segment corresponds to is captured from the preceding RewriteCond directives and this is available later in the substitution string using the %1 backreference.

The above rule(s) will rewrite the request as follows (very close to your examples):

/ -> index.php (by mod_dir, no URL parameters)

/el -> index.php?ct=&lg=el (ct parameter is empty)

/el/ (with a trailing slash) - no rewrite

/el/company -> index.php?ct=1&lg=el

/en/contact -> index.php?ct=5&lg=en

/ab - no rewrite (unrecognised language code)

/en/contacts - no rewrite (2nd path segment not recognised)

and similar ones without the "index.php".

Although, going forward, the rewritten URL should always contain index.php.

I want to convert them to:

To clarify, this rule rewrites the "pretty" URL back to the underlying URL that your application understands. It doesn't physically change the URLs used in your application - you must manually change the URLs in your HTML source to be the new "pretty" URLs.

If, however, you are changing an existing URL structure that has already been indexed by search engines and possibly linked to by third parties then you should consider also implementing an external redirect from the old URL to the new "pretty" URL in order to preserve SEO. But this is not necessary for your application to work with the new "pretty" URLs.

Title: .htaccess to beautify a url

Body:
There are several articles about this but I cannot make it work.

I have the following urls:

 1. /index.php
 2. /index.php?lg=el
 3. /index.php?lg=en
 4. /index.php?lg=el#anchor
 5. /index.php?lg=en#anchor
 6. /index.php?ct=1&lg=el
 7. /index.php?ct=1&lg=el#anchor
 8. /index.php?ct=1&lg=en
 9. /index.php?ct=1&lg=en#anchor
10. /index.php?ct=2&lg=el
11. /index.php?ct=2&lg=el#anchor
12. /index.php?ct=3&lg=el
13. /index.php?ct=3&lg=el#anchor
14. /index.php?ct=4&lg=el
15. /index.php?ct=4&lg=el#anchor
16. /index.php?ct=5&lg=el
17. /index.php?ct=5&lg=el#anchor
18. /index.php?ct=2&lg=en
19. /index.php?ct=2&lg=en#anchor
20. /index.php?ct=3&lg=en
21. /index.php?ct=3&lg=en#anchor
22. /index.php?ct=4&lg=en
23. /index.php?ct=4&lg=en#anchor
24. /index.php?ct=5&lg=en
25. /index.php?ct=5&lg=en#anchor

and similar ones without the "index.php".
The "ct" variable should be converted based on the following array (index from 1):

[company,history,news,measurements,contact]

I want to convert them to:

 1. /
 2. /el
 3. /en
 4. /el#anchor
 5. /en#anchor
 6. /el/company
 7. /el/company#anchor
 8. /en/company
 9. /en/company#anchor
10. /el/history
11. /el/history#anchor
12. /el/news
13. /el/news#anchor
14. /el/measurements
15. /el/measurements#anchor
16. /el/contact
17. /el/contact#anchor
18. /en/history
19. /en/history#anchor
20. /en/news
21. /en/news#anchor
22. /en/measurements
23. /en/measurements#anchor
24. /en/contact
25. /en/contact#anchor

I have tried the following syntax in .htaccess:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(\/)?([a-z]{2})?(\/)?((?:company|history|news|measurements|contact))?(#[\w\-]+)?$ $1index.php?ct=$4&lg=$2$5 [L,QSA]

but I cannot get the expected result.

Any ideas?

Body:
6. /el/company
7. /el/company#anchor

The #anchor (aka. the fragment identifier) is not passed to the server, so it's not part of the URL rewriting process. #anchor is used by the client-side code and it is present on the client-side URL, so there is nothing to do in this respect. So, #6 and #7 (and other similar URLs) are in fact "the same" as regards the server request.

The trick is converting the 2nd path segment into a number 1..5, which you don't appear to be doing in your attempt.

If you are OK with the ct URL parameter always being present (except on requests for the root), but empty when not required (ie. ct=), rather than being totally absent, then you could do it like the following in a single rule:

DirectoryIndex index.php

RewriteEngine On

# HTTP to HTTPS redirect
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Rewrite "pretty" URL
RewriteCond 1$2 ^(\d)company [OR]
RewriteCond 2$2 ^(\d)history [OR]
RewriteCond 3$2 ^(\d)news [OR]
RewriteCond 4$2 ^(\d)measurements [OR]
RewriteCond 5$2 ^(\d)contact [OR]
RewriteCond $2 ^$
RewriteRule ^(el|en)(?:/(company|history|news|measurements|contact))?$ index.php?ct=%1&lg=$1 [L]

Since you only appear to have two languages I've used simple alternation to match just these two. ie. (el|en). If you do have many language codes then consider changing this to [a-z]{2} instead. However, it is preferable to be specific and list the languages to avoid potential conflicts.

There's no need for the filesystem check (to check that the request does not map to a file) since you don't have files of the form /en/contact. If you did then the rewrite would not be possible with the filesystem check anyway.

The RewriteBase directive is not required here.

The "number" (array index) that the 2nd path segment corresponds to is captured from the preceding RewriteCond directives and this is available later in the substitution string using the %1 backreference.

The above rule(s) will rewrite the request as follows (very close to your examples):

/ -> index.php (by mod_dir, no URL parameters)

/el -> index.php?ct=&lg=el (ct parameter is empty)

/el/ (with a trailing slash) - no rewrite

/el/company -> index.php?ct=1&lg=el

/en/contact -> index.php?ct=5&lg=en

/ab - no rewrite (unrecognised language code)

/en/contacts - no rewrite (2nd path segment not recognised)

and similar ones without the "index.php".

Although, going forward, the rewritten URL should always contain index.php.

I want to convert them to:

To clarify, this rule rewrites the "pretty" URL back to the underlying URL that your application understands. It doesn't physically change the URLs used in your application - you must manually change the URLs in your HTML source to be the new "pretty" URLs.

If, however, you are changing an existing URL structure that has already been indexed by search engines and possibly linked to by third parties then you should consider also implementing an external redirect from the old URL to the new "pretty" URL in order to preserve SEO. But this is not necessary for your application to work with the new "pretty" URLs.


问:
Uncaught (in promise) TypeError: dispatch is not a function useContext/useReducer
I am new to react. I am working on a blogging website in which I need to create a login page. I am facing the following error:

TypeError: dispatch is not a function

Following is my code to handle submit and request to the API. I am getting

```<code>const { dispatch, isFetching } = useContext(Context);
const handleSubmit = async (e) => {
    e.preventDefault();
    dispatch({ type: "LOGIN_START" });
    try {
      const res = await axios.post("http://localhost:5001/api/auth/login", {
        username: userRef.current.value,
        password: passwordRef.current.value,
      });
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "LOGIN_FAILURE" });
    }
  };
</code>```

Following is my code of the form:

```<code>return (
    <div className="login">
      <span className="loginTitle">Login</span>
      <form className="loginForm" onSubmit={(e) => handleSubmit(e)}>
        <label>Username</label>
        <input
          type="text"
          className="loginInput"
          placeholder="Enter your username..."
          ref={userRef}
        />
        <label>Password</label>
        <input
          type="password"
          className="loginInput"
          placeholder="Enter your password..."
          ref={passwordRef}
        />
        <button className="loginButton" type="submit" disabled={isFetching}>
          Login
        </button>
      </form>
      <button className="loginRegisterButton">
        <Link className="link" to="/register">
          Register
        </Link>
      </button>
    </div>
  );
</code>```

Following is the Context Provider

```<code>import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);

export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};
</code>```

Following is my app.js with all the root nodes in it

```<code>import Home from "./Pages/home/Home";
import TopBar from "./components/topbar/TopBar";
import Single from "./Pages/single/Single";
import Write from "./Pages/write/Write";
import Settings from "./Pages/settings/Settings";
import Login from "./Pages/login/Login";
import Register from "./Pages/register/Register";
import { useContext } from "react";
import { Context } from "./context/Context";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  BrowserRouter
} from "react-router-dom"

function App() {
  const { user } = useContext(Context);
  return (
    <BrowserRouter >
      <TopBar />
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="register" element={user ? <Home /> : <Register />} />
        <Route path="login" element={ user ? <Home /> : <Login />} />
        <Route path="write" element={user ? <Write /> : <Register />} />
        <Route path="settings" element={user ? <Settings /> : <Register />} />
        <Route path="post/:postId" element={<Single />} />
      </Routes>
    </BrowserRouter >
  );
}

export default App;
</code>```

Can somebody please help me out with this.

答:
You are apparently getting the default value from the context, and your default value does not have a dispatch function. For context to work, there must be a context provider higher up the component tree than the component that's trying to consume context.

You are either not rendering a ContextProvider at all, or you are rendering it in the wrong part of the component tree.

For example, the following will work:

```<code>const App = () => {
  return (
    <ContextProvider>
      <MyForm />
    <ContextProvider>
  )
}

const MyForm = () => {
  const { dispatch, isFetching } = useContext(Context);
  const handleSubmit = async (e) => {
     // ...
  }

  return (
    <div className="login">
      // ...
    </div>
  )
}
</code>```

But this will not (the provider is a child of the consumer):

```<code>const MyForm = () => {
  const { dispatch, isFetching } = useContext(Context);
  const handleSubmit = async (e) => {
     // ...
  }

  return (
    <ContextProvider>
      <div className="login">
        // ...
      </div>
    </ContextProvider>
  )
}
</code>```

And neither will this (the provider exists, but isn't an ancestor of MyForm)

```<code>const App = () => {
  return (
    <div>
      <MyForm />
      <ContextProvider />
    </div>
  )
}
</code>```

Body:
I am new to react. I am working on a blogging website in which I need to create a login page. I am facing the following error:

TypeError: dispatch is not a function

Following is my code to handle submit and request to the API. I am getting

const { dispatch, isFetching } = useContext(Context);
const handleSubmit = async (e) => {
    e.preventDefault();
    dispatch({ type: "LOGIN_START" });
    try {
      const res = await axios.post("http://localhost:5001/api/auth/login", {
        username: userRef.current.value,
        password: passwordRef.current.value,
      });
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "LOGIN_FAILURE" });
    }
  };

Following is my code of the form:

return (

      Login
      <form className="loginForm" onSubmit={(e) => handleSubmit(e)}>
        Username
        <input
          type="text"
          className="loginInput"
          placeholder="Enter your username..."
          ref={userRef}
        />
        Password
        <input
          type="password"
          className="loginInput"
          placeholder="Enter your password..."
          ref={passwordRef}
        />
        <button className="loginButton" type="submit" disabled={isFetching}>
          Login
        </button>
      </form>
      <button className="loginRegisterButton">
        <Link className="link" to="/register">
          Register
        </Link>
      </button>

  );

Following is the Context Provider

import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);

export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

Following is my app.js with all the root nodes in it

import Home from "./Pages/home/Home";
import TopBar from "./components/topbar/TopBar";
import Single from "./Pages/single/Single";
import Write from "./Pages/write/Write";
import Settings from "./Pages/settings/Settings";
import Login from "./Pages/login/Login";
import Register from "./Pages/register/Register";
import { useContext } from "react";
import { Context } from "./context/Context";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  BrowserRouter
} from "react-router-dom"

function App() {
  const { user } = useContext(Context);
  return (
    <BrowserRouter >
      <TopBar />
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="register" element={user ? <Home /> : <Register />} />
        <Route path="login" element={ user ? <Home /> : <Login />} />
        <Route path="write" element={user ? <Write /> : <Register />} />
        <Route path="settings" element={user ? <Settings /> : <Register />} />
        <Route path="post/:postId" element={<Single />} />
      </Routes>
    </BrowserRouter >
  );
}

export default App;

Can somebody please help me out with this.

Body:
You are apparently getting the default value from the context, and your default value does not have a dispatch function. For context to work, there must be a context provider higher up the component tree than the component that's trying to consume context.

You are either not rendering a ContextProvider at all, or you are rendering it in the wrong part of the component tree.

For example, the following will work:

const App = () => {
  return (
    <ContextProvider>
      <MyForm />
    <ContextProvider>
  )
}

const MyForm = () => {
  const { dispatch, isFetching } = useContext(Context);
  const handleSubmit = async (e) => {
     // ...
  }

  return (
    <div className="login">
      // ...
    </div>
  )
}

But this will not (the provider is a child of the consumer):

const MyForm = () => {
  const { dispatch, isFetching } = useContext(Context);
  const handleSubmit = async (e) => {
     // ...
  }

  return (
    <ContextProvider>
      <div className="login">
        // ...
      </div>
    </ContextProvider>
  )
}

And neither will this (the provider exists, but isn't an ancestor of MyForm)

const App = () => {
  return (
    <div>
      <MyForm />
      <ContextProvider />
    </div>
  )
}


问:
Java Streams; avoid finisher on Collectors.collectingAndThen
I've this code:

private Iterable<Practitioner> pickPractitioners(List<String> ids) {

    return Optional.ofNullable(ids)
        .map(List::stream)
        .orElse(Stream.of())
        .collect(
            Collectors.collectingAndThen(
                Collectors.toList(),
                this.practitionerRepository::findAllById
            )
        );

}
```

Problem is that when ids is empty, this.practitionerRepository::findAllById is also executed.

I'd like to avoid this step if resulting collector is empty.

Any ideas?

答:
Whilst the practical part of this question (how to avoid interrogating the repository with an empty list as an argument) is already addressed in other answers I want to point out that there's a cleaner way to build a pipeline in this method.

Firstly it's worthy to remind that the main purpose of Optional.ofNullable() is to create an Optional object that has to be returned from a method.

Attempts to use Optional.ofNullable() in order to utilize method-chaining or to avoid null-checks in the middle of the method according to Stuart Marks are considered to be anti-patterns.

Here is the quote from his talk at Devoxx:

"it's generally a bad idea to create an Optional for the specific
purpose of chaining methods from it to get a value."

A similar idea was expressed in his answer on stackoverflow.

What are the alternatives?

Since Java 9 Stream interface has its own method ofNullable().

Returns a sequential Stream containing a single element, if non-null,
otherwise returns an empty Stream.

Keeping all that in mind method pickPractitioners() could be rewritten like this:

```<code>private Function<List<String>, Iterable<Practitioner>> getPractitioners =
        idList -> idList.isEmpty() ? Collections.emptyList() :
                                     this.practitionerRepository.findAllById(idList);

private Iterable<Practitioner> pickPractitioners(List<String> ids) {

    return Stream.ofNullable(ids)
            .flatMap(List::stream)
            .collect(Collectors.collectingAndThen(
                            Collectors.toList(),
                            getPractitioners
            ));
}
</code>```

Body:
I've this code:

private Iterable<Practitioner> pickPractitioners(List<String> ids) {

    return Optional.ofNullable(ids)
        .map(List::stream)
        .orElse(Stream.of())
        .collect(
            Collectors.collectingAndThen(
                Collectors.toList(),
                this.practitionerRepository::findAllById
            )
        );

}

Problem is that when ids is empty, this.practitionerRepository::findAllById is also executed.

I'd like to avoid this step if resulting collector is empty.

Any ideas?

Body:
Whilst the practical part of this question (how to avoid interrogating the repository with an empty list as an argument) is already addressed in other answers I want to point out that there's a cleaner way to build a pipeline in this method.

Firstly it's worthy to remind that the main purpose of Optional.ofNullable() is to create an Optional object that has to be returned from a method.

Attempts to use Optional.ofNullable() in order to utilize method-chaining or to avoid null-checks in the middle of the method according to Stuart Marks are considered to be anti-patterns.

Here is the quote from his talk at Devoxx:

"it's generally a bad idea to create an Optional for the specific
purpose of chaining methods from it to get a value."

A similar idea was expressed in his answer on stackoverflow.

What are the alternatives?

Since Java 9 Stream interface has its own method ofNullable().

Returns a sequential Stream containing a single element, if non-null,
otherwise returns an empty Stream.

Keeping all that in mind method pickPractitioners() could be rewritten like this:

private Function<List<String>, Iterable<Practitioner>> getPractitioners =
        idList -> idList.isEmpty() ? Collections.emptyList() :
                                     this.practitionerRepository.findAllById(idList);

private Iterable<Practitioner> pickPractitioners(List<String> ids) {

    return Stream.ofNullable(ids)
            .flatMap(List::stream)
            .collect(Collectors.collectingAndThen(
                            Collectors.toList(),
                            getPractitioners
            ));
}


问:
d3 - disable scrolling when zooming with mouse wheel?
I am using the code from the Brush & Zoom line chart block.

What I notice, though, is that if the graph is fully zoomed out (like it is when originally viewing the graph) and I place my mouse cursor over the graph and spin the mouse wheel down (which would normally zoom out), it scrolls the browser window down.

Is there a way in d3 to basically say, "Anytime the mouse is over the SVG, wheel scrolling should NOT scroll the browser window?"

答: You may try to set overscroll-behavior to "none" on svg. It is supported in Chrome/Edge/Firefox, but unfortunately not on Safari.</p>


问:
The Favicon is not showing on my wordpress website especially on Chrome
I have uploaded the favicon on my wordpress website but it is not showing on chrome. http://babygearsmalaysia.com

Can anyone help me please?

答: This is to be configured inside the Customizer theme.</p>


问:
Is there an opportunity to get the index of an specific array by the the UUID and then add something to it? [Swift UI]
so i am working on a Project in Xcode and I need help. I am kinda new to Swift and I need to get the Index of a Item in a Array by the UUID, so here is some Code:

```<code>struct Group: Identifiable {
    let id =  UUID()
    var name: String
    var members: Array<Member>
}
</code>```
```<code>@State var groupIndex: Int = 0

var tgroup: Group

// in the body:

ForEach(Array(groups.enumerated()), id: \.1.id) { (index, textItem) in
    if groups[index].id == tgroup.id {
        Text(String(index)) // and I need this index to be the groupIndex var
        ...
    }
</code>```

but in the Body I am not allowed to change a var, how can I get this index? At the end I want to add something to the same Array.

Thank You!

答:
there is no need/meaning to try to get the index in the ForEach loop.
To get the index of tgroup inside groups, just do this:

```<code>func getGroupIndex() -> Int? {
    return groups.firstIndex(where: {$0.id == tgroup.id})
}
</code>```

and do not put this in the ForEach loop, keep using:

```<code>ForEach(Array(groups.enumerated()), id: \.1.id) { (index, textItem) in
    if textItem.id == tgroup.id {
        Text(String(index)) // and I need this index to be the groupIndex var
    }
}
</code>```

EDIT-1: here is the code I used for testing

```<code>struct Group: Identifiable {
    let id =  UUID()
    var name: String
    var members: Array<String> // <-- for testing
}

struct GroupIndexView: View {
    @State var groups: [Group]
    var tgroup: Group

    @State var groupIndex: Int = 0

    var body: some View {
        ForEach(Array(groups.enumerated()), id: \.1.id) { (index, textItem) in
            if groupIndex == index {  // <--- here
                Text(String(index)) // and I need this index to be the groupIndex var
            }
        }
        .onAppear {
            if let ndx = getGroupIndex(of: tgroup) {
                groupIndex = ndx
            }
            print("---> groupIndex: \(groupIndex)")
        }
    }

    func getGroupIndex(of group: Group) -> Int? {
        return groups.firstIndex(where: {$0.id == group.id})
    }

}

struct ContentView: View {
    @State var groups: [Group] = [Group(name: "name-1", members: []), Group(name: "name-2", members: [])]

    var body: some View {
        GroupIndexView(groups: groups, tgroup: groups[1])
    }
}
</code>```

Body:
so i am working on a Project in Xcode and I need help. I am kinda new to Swift and I need to get the Index of a Item in a Array by the UUID, so here is some Code:

struct Group: Identifiable {
    let id =  UUID()
    var name: String
    var members: Array<Member>
}

@State var groupIndex: Int = 0

var tgroup: Group

// in the body:

ForEach(Array(groups.enumerated()), id: \.1.id) { (index, textItem) in
    if groups[index].id == tgroup.id {
        Text(String(index)) // and I need this index to be the groupIndex var
        ...
    }

but in the Body I am not allowed to change a var, how can I get this index? At the end I want to add something to the same Array.

Thank You!

Body:
there is no need/meaning to try to get the index in the ForEach loop.
To get the index of tgroup inside groups, just do this:

func getGroupIndex() -> Int? {
    return groups.firstIndex(where: {$0.id == tgroup.id})
}

and do not put this in the ForEach loop, keep using:

ForEach(Array(groups.enumerated()), id: \.1.id) { (index, textItem) in
    if textItem.id == tgroup.id {
        Text(String(index)) // and I need this index to be the groupIndex var
    }
}

EDIT-1: here is the code I used for testing

struct Group: Identifiable {
    let id =  UUID()
    var name: String
    var members: Array<String> // <-- for testing
}

struct GroupIndexView: View {
    @State var groups: [Group]
    var tgroup: Group

    @State var groupIndex: Int = 0

    var body: some View {
        ForEach(Array(groups.enumerated()), id: \.1.id) { (index, textItem) in
            if groupIndex == index {  // <--- here
                Text(String(index)) // and I need this index to be the groupIndex var
            }
        }
        .onAppear {
            if let ndx = getGroupIndex(of: tgroup) {
                groupIndex = ndx
            }
            print("---> groupIndex: \(groupIndex)")
        }
    }

    func getGroupIndex(of group: Group) -> Int? {
        return groups.firstIndex(where: {$0.id == group.id})
    }

}

struct ContentView: View {
    @State var groups: [Group] = [Group(name: "name-1", members: []), Group(name: "name-2", members: [])]

    var body: some View {
        GroupIndexView(groups: groups, tgroup: groups[1])
    }
}


问:
SwiftUI: @State variable never get updated from @Published
I'm trying to trigger an alert when is an error in the model but it never get updated to show the alert:

Here is my implementation in the view:

```<code>struct ContentView: View {
    @ObservedObject var viewModel: ViewModel
    @State var showAlert = false
    init() {
        viewModel = ViewModel()
        showAlert = viewModel.showAlert
    }
    var body: some View {
        NavigationView {
            Text("Hello, world!")
                .padding()
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("This works"),
                  message: Text("Hello"),
                  dismissButton: .default(Text("got it"))
        )}
    }
}
</code>```

Here is my models:

```<code>class ViewModel: ObservableObject {
    @Published var showAlert = false
    var cancellables = Set<AnyCancellable>()

    init() {
        DoSomething.shared.showAlert.sink { _ in
            print("got new Value")
        } receiveValue: {[weak self] value in
            print("value")
            self?.showAlert = value
        }.store(in: &cancellables)
    }
}
class DoSomething {
    let showAlert = PassthroughSubject<Bool, Never>()
    static let shared = DoSomething()
    private init() {
        checkToShowAlert()
    }
    func checkToShowAlert() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
            print("change value")
            self?.showAlert.send(true)
        }
    }
}
</code>```

Any of you knows why the showAlert variable it never gets updated?

I'll really appreciate your help

答:
Best remove the view model object, we don't need those in SwiftUI because the View struct holds the view data and the @State and @Binding property wrappers make the struct behave like an object.

Also, I don't think you need Combine for what you are trying to do because you aren't combining anything using combineLatest etc, but when we do use it in SwiftUI we don't use sink or store, instead we assign the end of the pipeline to an @Published.

Example:

```<code>struct ContentView: View {
    @State var isPresented = false

    var body: some View {
        NavigationView {
            VStack{
                Text("Hello, world!")
                  .padding()
                Button("Show Alert") {
                    showAlert()
                 }
            }
        }
        .alert(isPresented: $isPresented) {
            Alert(title:Text("This works"),
                  message: Text("Hello"),
                  dismissButton: .default(Text("got it"))
        )}
    }

    func showAlert() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            isPresented = true
        }
    }
}
</code>```

Body:
I'm trying to trigger an alert when is an error in the model but it never get updated to show the alert:

Here is my implementation in the view:

struct ContentView: View {
    @ObservedObject var viewModel: ViewModel
    @State var showAlert = false
    init() {
        viewModel = ViewModel()
        showAlert = viewModel.showAlert
    }
    var body: some View {
        NavigationView {
            Text("Hello, world!")
                .padding()
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("This works"),
                  message: Text("Hello"),
                  dismissButton: .default(Text("got it"))
        )}
    }
}

Here is my models:

class ViewModel: ObservableObject {
    @Published var showAlert = false
    var cancellables = Set<AnyCancellable>()

    init() {
        DoSomething.shared.showAlert.sink { _ in
            print("got new Value")
        } receiveValue: {[weak self] value in
            print("value")
            self?.showAlert = value
        }.store(in: &cancellables)
    }
}
class DoSomething {
    let showAlert = PassthroughSubject<Bool, Never>()
    static let shared = DoSomething()
    private init() {
        checkToShowAlert()
    }
    func checkToShowAlert() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
            print("change value")
            self?.showAlert.send(true)
        }
    }
}

Any of you knows why the showAlert variable it never gets updated?

I'll really appreciate your help

Body:
Best remove the view model object, we don't need those in SwiftUI because the View struct holds the view data and the @State and @Binding property wrappers make the struct behave like an object.

Also, I don't think you need Combine for what you are trying to do because you aren't combining anything using combineLatest etc, but when we do use it in SwiftUI we don't use sink or store, instead we assign the end of the pipeline to an @Published.

Example:

struct ContentView: View {
    @State var isPresented = false

    var body: some View {
        NavigationView {
            VStack{
                Text("Hello, world!")
                  .padding()
                Button("Show Alert") {
                    showAlert()
                 }
            }
        }
        .alert(isPresented: $isPresented) {
            Alert(title:Text("This works"),
                  message: Text("Hello"),
                  dismissButton: .default(Text("got it"))
        )}
    }

    func showAlert() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            isPresented = true
        }
    }
}


问:
Teams: Can I have access to my Files (Sharepoint) using resource-specific consent permissions?
We have a published app in the Teams App Store.

We want to let the bot to have access to Teams Files. This is possible using Graph Application Permissions.
But there's a small problem, the "Files.Read.All" and "Files.ReadWrite.All" seems like overkill to our clients and they are not going to let us access all SharePoint resources just to upload a file into Teams Directory.

Resource-specific consent looks like a solution for our purposes.
However, after checking the documentation and samples we've found out that there are no "Files.ReadWrite.Group" and "Sites.ReadWrite.Group" resource-specific consent permissions.
Despite that, we tried to add them but got an error during the app installation process.

When we're requesting the channel information from graph api using resource-specific consent permissions we get:

```<code>{
    ...
    "filesFolderWebUrl": "https://example.sharepoint.com/sites/RSC/Shared Documents/General",
    ...
}
</code>```

If we try to request GET {filesFolderWebUrl} with auth token we get 401 UNAUTHORIZED.
We also tried to use https://example.sharepoint.com/_api/ and it fails with:

```<code>{
    "error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."
}
</code>```

The GET https://graph.microsoft.com/beta/sites/ request returns blank response:

```<code>{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#sites",
    "value": []
}
</code>```

Is there a way to get access to Teams Files using resource-specific consent? Any help would be appreciated.

答:
There are some new graph scopes (preview) you could try:

Files.Read.Selected - allows read access to files user can select.

Files.ReadWrite.Selected - allows read/write access to files user can select

Files.ReadWrite.AppFolder - allows access to files in the "app folder". This one looks promising in your case.

These are new, and in "preview" state at the moment of writing, but already available for the apps. Disclaimer: I have not tried them myself yet, just discovered recently.

Body:
We have a published app in the Teams App Store.

We want to let the bot to have access to Teams Files. This is possible using Graph Application Permissions.
But there's a small problem, the "Files.Read.All" and "Files.ReadWrite.All" seems like overkill to our clients and they are not going to let us access all SharePoint resources just to upload a file into Teams Directory.

Resource-specific consent looks like a solution for our purposes.
However, after checking the documentation and samples we've found out that there are no "Files.ReadWrite.Group" and "Sites.ReadWrite.Group" resource-specific consent permissions.
Despite that, we tried to add them but got an error during the app installation process.

When we're requesting the channel information from graph api using resource-specific consent permissions we get:

{
    ...
    "filesFolderWebUrl": "https://example.sharepoint.com/sites/RSC/Shared Documents/General",
    ...
}

If we try to request GET {filesFolderWebUrl} with auth token we get 401 UNAUTHORIZED.
We also tried to use https://example.sharepoint.com/_api/ and it fails with:

{
    "error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."
}

The GET https://graph.microsoft.com/beta/sites/ request returns blank response:

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#sites",
    "value": []
}

Is there a way to get access to Teams Files using resource-specific consent? Any help would be appreciated.


问:
How to create a subclass in python that is inherited from turtle Module
So, i'm trying to learn python and every time i post a question here it feels like giving in...

I'm trying to make my own class of turtle.Turtle.

```<code>    import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""
    def __init__(self):
        pass

my_turtle = TurtleGTX()
my_turtle.forward(10)
</code>```

Gives the Traceback: AttributeError: 'TurtleGTX' object has no attribute '_position'. Which I then learn  is a "private vairable" which according to the offical python tutorial i can mangle/override in my subclass TurtleGTX. How to do this with a program as large as turtle seems rather difficult and implies i'm missing a simpler solution to the problem. In the end i learned and that was the point but i would still like to run it by the community to see if there is a elegant way to create a subclass of turtle.Turtle. (The next step is to have your turtle behave different then the standard turtle)

So a comment below made me think that maybe i could do this:

```<code>import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""

my_turtle = TurtleGTX()
my_turtle.forward(100)
</code>```

which actual runs! Now i'm going to see where that leads me... something tells me that i might have gone 1 step forward two step back as this means i won't be able to initialize anything on my subclass...

答:
It's a tempting pattern to subclass Turtle and add custom functionality, say, turtle.jump(). But I've seen a good deal of problems caused by this pattern and caution against it.

Calling the Turtle() initializer (including subclasses of Turtle) registers the object with the turtle module's internal list of turtles. This list has _update() called on it per frame if you don't disable the internal update loop with turtle.tracer(0). This internal turtle isn't likely to get garbage collected as your subclass might expect.

In addition to the update/draw internals they're hooked into, Turtle has many properties and methods that can easily name clash with your custom properties and methods (there are about 150 such names in the turtle module, not counting dunderscores). When calling, say, self.left(), it can be hard to remember if this is a turtle method call on the superclass or your derived class. By composing the turtle as a property rather than a subclass, self.turtle.left() makes the ownership completely clear, at the cost of a bit of verbosity.

Here's a collection of alternatives to inheritance, some of which are only useful for specific purposes but listed here anyway for completeness:

If you don't mind the turtles not being garbage collected (you are making a fixed amount that you plan to keep around), you could allocate instances of a custom class, each of which has an internal self.turtle = Turtle() instance that is manipulated in the normal way from the wrapper. This is the composition approach.

Since you're probably only using a handful of turtle methods, you can compromise a bit and add a self.left(n) method on your composed class and delegate to the underlying self.turtle.left(n). This involves adding a few extra methods but avoids all of the pitfalls of inheritance.

Instead of classes, you could make Turtle instances and pass them to functions that cause them to take an action in a C-style imperative manner: def jump(turtle, height): ....

If you plan to create particles of some sort that are created and destroyed relatively frequently and you just need a turtle to render rather than represent them, you might store the particles' internal representations and physics properties in a class alongside a reference to a single "pen" turtle. When drawing is needed, tracing is disabled and the turtle is moved from one position to the next among all shared particles, drawing as needed.

In theory, this is a great solution, but in practice, I've found it to be too much of a performance impact to bear, even with tracer off.

Custom classes can borrow from an object pool of turtles, helping to mitigate the garbage collection problem. See Why is my Python Turtle program slowing down drastically the longer it runs? for details.

That said, I'd be eager to see a useful, non-trivial case of the subclassing pattern if anyone has one as a counterargument.

Body:
So, i'm trying to learn python and every time i post a question here it feels like giving in...

I'm trying to make my own class of turtle.Turtle.

    import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""
    def __init__(self):
        pass

my_turtle = TurtleGTX()
my_turtle.forward(10)

Gives the Traceback: AttributeError: 'TurtleGTX' object has no attribute '_position'. Which I then learn  is a "private vairable" which according to the offical python tutorial i can mangle/override in my subclass TurtleGTX. How to do this with a program as large as turtle seems rather difficult and implies i'm missing a simpler solution to the problem. In the end i learned and that was the point but i would still like to run it by the community to see if there is a elegant way to create a subclass of turtle.Turtle. (The next step is to have your turtle behave different then the standard turtle)

So a comment below made me think that maybe i could do this:

import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""

my_turtle = TurtleGTX()
my_turtle.forward(100)

which actual runs! Now i'm going to see where that leads me... something tells me that i might have gone 1 step forward two step back as this means i won't be able to initialize anything on my subclass...


问:
Obtaining context information in Spring 3.0 Exception Handlers
I am attempting to set-up a scheme for uniformly handling exceptions in Spring.  As such, I need a way to pass context information into an @ExceptionHandler-annotated method, for example consider the following:

```<code>@ExceptionHandler(Exception.class)
public void handleException(Exception ex, HttpServletRequest request) {
    // Need access to myContext from login()
}

@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(HttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
    ...
    myContext = "Some contextual information"
    ...
    i_will_always_throw_an_exception();
}
</code>```

Since Spring is responsible for translating a thrown exception into an invocation of handleException(), I am having difficulty trying to find a way to pass myContext to the handler.  One thought I have is creating a subclass of HttpServletRequest.  If that approach works I would have code like this:

```<code>@ExceptionHandler(Exception.class)
public void handleException(Exception ex, MyCustomHttpServletRequest request) {
    // I now have access to the context via the following
    String myContext = request.getContext();
}

@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(MyCustomHttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
    ...
    myContext = "Some contextual information"
    request.setContext(myContext);
    ...
    i_will_always_throw_an_exception();
}
</code>```

But, if I follow this approach, how do I properly use my own arbitrary sub-class of HttpServletRequest to make this work?

答:
Can't you just put it into exception (if necessary - wrapping the original exception with the new one)?

```<code>@ExceptionHandler(MyContextualException.class)
public void handleException(MyContextualException ex) {
    // Need access to myContext from login()
}

@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(HttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
    ...
    myContext = "Some contextual information"
    ...
    try {
        i_will_always_throw_an_exception();
    } catch (Exception ex) {
        throw new MyContextualException(myContext, ex);
    }
}
</code>```

An alternative approach is to pass the context as a request attribute:

```<code>request.setAttribute("myContext", myContext);
</code>```

Body:
I am attempting to set-up a scheme for uniformly handling exceptions in Spring.  As such, I need a way to pass context information into an @ExceptionHandler-annotated method, for example consider the following:

@ExceptionHandler(Exception.class)
public void handleException(Exception ex, HttpServletRequest request) {
    // Need access to myContext from login()
}

@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(HttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
    ...
    myContext = "Some contextual information"
    ...
    i_will_always_throw_an_exception();
}

Since Spring is responsible for translating a thrown exception into an invocation of handleException(), I am having difficulty trying to find a way to pass myContext to the handler.  One thought I have is creating a subclass of HttpServletRequest.  If that approach works I would have code like this:

@ExceptionHandler(Exception.class)
public void handleException(Exception ex, MyCustomHttpServletRequest request) {
    // I now have access to the context via the following
    String myContext = request.getContext();
}

@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(MyCustomHttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
    ...
    myContext = "Some contextual information"
    request.setContext(myContext);
    ...
    i_will_always_throw_an_exception();
}

But, if I follow this approach, how do I properly use my own arbitrary sub-class of HttpServletRequest to make this work?

Body:
Can't you just put it into exception (if necessary - wrapping the original exception with the new one)?

@ExceptionHandler(MyContextualException.class)
public void handleException(MyContextualException ex) {
    // Need access to myContext from login()
}

@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(HttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
    ...
    myContext = "Some contextual information"
    ...
    try {
        i_will_always_throw_an_exception();
    } catch (Exception ex) {
        throw new MyContextualException(myContext, ex);
    }
}

An alternative approach is to pass the context as a request attribute:

request.setAttribute("myContext", myContext);


问:
ECS (EC2 type) task is failing container health check, but ALB health check works
I have ECS cluster (EC2 type, 1 service only) with ALB and Target Group. Desired count is set to 2 on ECS service level, no ASG for tasks. Technically everything works. I can communicate with my API without  any problem, but there is a small issue that bothers me. Container health check for my ECS tasks doesn't work. I'm mapping container port 3000 to host port 0, but since it's inside container it shouldn't matter?

I'm struggling to understand why, here is the cmd I use (I will just paste my whole health check block since I'm using terraform to deploy my infra)

```<code>healthCheck = {
    retries = 10
    command = ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"]
    timeout : 5
    interval : 10
    startPeriod : 45
}
</code>```

I's worth mentioning that both my task with random ports are visible in Target Group health check, where I'm using the same endpoint. Here is how it looks like:

```<code>resource "aws_alb_target_group" "my_api_backend_tg" {
  name                 = "my_tg_name"
  port                 = 3000
  protocol             = "HTTP"
  vpc_id               = "vpc_id"
  deregistration_delay = 25

  health_check {
    path                = "/health"
    healthy_threshold   = 2
    unhealthy_threshold = 5
    timeout             = 5
    interval            = 15
    matcher             = "200"
  }

  lifecycle {
    create_before_destroy = true
    ignore_changes        = [name]
  }
}
</code>```

I'm relatively new to AWS, so it might be trivial, but I'm not even sure how can I debug it, would appreciate any help.

答: After all it was something trivial and not even related to AWS, but to docker itself. Image was so thin that there was no curl installed. Installing it fixed my problem.</p>

Body:
I have ECS cluster (EC2 type, 1 service only) with ALB and Target Group. Desired count is set to 2 on ECS service level, no ASG for tasks. Technically everything works. I can communicate with my API without  any problem, but there is a small issue that bothers me. Container health check for my ECS tasks doesn't work. I'm mapping container port 3000 to host port 0, but since it's inside container it shouldn't matter?

I'm struggling to understand why, here is the cmd I use (I will just paste my whole health check block since I'm using terraform to deploy my infra)

healthCheck = {
    retries = 10
    command = ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"]
    timeout : 5
    interval : 10
    startPeriod : 45
}

I's worth mentioning that both my task with random ports are visible in Target Group health check, where I'm using the same endpoint. Here is how it looks like:

resource "aws_alb_target_group" "my_api_backend_tg" {
  name                 = "my_tg_name"
  port                 = 3000
  protocol             = "HTTP"
  vpc_id               = "vpc_id"
  deregistration_delay = 25

  health_check {
    path                = "/health"
    healthy_threshold   = 2
    unhealthy_threshold = 5
    timeout             = 5
    interval            = 15
    matcher             = "200"
  }

  lifecycle {
    create_before_destroy = true
    ignore_changes        = [name]
  }
}

I'm relatively new to AWS, so it might be trivial, but I'm not even sure how can I debug it, would appreciate any help.


问:
Error message in terminal when using "-a"
I tried this command

```<code>ls -a -l ~/.ssh
</code>```

but I got this error message,

```<code>Get-ChildItem : Parameter cannot be processed because the parameter name 'a' is ambiguous. Possible matches include: -Attributes -Directory -File -Hidden
-ReadOnly -System.
</code>```

答:
Have you tried...?:</p>
```<code>ls -la ~/.ssh
</code>```

Body:
I tried this command

ls -a -l ~/.ssh

but I got this error message,

Get-ChildItem : Parameter cannot be processed because the parameter name 'a' is ambiguous. Possible matches include: -Attributes -Directory -File -Hidden
-ReadOnly -System.

Body:
Have you tried...?:

ls -la ~/.ssh


问:
passing variables from PHP page to jQuery modal window
Ok, so as the title implies, I'm opening a modal dialog and need to pass it various variables, one of which is the url of the page I'm starting from. Now this wouldn't be a problem if the jQuery that creates the dialog was in script tags in the head of a page as I could use PHP to echo the info and append it to the URL as a GET string, but the code is actually in an external .js file which is referenced in the head.

script.js:

```<code>var dialogVariables = {
    modal: true,
    autoOpen: false,
    width: 500,
    buttons: {
        Cancel: function() {
            $(this).dialog('close');
        } //end cancel button
    },//end button
    open: function() {
        $("#reportDialog").load("/report.php");}
    };
$("#reportDialog").dialog(dialogVariables);
</code>```

Any ideas as to how I can pass the information across?

答:
I would add some data attribute to the element like for example:

```<code><div id="reportDialog" data-varname="some data"></div>
</code>```

You can get this using:

```<code>$('#reportDialog').data('varname');
</code>```

Body:
Ok, so as the title implies, I'm opening a modal dialog and need to pass it various variables, one of which is the url of the page I'm starting from. Now this wouldn't be a problem if the jQuery that creates the dialog was in script tags in the head of a page as I could use PHP to echo the info and append it to the URL as a GET string, but the code is actually in an external .js file which is referenced in the head.

script.js:

var dialogVariables = {
    modal: true,
    autoOpen: false,
    width: 500,
    buttons: {
        Cancel: function() {
            $(this).dialog('close');
        } //end cancel button
    },//end button
    open: function() {
        $("#reportDialog").load("/report.php");}
    };
$("#reportDialog").dialog(dialogVariables);

Any ideas as to how I can pass the information across?

Body:
I would add some data attribute to the element like for example:

<div id="reportDialog" data-varname="some data"></div>

You can get this using:

$('#reportDialog').data('varname');


问:
How to execute a function after setting a state in React Native?
my problem is I need to execute a function (getCupons) after setting the two states setPagenumber and setMoreresults but this two functions are asynchronous and don't have a callback. Thanks</p>
```<code>const [pageNumber, setPagenumber] = useState(1);
const [moreResults, setMoreresults] = useState(true);
const isFocused = useIsFocused();

useEffect(() => {
    setPagenumber(1);
    setMoreresults(true);
    getCupons();
}, [isFocused])
</code>```

答:
You can create another useEffect, then it will be called when the conditions are met.</p>
```<code>  const [pageNumber, setPagenumber] = useState(0);
  const [moreResults, setMoreresults] = useState(false);
  const isFocused = useIsFocused();

  useEffect(() => {
    setPagenumber(1);
    setMoreresults(true);
  }, [isFocused]);

  useEffect(() => {
    if (moreResults && pageNumber === 1) {
      getCupons();
    }
  }, [pageNumber, moreResults]);

</code>```

Body:
my problem is I need to execute a function (getCupons) after setting the two states setPagenumber and setMoreresults but this two functions are asynchronous and don't have a callback. Thanks

const [pageNumber, setPagenumber] = useState(1);
const [moreResults, setMoreresults] = useState(true);
const isFocused = useIsFocused();

useEffect(() => {
    setPagenumber(1);
    setMoreresults(true);
    getCupons();
}, [isFocused])

Body:
You can create another useEffect, then it will be called when the conditions are met.

  const [pageNumber, setPagenumber] = useState(0);
  const [moreResults, setMoreresults] = useState(false);
  const isFocused = useIsFocused();

  useEffect(() => {
    setPagenumber(1);
    setMoreresults(true);
  }, [isFocused]);

  useEffect(() => {
    if (moreResults && pageNumber === 1) {
      getCupons();
    }
  }, [pageNumber, moreResults]);


问:
Python list withing list distinct elements
I have a list that looks like this:

```<code>a = [[99 , 2],[2,99]]
</code>```

My objective is to get a list that has one of the elements because they are similar combinations:

so I need another list b that is either:

```<code>b = [[99,2]]
</code>```

or

```<code>b= [[2,99]]
</code>```

How do I go about it in the most efficient manner without any libraries, answers with libraries are also appreciated since I would wanna know what are the stuffs already out there to ease my pain with learning how to code.

Thank you

答:
I can give you an answer using libraries. random is part of the python standard library (you already have it installed if you have python), so depending on why you don't want to use libraries, this might work.

```<code>import random

a = [[99 , 2],[2,99]]
b = random.choice(a)
</code>```

b will be a list that has exactly one of the elements of list a.
If you need b to be a list of lists, modify it like so:

```<code>import random

a = [[99 , 2],[2,99]]
b = [random.choice(a)]
</code>```

Body:
I have a list that looks like this:

a = [[99 , 2],[2,99]]

My objective is to get a list that has one of the elements because they are similar combinations:

so I need another list b that is either:

b = [[99,2]]

or

b= [[2,99]]

How do I go about it in the most efficient manner without any libraries, answers with libraries are also appreciated since I would wanna know what are the stuffs already out there to ease my pain with learning how to code.

Thank you

Body:
I can give you an answer using libraries. random is part of the python standard library (you already have it installed if you have python), so depending on why you don't want to use libraries, this might work.

import random

a = [[99 , 2],[2,99]]
b = random.choice(a)

b will be a list that has exactly one of the elements of list a.
If you need b to be a list of lists, modify it like so:

import random

a = [[99 , 2],[2,99]]
b = [random.choice(a)]