问:
VBA Copy row from one 2D array and add it to another 2D array
I have a large database (~7000 rows x 25 columns) that i have assigned to an array. Based on user inputs, I am trying to search the database to find items that match the input and copy the entire row to a new array to create a new database to filter with the next question.  The arrays are DBRange and DBT and are defined as public variants. I've tried copying the data from DBRange to a new sheet, but that is incredibly slow and I'm trying to speed things up with keeping things within arrays if possible.</p>
```<code>DBRange = wsd.Range("A1").CurrentRegion 'Sets DBRange to the entirety of the Database

Cervical = 0

If CervicalStartOB.Value = True Then
Cervical = 1
SpineSection.Hide

For i = LBound(DBRange, 1) To UBound(DBRange, 1) 'starts for loop starting with the 1st row in the array to the last row
    If DBRange(i, 13) = "X" Then  'determines if the value in row i column 13 has an X
    ReDim Preserve DBT(count, UBound(DBRange, 2))
    DBT(count, UBound(DBRange, 2)) = Application.WorksheetFunction.Index(DBRange, i, 0)
    count = count + 1

    End If
  Next i
</code>```

答:
Get Range Criteria Rows

Option Explicit

Sub GetRangeCriteriaRowsTESTKeepHeaders()

    Const sCriteriaString As String = "X"
    Const sCol As Long = 13
    Const sfRow As Long = 2 ' First Data Row

    Dim wsd As Worksheet: Set wsd = ActiveSheet

    ' Reference the source range
    Dim srg As Range: Set srg = wsd.Range("A1").CurrentRegion

    ' Write the criteria rows to an array.
    ' If you want to keep headers, use the first row ('sfrow')
    ' as the parameter of the 'FirstRow' argument of the function.
    Dim DBT As Variant
    DBT = GetRangeCriteriaRows(srg, sCriteriaString, sCol, sfRow)
    If IsEmpty(DBT) Then Exit Sub

End Sub

Sub GetRangeCriteriaRowsTESTOnlyData()

    Const sCriteriaString As String = "X"
    Const sCol As Long = 13
    Const sfRow As Long = 2 ' First Data Row

    Dim wsd As Worksheet: Set wsd = ActiveSheet

    ' Reference the source range.
    Dim srg As Range: Set srg = wsd.Range("A1").CurrentRegion

    ' Reference the data range (no headers).
    Dim shrCount As Long: shrCount = sfRow - 1
    Dim sdrg As Range
    Set sdrg = srg.Resize(srg.Rows.Count - shrCount).Offset(shrCount)

    ' Write the criteria rows to an array.
    ' If the range has no headers, don't use the 'FirstRow' argument
    ' of the function.
    Dim DBT As Variant: DBT = GetRangeCriteriaRows(sdrg, sCriteriaString, sCol)
    If IsEmpty(DBT) Then Exit Sub

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the values of the rows of a range ('SourceRange'),
'               that meet a string criterion ('CriteriaString') in a column
'               ('CriteriaColumnIndex'), in a 2D one-based array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetRangeCriteriaRows( _
    ByVal SourceRange As Range, _
    ByVal CriteriaString As String, _
    Optional ByVal CriteriaColumnIndex As Long = 1, _
    Optional ByVal FirstRow As Long = 1) _
As Variant
    Const ProcName As String = "GetRangeCriteriaRows"
    On Error GoTo ClearError

    ' Count the source rows and the source/destination columns.
    Dim srCount As Long: srCount = SourceRange.Rows.Count
    Dim cCount As Long: cCount = SourceRange.Columns.Count
    ' Count the source header rows.
    Dim shrCount As Long: shrCount = FirstRow - 1

    ' Define the source data range according to the first row.
    Dim sdrg As Range
    Set sdrg = SourceRange.Resize(srCount - shrCount).Offset(shrCount)

    ' Write the source range values to the source array.
    Dim sData As Variant: sData = SourceRange.Value

    ' Count the criteria rows in the source data criteria column range.
    Dim sdcrg As Range: Set sdcrg = sdrg.Columns(CriteriaColumnIndex)
    Dim drCount As Long
    drCount = Application.CountIf(sdcrg, CriteriaString) + shrCount

    ' Define the destination array.
    Dim dData As Variant: ReDim dData(1 To drCount, 1 To cCount)

    Dim sr As Long ' Current Source Row
    Dim c As Long ' Current Source/Destination Column
    Dim dr As Long ' Current Destination Row

    ' Write the header rows from the source array to the destination array.
    If FirstRow > 1 Then
        For sr = 1 To shrCount
            dr = dr + 1
            For c = 1 To cCount
                dData(dr, c) = sData(sr, c)
            Next c
        Next sr
    End If

    ' Write the criteria rows from the source array to the destination array.
    For sr = FirstRow To srCount
        If StrComp(CStr(sData(sr, CriteriaColumnIndex)), CriteriaString, _
                vbTextCompare) = 0 Then
            dr = dr + 1
            For c = 1 To cCount
                dData(dr, c) = sData(sr, c)
            Next c
        End If
    Next sr

    GetRangeCriteriaRows = dData

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

Body:
I have a large database (~7000 rows x 25 columns) that i have assigned to an array. Based on user inputs, I am trying to search the database to find items that match the input and copy the entire row to a new array to create a new database to filter with the next question.  The arrays are DBRange and DBT and are defined as public variants. I've tried copying the data from DBRange to a new sheet, but that is incredibly slow and I'm trying to speed things up with keeping things within arrays if possible.

DBRange = wsd.Range("A1").CurrentRegion 'Sets DBRange to the entirety of the Database

Cervical = 0

If CervicalStartOB.Value = True Then
Cervical = 1
SpineSection.Hide

For i = LBound(DBRange, 1) To UBound(DBRange, 1) 'starts for loop starting with the 1st row in the array to the last row
    If DBRange(i, 13) = "X" Then  'determines if the value in row i column 13 has an X
    ReDim Preserve DBT(count, UBound(DBRange, 2))
    DBT(count, UBound(DBRange, 2)) = Application.WorksheetFunction.Index(DBRange, i, 0)
    count = count + 1

    End If
  Next i


来源: stackexchange

问:
Cannot find Qt6 installation?
Trying to follow the install instructions from a GitHub page: https://github.com/TASEmulators/fceux

I went through with installing Qt6 and when I do the following this happens:

```<code>mkdir build
cd build
cmake  -DCMAKE_INSTALL_PREFIX=/usr  -DQT6=1  -DCMAKE_BUILD_TYPE=Debug    ..

-- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19042.
-- GUI Frontend: Qt6
CMake Error at src/CMakeLists.txt:22 (find_package):
  By not providing "FindQt6.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt6", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt6" with any of
  the following names:

    Qt6Config.cmake
    qt6-config.cmake

  Add the installation prefix of "Qt6" to CMAKE_PREFIX_PATH or set "Qt6_DIR"
  to a directory containing one of the above files.  If "Qt6" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!

</code>```

答:
As the error message says, you need up set the environment value Qt6_DIR to the location you installed qt6 to. This should be a part of the instructions in installing qt6.

You should link the instructions you used for installing qt6. They may contain instructions to set the environment variable QT_DIR instead of the Qt6_DIR which is required by what you're building. If this is the case just follow the instructions for setting QT_DIR to also set Qt6_DIR.

ContentLicense: CC BY-SA 4.0

Title: Cannot find Qt6 installation?

Body:
Trying to follow the install instructions from a GitHub page: https://github.com/TASEmulators/fceux

I went through with installing Qt6 and when I do the following this happens:

mkdir build
cd build
cmake  -DCMAKE_INSTALL_PREFIX=/usr  -DQT6=1  -DCMAKE_BUILD_TYPE=Debug    ..

-- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19042.
-- GUI Frontend: Qt6
CMake Error at src/CMakeLists.txt:22 (find_package):
  By not providing "FindQt6.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt6", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt6" with any of
  the following names:

    Qt6Config.cmake
    qt6-config.cmake

  Add the installation prefix of "Qt6" to CMAKE_PREFIX_PATH or set "Qt6_DIR"
  to a directory containing one of the above files.  If "Qt6" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!


问:
gdb not loading symbols after attaching to process (MySQL debug binary)
I'm trying to use gdb to step-debug mysql internals.

I compiled the debug binary (Server version: 8.0.28-debug Source distribution ), but it doesn't seem like gdb can access most of the symbols.

When I attach gdb to a running server process, then send a MySQL query in another terminal, gdb breaks at some OS level function, and the query terminal does get paused. But when I try to "step into," the query result is returned without me getting to peek into any code.

When I run info sources or info functions in gdb, almost nothing seems to be from mysql, except a few under MySQL's extras directory. Scrolling way down the info functions output, below Non-debugging symbols I finally see a bunch of mysql functions. So, they don't appear to be loaded.

I started mysqld with the --gdb=ON --debug=ON flags, and also tried setting the SESSION variable for debugging in the MySQL terminal:

```<code>mysql> SET SESSION debug = 'd:t:i:o,/tmp/mysqld.trace:F:L:N:P';
</code>```

Nothing I've tried has worked yet.

Here's my whole setup, from the point of launching a vagrant VM with Ubuntu 20.04. I basically followed the steps here, modified for a debug install.

```<code>$ apt update
$ apt upgrade -y
$ apt install libssl-dev libncurses5-dev pkg-config bison build-essential –y
$ cd ~
$ mkdir bld
$ cd bld
$ ################
$ ## BUILD STEP ##
$ ################
$ cmake /vagrant/mysql-server/ -DDOWNLOAD_BOOST=1 -DWITH_BOOST=$HOME/my_boost \
    -DWITH_DEBUG=true -DWITH_INNODB_EXTRA_DEBUG=true
$ # /vagrant folder is mounted from the Windows 10 host OS, contains the mysql git repo
$ make -j8
$ make install
$ ###
$ groupadd mysql
$ useradd -r -g mysql -s /bin/false mysql
$ cd /usr/local/mysql-test
$ mkdir mysql-files
$ chown mysql:mysql mysql-files
$ chmod 750 mysql-files
$ ###
$ /usr/local/bin/mysqld --initialize-insecure --user=mysql
$ # I dont need "secure" on local VM
$
$ ##################################
$ # START THE SERVER FOR DEBUGGING #
$ ##################################
$ /usr/local/bin/mysqld_safe --user=mysql --gdb=ON --debug=ON --thread_cache_size=5
$ # get mysqld PID
$ ps aux | grep mysql
root        2565  0.0  0.0  11856  4492 pts/0    S    07:12   0:00 sudo mysqld_safe --user=mysql --debug=ON --gdb=ON
root        2566  0.0  0.0   2608  1808 pts/0    S    07:12   0:00 /bin/sh /usr/local/bin/mysqld_safe --user=mysql --debug=ON --gdb=ON
mysql       2667  1.1  4.0 1818376 415952 pts/0  Sl   07:12   0:11 /usr/local/bin/mysqld --basedir=/usr/local --datadir=/usr/local/data --plugin-dir=/usr/local/lib/plugin --user=mysql --debug=ON --gdb=ON --log-error=vagrant.err --pid-file=vagrant.pid
vagrant     2745  0.0  0.0   8900   736 pts/1    S+   07:29   0:00 grep --color=auto mysql
$ # START GDB
$ gdb
(gdb) attach 2667
Attaching to process 2667
[New LWP 2670]
[New LWP 2671]
[New LWP 2672]
[New LWP 2673]
[New LWP 2674]
[New LWP 2675]
[New LWP 2676]
[New LWP 2677]
[New LWP 2678]
[New LWP 2679]
[New LWP 2680]
[New LWP 2681]
[New LWP 2682]
[New LWP 2683]
[New LWP 2684]
[New LWP 2685]
[New LWP 2688]
[New LWP 2689]
[New LWP 2690]
[New LWP 2691]
[New LWP 2692]
[New LWP 2693]
[New LWP 2694]
[New LWP 2695]
[New LWP 2696]
[New LWP 2697]
[New LWP 2701]
[New LWP 2702]
[New LWP 2703]
[New LWP 2704]
[New LWP 2705]
[New LWP 2706]
[New LWP 2707]
[New LWP 2708]
[New LWP 2709]
[New LWP 2711]
[New LWP 2713]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
0x00007f200fe2faff in __GI___poll (fds=0x7f1ffecb87d0, nfds=2, timeout=-1) at ../sysdeps/unix/sysv/linux/poll.c:29
29      ../sysdeps/unix/sysv/linux/poll.c: No such file or directory.
(gdb)
</code>```

None of the post-attach output mentions mysql. gdb does not seem to be importing the symbols.

This tutorial suggests that the gdb output after attach [PID] should look more like the following, with a line ike Reading symbols from ... mysqld...done.:

```<code>(gdb) attach 7506
Attaching to process 7506
Reading symbols from /home/cbell/source/bzr/mysql-5.6/sql/mysqld...done.
Reading symbols from /lib/x86_64-linux-gnu/libpthread.so.0...(no debugging symbols found)...done.
[Thread debugging using libthread_db enabled]
[New Thread 0x7f7ba8e57700 (LWP 7524)]
[New Thread 0x7f7ba4a26700 (LWP 7523)]
[New Thread 0x7f7ba5227700 (LWP 7522)]
[New Thread 0x7f7ba5a28700 (LWP 7521)]
[New Thread 0x7f7ba6229700 (LWP 7520)]
[New Thread 0x7f7ba6a2a700 (LWP 7519)]
[New Thread 0x7f7ba722b700 (LWP 7518)]
[New Thread 0x7f7ba7a2c700 (LWP 7517)]
[New Thread 0x7f7ba822d700 (LWP 7516)]
[New Thread 0x7f7ba8a2e700 (LWP 7515)]
[New Thread 0x7f7ba9658700 (LWP 7513)]
[New Thread 0x7f7ba9e59700 (LWP 7512)]
[New Thread 0x7f7baa65a700 (LWP 7511)]
[New Thread 0x7f7baae5b700 (LWP 7510)]
[New Thread 0x7f7bab65c700 (LWP 7509)]
[New Thread 0x7f7bb085f700 (LWP 7508)]
Loaded symbols for /lib/x86_64-linux-gnu/libpthread.so.0
Reading symbols from /lib/x86_64-linux-gnu/librt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/librt.so.1
Reading symbols from /lib/x86_64-linux-gnu/libcrypt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libcrypt.so.1
Reading symbols from /lib/x86_64-linux-gnu/libdl.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libdl.so.2
Reading symbols from /usr/lib/x86_64-linux-gnu/libstdc++.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib/x86_64-linux-gnu/libstdc++.so.6
Reading symbols from /lib/x86_64-linux-gnu/libm.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libm.so.6
Reading symbols from /lib/x86_64-linux-gnu/libgcc_s.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libgcc_s.so.1
Reading symbols from /lib/x86_64-linux-gnu/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libc.so.6
Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
0x00007f7bb0939ae3 in poll () from /lib/x86_64-linux-gnu/libc.so.6
</code>```

答:
$ make -j8

$ make install

It is exceedingly likely that make install runs strip on the binary before installing it into /usr/loca/bin (that's the standard procedure).

What you want to do is use the "as built" binary (which presumably still has debug info) to debug the process. Something like:

```<code>gdb ~/bld/.../mysqld -p 2667
</code>```

This tutorial suggests that the gdb output after ...

Reading symbols from /home/cbell/source/bzr/mysql-5.6/sql/mysqld...done.

Note that they are not running installed binary, but the binary from their build tree.

Body:
I'm trying to use gdb to step-debug mysql internals.

I compiled the debug binary (Server version: 8.0.28-debug Source distribution ), but it doesn't seem like gdb can access most of the symbols.

When I attach gdb to a running server process, then send a MySQL query in another terminal, gdb breaks at some OS level function, and the query terminal does get paused. But when I try to "step into," the query result is returned without me getting to peek into any code.

When I run info sources or info functions in gdb, almost nothing seems to be from mysql, except a few under MySQL's extras directory. Scrolling way down the info functions output, below Non-debugging symbols I finally see a bunch of mysql functions. So, they don't appear to be loaded.

I started mysqld with the --gdb=ON --debug=ON flags, and also tried setting the SESSION variable for debugging in the MySQL terminal:

mysql> SET SESSION debug = 'd:t:i:o,/tmp/mysqld.trace:F:L:N:P';

Nothing I've tried has worked yet.

Here's my whole setup, from the point of launching a vagrant VM with Ubuntu 20.04. I basically followed the steps here, modified for a debug install.

$ apt update
$ apt upgrade -y
$ apt install libssl-dev libncurses5-dev pkg-config bison build-essential –y
$ cd ~
$ mkdir bld
$ cd bld
$ ################
$ ## BUILD STEP ##
$ ################
$ cmake /vagrant/mysql-server/ -DDOWNLOAD_BOOST=1 -DWITH_BOOST=$HOME/my_boost \
    -DWITH_DEBUG=true -DWITH_INNODB_EXTRA_DEBUG=true
$ # /vagrant folder is mounted from the Windows 10 host OS, contains the mysql git repo
$ make -j8
$ make install
$ ###
$ groupadd mysql
$ useradd -r -g mysql -s /bin/false mysql
$ cd /usr/local/mysql-test
$ mkdir mysql-files
$ chown mysql:mysql mysql-files
$ chmod 750 mysql-files
$ ###
$ /usr/local/bin/mysqld --initialize-insecure --user=mysql
$ # I dont need "secure" on local VM
$
$ ##################################
$ # START THE SERVER FOR DEBUGGING #
$ ##################################
$ /usr/local/bin/mysqld_safe --user=mysql --gdb=ON --debug=ON --thread_cache_size=5
$ # get mysqld PID
$ ps aux | grep mysql
root        2565  0.0  0.0  11856  4492 pts/0    S    07:12   0:00 sudo mysqld_safe --user=mysql --debug=ON --gdb=ON
root        2566  0.0  0.0   2608  1808 pts/0    S    07:12   0:00 /bin/sh /usr/local/bin/mysqld_safe --user=mysql --debug=ON --gdb=ON
mysql       2667  1.1  4.0 1818376 415952 pts/0  Sl   07:12   0:11 /usr/local/bin/mysqld --basedir=/usr/local --datadir=/usr/local/data --plugin-dir=/usr/local/lib/plugin --user=mysql --debug=ON --gdb=ON --log-error=vagrant.err --pid-file=vagrant.pid
vagrant     2745  0.0  0.0   8900   736 pts/1    S+   07:29   0:00 grep --color=auto mysql
$ # START GDB
$ gdb
(gdb) attach 2667
Attaching to process 2667
[New LWP 2670]
[New LWP 2671]
[New LWP 2672]
[New LWP 2673]
[New LWP 2674]
[New LWP 2675]
[New LWP 2676]
[New LWP 2677]
[New LWP 2678]
[New LWP 2679]
[New LWP 2680]
[New LWP 2681]
[New LWP 2682]
[New LWP 2683]
[New LWP 2684]
[New LWP 2685]
[New LWP 2688]
[New LWP 2689]
[New LWP 2690]
[New LWP 2691]
[New LWP 2692]
[New LWP 2693]
[New LWP 2694]
[New LWP 2695]
[New LWP 2696]
[New LWP 2697]
[New LWP 2701]
[New LWP 2702]
[New LWP 2703]
[New LWP 2704]
[New LWP 2705]
[New LWP 2706]
[New LWP 2707]
[New LWP 2708]
[New LWP 2709]
[New LWP 2711]
[New LWP 2713]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
0x00007f200fe2faff in __GI___poll (fds=0x7f1ffecb87d0, nfds=2, timeout=-1) at ../sysdeps/unix/sysv/linux/poll.c:29
29      ../sysdeps/unix/sysv/linux/poll.c: No such file or directory.
(gdb)

None of the post-attach output mentions mysql. gdb does not seem to be importing the symbols.

This tutorial suggests that the gdb output after attach [PID] should look more like the following, with a line ike Reading symbols from ... mysqld...done.:

(gdb) attach 7506
Attaching to process 7506
Reading symbols from /home/cbell/source/bzr/mysql-5.6/sql/mysqld...done.
Reading symbols from /lib/x86_64-linux-gnu/libpthread.so.0...(no debugging symbols found)...done.
[Thread debugging using libthread_db enabled]
[New Thread 0x7f7ba8e57700 (LWP 7524)]
[New Thread 0x7f7ba4a26700 (LWP 7523)]
[New Thread 0x7f7ba5227700 (LWP 7522)]
[New Thread 0x7f7ba5a28700 (LWP 7521)]
[New Thread 0x7f7ba6229700 (LWP 7520)]
[New Thread 0x7f7ba6a2a700 (LWP 7519)]
[New Thread 0x7f7ba722b700 (LWP 7518)]
[New Thread 0x7f7ba7a2c700 (LWP 7517)]
[New Thread 0x7f7ba822d700 (LWP 7516)]
[New Thread 0x7f7ba8a2e700 (LWP 7515)]
[New Thread 0x7f7ba9658700 (LWP 7513)]
[New Thread 0x7f7ba9e59700 (LWP 7512)]
[New Thread 0x7f7baa65a700 (LWP 7511)]
[New Thread 0x7f7baae5b700 (LWP 7510)]
[New Thread 0x7f7bab65c700 (LWP 7509)]
[New Thread 0x7f7bb085f700 (LWP 7508)]
Loaded symbols for /lib/x86_64-linux-gnu/libpthread.so.0
Reading symbols from /lib/x86_64-linux-gnu/librt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/librt.so.1
Reading symbols from /lib/x86_64-linux-gnu/libcrypt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libcrypt.so.1
Reading symbols from /lib/x86_64-linux-gnu/libdl.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libdl.so.2
Reading symbols from /usr/lib/x86_64-linux-gnu/libstdc++.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib/x86_64-linux-gnu/libstdc++.so.6
Reading symbols from /lib/x86_64-linux-gnu/libm.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libm.so.6
Reading symbols from /lib/x86_64-linux-gnu/libgcc_s.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libgcc_s.so.1
Reading symbols from /lib/x86_64-linux-gnu/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/x86_64-linux-gnu/libc.so.6
Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
0x00007f7bb0939ae3 in poll () from /lib/x86_64-linux-gnu/libc.so.6

Body:
$ make -j8

$ make install

It is exceedingly likely that make install runs strip on the binary before installing it into /usr/loca/bin (that's the standard procedure).

What you want to do is use the "as built" binary (which presumably still has debug info) to debug the process. Something like:

gdb ~/bld/.../mysqld -p 2667

This tutorial suggests that the gdb output after ...

Reading symbols from /home/cbell/source/bzr/mysql-5.6/sql/mysqld...done.

Note that they are not running installed binary, but the binary from their build tree.


问:
How do you access text from an embed on discord.jsv16?
I’m trying to access the footer of an embed, to see if it has specific text. I can’t find the name of what the footer is,

The one I mainly find is message.embed[0].footer, which doesn’t work.

For more context, I’m trying to make a multi-paged help embed, with buttons that go to the next page, and the footer says what page you’re on.

I’m using the footer to detect the page you are on, and know which page to go to.

答:
Use Message#embeds which returns an array of MessageEmbeds, get the footer from that and get the text from it.

const currentPage = message.embeds[0].footer.text
```


问:
How to push the project from azuredevops to visual studio 2019 again?
I push the project from azure to visual studio 2019 through team explorer but it didn't went well because some files are missing. How can I do the same again? The map & get option don't appear.</p>

答:
Open the source control explorer and in the top bar edit the workspace there you can add additional mappings if needed.

Then use the add files and folders option in the toolbar to add the files that are missing from your previous check-in and perform another check-in.


问:
Docker mounted volume GID mismatch causes error: dial unix /var/run/docker.sock: connect: permission denied
Using the official jenkins image, I have installed docker and docker-compose and added jenkins to the docker group (GID 999 in the container).

After that, I shared the /var/run/docker.sock of the host so enable jenkins create "siblings" containers. It happens that the original file have GID 134 and with this GID is mounted. I am getting the following error:

demo_1  | docker: Got permission denied while trying to connect to the
  Docker daemon socket at unix:///var/run/docker.sock: Post
  http://%2Fvar%2Frun%2Fdocker.sock/v1.32/containers/create: dial unix
  /var/run/docker.sock: connect: permission denied. demo_1 | See 'docker
  run --help'.

Any idea about how to solve this?

My minimal (and not optimized yet) Dockerfile is:

```<code>FROM jenkins/jenkins:lts

USER root

RUN apt-get update && apt-get install -y apt-transport-https \
     ca-certificates \
     curl \
     gnupg2 \
     software-properties-common

RUN curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | apt-key add -
RUN apt-key fingerprint 0EBFCD88
RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") \
   $(lsb_release -cs) \
   stable"

RUN apt-get update
RUN apt-get install -y docker-ce docker-compose
RUN usermod -aG docker jenkins

USER jenkins
RUN newgrp docker
</code>```

I have also created a docker-compose to test it:

```<code>version: '2'
services:
    demo:
        build: .
        ports:
            - 8080:8080
            - 50000:50000
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
        command: >
            /bin/sh -c "
                set -e
                groups
                docker -v
                docker-compose -v
                ls -ln /var/run/docker.sock
                id jenkins
                docker run hello-world
            "
</code>```

The output is:

```<code>demo_1  | jenkins staff docker
demo_1  | Docker version 17.09.0-ce, build afdb6d4
demo_1  | docker-compose version 1.8.0, build unknown
demo_1  | srw-rw---- 1 0 134 0 Sep 30 07:36 /var/run/docker.sock
demo_1  | uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),50(staff),999(docker)
demo_1  | docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.32/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
demo_1  | See 'docker run --help'.
</code>```

答:
you can create a group in dockerfile with the same group id as docker
https://stackoverflow.com/a/71085404/4791684</p>

ContentLicense: CC BY-SA 3.0

Body:
Using the official jenkins image, I have installed docker and docker-compose and added jenkins to the docker group (GID 999 in the container).

After that, I shared the /var/run/docker.sock of the host so enable jenkins create "siblings" containers. It happens that the original file have GID 134 and with this GID is mounted. I am getting the following error:

demo_1  | docker: Got permission denied while trying to connect to the
  Docker daemon socket at unix:///var/run/docker.sock: Post
  http://%2Fvar%2Frun%2Fdocker.sock/v1.32/containers/create: dial unix
  /var/run/docker.sock: connect: permission denied. demo_1 | See 'docker
  run --help'.

Any idea about how to solve this?

My minimal (and not optimized yet) Dockerfile is:

FROM jenkins/jenkins:lts

USER root

RUN apt-get update && apt-get install -y apt-transport-https \
     ca-certificates \
     curl \
     gnupg2 \
     software-properties-common

RUN curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | apt-key add -
RUN apt-key fingerprint 0EBFCD88
RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") \
   $(lsb_release -cs) \
   stable"

RUN apt-get update
RUN apt-get install -y docker-ce docker-compose
RUN usermod -aG docker jenkins

USER jenkins
RUN newgrp docker

I have also created a docker-compose to test it:

version: '2'
services:
    demo:
        build: .
        ports:
            - 8080:8080
            - 50000:50000
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
        command: >
            /bin/sh -c "
                set -e
                groups
                docker -v
                docker-compose -v
                ls -ln /var/run/docker.sock
                id jenkins
                docker run hello-world
            "

The output is:

demo_1  | jenkins staff docker
demo_1  | Docker version 17.09.0-ce, build afdb6d4
demo_1  | docker-compose version 1.8.0, build unknown
demo_1  | srw-rw---- 1 0 134 0 Sep 30 07:36 /var/run/docker.sock
demo_1  | uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),50(staff),999(docker)
demo_1  | docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.32/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
demo_1  | See 'docker run --help'.


问:
I wrote a loop that prints only the items in the list that begin with capital letter but islower() method doesnt return True if the item is lower case
```<code>friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0

while i < len(friends):
    if friends[i].islower != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1

print(f"The Number Of The Ignored Names Is {len(ignoredNames)}")
</code>```

答:
You iterate in python using for ... in ....
Also you don't need to invert checking for islower if you want to check for the upper case of the first letter.
Also don't compare boolean values to boolean constants. It's redundant.

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []

for friend in friends:
    if friend[0].isupper():
        print(friend)
    else:
        ignoredNames.append(friend)

print(f"The Number Of The Ignored Names Is {len(ignoredNames)}")
```


问:
Current URL (from address bar) in a Bookmarklet
I'm building a bookmarklet and I need to get the current URL of the webpage the user is on when they activate the bookmarklet.

I tried using

```<code>$current_url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
</code>```

But that will just get me the URL of the server where the JS for the bookmarklet is hosted. Is there anyway of getting the URL straight from the address bar?

答:
Yes, simply pass location.href form the bookmarklet.

For example;

```<code>location.href="http://mywebsite.com/bookie.php?url="+encodeURIComponent(location.href);
</code>```

Then on your server, you get the URL at $_GET['url']. Good luck.

Of course, that's just JS. You need to add javascript: scheme for it to work.

Body:
I'm building a bookmarklet and I need to get the current URL of the webpage the user is on when they activate the bookmarklet.

I tried using

$current_url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

But that will just get me the URL of the server where the JS for the bookmarklet is hosted. Is there anyway of getting the URL straight from the address bar?

Body:
Yes, simply pass location.href form the bookmarklet.

For example;

location.href="http://mywebsite.com/bookie.php?url="+encodeURIComponent(location.href);

Then on your server, you get the URL at $_GET['url']. Good luck.

Of course, that's just JS. You need to add javascript: scheme for it to work.


问:
How to check if a set1 is a subset of set2 in Scheme?
I tried to write a code to return 'true' if set1 is a subset of set2.

for example: (subset '(a b) '(a c b d)) --> #t  (subset '(a b) '(a c d)) --> #f

Here's what I did, can someone enlighten me why isn't it working?

```<code>(define (subset lst1 lst2)
  (cond ((null? lst2) #f)
        ((member (car lst1)  lst2)
         (subset  (cdr lst1)  lst2)
         #t)
        (else #f)))
</code>```

答:
```<code>    ((member (car lst1) lst2)
     (subset (cdr lst1) lst2)
     #t)
</code>```

true has no reason there.  You reduce the problem to a subproblem.

Also, no need to check (null? lst2), as you do not loop over lst2.  The final condition must check lst1 instead.

I would write so:

```<code>(define (subset lst1 lst2)
  (or (null? lst1)
      (and (member (car lst1) lst2)
           (subset (cdr lst1) lst2)))))
</code>```

Body:
I tried to write a code to return 'true' if set1 is a subset of set2.

for example: (subset '(a b) '(a c b d)) --> #t  (subset '(a b) '(a c d)) --> #f

Here's what I did, can someone enlighten me why isn't it working?

(define (subset lst1 lst2)
  (cond ((null? lst2) #f)
        ((member (car lst1)  lst2)
         (subset  (cdr lst1)  lst2)
         #t)
        (else #f)))

Body:
    ((member (car lst1) lst2)
     (subset (cdr lst1) lst2)
     #t)

true has no reason there.  You reduce the problem to a subproblem.

Also, no need to check (null? lst2), as you do not loop over lst2.  The final condition must check lst1 instead.

I would write so:

(define (subset lst1 lst2)
  (or (null? lst1)
      (and (member (car lst1) lst2)
           (subset (cdr lst1) lst2)))))


问:
Django add multiple Users to lobby model
I want to add Users to my players field in the lobby but i dont know how.
Every user should be in just one lobby.

User Model

```<code>class GeoUser(AbstractUser):
        user_score = models.IntegerField(default=0)
        email = models.EmailField(unique=True)
</code>```

Lobby Model

```<code>class Lobby(models.Model):
    lobby_code = models.CharField(
        max_length=18, unique=True)

    players = # here i want to add multiple users that should be in the lobby
</code>```

Thanks in advance

答:
I would advice you to add ForeignKey in GeoUser model pointing to Lobby model. This is OneToMany relation for Lobby, because one GeoUser will be in one Lobby, but there is actually no limit on how many GeoUser objects can be in Lobby.

```<code>class GeoUser(AbstractUser):
    user_score = models.IntegerField(default=0)
    email = models.EmailField(unique=True)

    lobby = models.ForeignKey('Lobby', on_delete=models.SET_NULL, null=True, default=None, related_name='users')

class Lobby(models.Model):
    lobby_code = models.CharField(
        max_length=18, unique=True)

    def players(self):
        return self.users.all()
</code>```

To get all players just call:

```<code>lobby = Lobby.objects.first()
lobby.players()    # returns a QuerySet of all related GeoUser objects
</code>```

Body:
I want to add Users to my players field in the lobby but i dont know how.
Every user should be in just one lobby.

User Model

class GeoUser(AbstractUser):
        user_score = models.IntegerField(default=0)
        email = models.EmailField(unique=True)

Lobby Model

class Lobby(models.Model):
    lobby_code = models.CharField(
        max_length=18, unique=True)

    players = # here i want to add multiple users that should be in the lobby

Thanks in advance

Body:
I would advice you to add ForeignKey in GeoUser model pointing to Lobby model. This is OneToMany relation for Lobby, because one GeoUser will be in one Lobby, but there is actually no limit on how many GeoUser objects can be in Lobby.

class GeoUser(AbstractUser):
    user_score = models.IntegerField(default=0)
    email = models.EmailField(unique=True)

    lobby = models.ForeignKey('Lobby', on_delete=models.SET_NULL, null=True, default=None, related_name='users')

class Lobby(models.Model):
    lobby_code = models.CharField(
        max_length=18, unique=True)

    def players(self):
        return self.users.all()

To get all players just call:

lobby = Lobby.objects.first()
lobby.players()    # returns a QuerySet of all related GeoUser objects


问:
Getting vCenter info for a VM using powershell
I need to get VMs' vCenter information, or at least just the vCenter name,

I've looked online at vmware help and all they have is connect to the vCenter to get the VM info, exactly the opposite of what i'm trying to achieve. Is it even possible ? giving I have the machine fqdn and ipaddress ?

Thanks

答:
I see the last answer here is 5 years old, but just today I found a way that goes deeper into the object hierarchy without having to deal with strings and splitting. To me it's more like the PoSH way.

```<code>(Get-VMHost "MyESXHost").GetClient().config.Server
</code>```

Here's another way that's less deep in the hierarchy but uses a simple split instead.

```<code>(Get-VMHost $ESX).GetClient().ServerUri.Split('@')[1]
</code>```

On some site I found an example that uses splitting heavier like in the previous answers. I less like this way, especially if it is avoidable, I am for the approach: the simpler, the better, but it works too.

```<code>Get-VMHost "MyESXHost" | Select-Object Name,@{N="vCenter";E={$_.Uid.Split('@')[1].Split(':')[0]}}
</code>```

So, in general, there are three properties (maybe more can be found) that give the same result. :

```<code>Uid # need splitting

GetClient().ServerUri # need light splitting

GetClient().config.Server # no splitting, only object properties
</code>```

I am not going here to looping with ForEach, hope it is not a problem.

Body:
I see the last answer here is 5 years old, but just today I found a way that goes deeper into the object hierarchy without having to deal with strings and splitting. To me it's more like the PoSH way.

(Get-VMHost "MyESXHost").GetClient().config.Server

Here's another way that's less deep in the hierarchy but uses a simple split instead.

(Get-VMHost $ESX).GetClient().ServerUri.Split('@')[1]

On some site I found an example that uses splitting heavier like in the previous answers. I less like this way, especially if it is avoidable, I am for the approach: the simpler, the better, but it works too.

Get-VMHost "MyESXHost" | Select-Object Name,@{N="vCenter";E={$_.Uid.Split('@')[1].Split(':')[0]}}

So, in general, there are three properties (maybe more can be found) that give the same result. :

Uid # need splitting

GetClient().ServerUri # need light splitting

GetClient().config.Server # no splitting, only object properties

I am not going here to looping with ForEach, hope it is not a problem.


问:
Can i subscribe to filtered RTK query data results across multiple components?
I have a series of components which all use data derived from an RTK Query response. While derived from the same response with the same query arguments, each component needs the data to pass through a set of relatively expensive client-side filters (whose args are redux store slice properties) which may not be the same for each component. However, all of the components require the data to pass through at least two specific filters. This relationship is shown by the following diagram:

Is it possible to subscribe to the data after it has been transformed by a specific filter/ set of filters?

Approaches I have considered:

Use query in all components, apply whichever filters are required in some useEffect or useMemo. This is not preferable since that means at least 2 filters are being duplicated nComponents times.

Use createSlice extraReducers option and listen for query completion, then perform filter operation. This works fine since i can use the filter args in the reducer, but I believe there is no way for me to repeat the operation with new args once the filter args have been updated but the query data has stayed the same.

Subscribe one component, publish data to slice after each corresponding filter stage,
subscribe each component to corresponding data. This is how i currently have this implemented, but it is not ideal because it couples components together which i wish to avoid, bloats one component which is sort of arbitrarily chosen, and produces frequent large state actions which slow down my application.

Raise query subscription to shared ancestor component, then pass data as props. This is not ideal because these components are at varying depths relative to their shared ancestor, which I imagine would result in prop drilling for at least some component.

Use react context to share results of first 2 filter operations with corresponding components. Haven't looked into this much yet; would it work with a query subscription?

Intuitively i would think some callback that operates as some middleware between the API result and the component's subscribed data would be ideal. I am aware of the transformResponse option definable in the API slice, but I believe it is not appropriate or possible for this situation.

```<code>const queryResult = endpointName.useQuery(args, filterArgs, (data, filterArgs) => {
    return data.performSomeSharedFilterOperationHere(filterArgs);
    }
);
</code>```

Ideally the data would update when query args change OR when filter args change. I suppose the difference between this and a simple useEffect implementation is that in the useEffect scenario, the data is not 'shared' and the filter operations occur nSubscribedComponents times.

Is there anything in RTK that permits the behavior I am seeking?

答:
I think the right answer here is to use the selectFromResult option in the query hooks.

Create the following Reselect selectors:

```<code>
const selectFilter1 = createSelector(
  // Start by taking the actual response data as its input
  (inputData) => inputData,
  (data) => // magically transform here
)

const selectFilter2 = createSelector(
  selectFilter1,
  (filteredData) => // magically transform here
)

// repeat for filters 2 and 3
</code>```

Then, in the component:

  const { filteredData} = useGetPostsQuery(undefined, {
    selectFromResult: result => ({
      // We can optionally include the other metadata fields from the result here
      ...result,
      // Include a field called `filteredData` in the result object,
      // and memoize the calculation
      filteredData: selectFilter3(result.data)
    })
  })
```

The components will be sharing the same selector instance, so each time the selector is called the same result.data reference should be passed in, and thus the calculations should memoize.  The first couple selectors should memoize their results, and thus selectFilter3 will only have to recalculate when selectFilter2's result changes, etc.

Body:
I have a series of components which all use data derived from an RTK Query response. While derived from the same response with the same query arguments, each component needs the data to pass through a set of relatively expensive client-side filters (whose args are redux store slice properties) which may not be the same for each component. However, all of the components require the data to pass through at least two specific filters. This relationship is shown by the following diagram:

Is it possible to subscribe to the data after it has been transformed by a specific filter/ set of filters?

Approaches I have considered:

Use query in all components, apply whichever filters are required in some useEffect or useMemo. This is not preferable since that means at least 2 filters are being duplicated nComponents times.

Use createSlice extraReducers option and listen for query completion, then perform filter operation. This works fine since i can use the filter args in the reducer, but I believe there is no way for me to repeat the operation with new args once the filter args have been updated but the query data has stayed the same.

Subscribe one component, publish data to slice after each corresponding filter stage,
subscribe each component to corresponding data. This is how i currently have this implemented, but it is not ideal because it couples components together which i wish to avoid, bloats one component which is sort of arbitrarily chosen, and produces frequent large state actions which slow down my application.

Raise query subscription to shared ancestor component, then pass data as props. This is not ideal because these components are at varying depths relative to their shared ancestor, which I imagine would result in prop drilling for at least some component.

Use react context to share results of first 2 filter operations with corresponding components. Haven't looked into this much yet; would it work with a query subscription?

Intuitively i would think some callback that operates as some middleware between the API result and the component's subscribed data would be ideal. I am aware of the transformResponse option definable in the API slice, but I believe it is not appropriate or possible for this situation.

const queryResult = endpointName.useQuery(args, filterArgs, (data, filterArgs) => {
    return data.performSomeSharedFilterOperationHere(filterArgs);
    }
);

Ideally the data would update when query args change OR when filter args change. I suppose the difference between this and a simple useEffect implementation is that in the useEffect scenario, the data is not 'shared' and the filter operations occur nSubscribedComponents times.

Is there anything in RTK that permits the behavior I am seeking?

Body:
I think the right answer here is to use the selectFromResult option in the query hooks.

Create the following Reselect selectors:

const selectFilter1 = createSelector(
  // Start by taking the actual response data as its input
  (inputData) => inputData,
  (data) => // magically transform here
)

const selectFilter2 = createSelector(
  selectFilter1,
  (filteredData) => // magically transform here
)

// repeat for filters 2 and 3

Then, in the component:

  const { filteredData} = useGetPostsQuery(undefined, {
    selectFromResult: result => ({
      // We can optionally include the other metadata fields from the result here
      ...result,
      // Include a field called `filteredData` in the result object,
      // and memoize the calculation
      filteredData: selectFilter3(result.data)
    })
  })

The components will be sharing the same selector instance, so each time the selector is called the same result.data reference should be passed in, and thus the calculations should memoize.  The first couple selectors should memoize their results, and thus selectFilter3 will only have to recalculate when selectFilter2's result changes, etc.


问:
GraphQL print function doesn't escape string correctly
I am using the following code:

```<code>const GQL_ADD_JOB = gql`
    mutation AddJob {
        addJob(title: $title, company: $company, description: $description) {
            title
            company
            description
        }
    }
    `;
</code>```

And then using axios, I attempt to POST using GraphQL's print function:

```<code>request.post(
  GQL_ENDPOINT,
  {
    query: print(GQL_ADD_JOB),
    variables: {
      title: job.title,
      company: job.company,
      description: job.description,
    },
  }
)
</code>```

Where job.title, job.company, and job.description can all be strings containing any character, including newlines, quotes, etc. However, calling this results in a JSON parse error. The error shows that the request sent the following data:

'{"query":"mutation AddJob {\n  addJob(title: $title, company: $company, description: $description) {\n    title\n    company\n    description\n  }\n}","variables":{"title":"Route Service Sales Representative - 3rd Shift","company":"Cintas","description":"test desc"}}'

When I use this data and manually perform a POST via curl, I get the following error:

{"message":"Syntax Error: Cannot parse the unexpected character "\\".","extensions":{"code":"GRAPHQL_PARSE_FAILED","exception":{"stacktrace":["GraphQLError: Syntax Error: Cannot parse the unexpected character "\\".","    at syntaxError (/home/user/repos/comp/node_modules/graphql/error/syntaxError.js:15:10)","    at readToken (/home/user/repos/comp/node_modules/graphql/language/lexer.js:360:40)","    at Lexer.lookahead (/home/user/repos/comp/node_modules/graphql/language/lexer.js:75:108)","    at Lexer.advance (/home/user/repos/comp/node_modules/graphql/language/lexer.js:58:35)","    at Parser.expectToken (/home/user/repos/comp/node_modules/graphql/language/parser.js:1408:19)","    at Parser.many (/home/user/repos/comp/node_modules/graphql/language/parser.js:1519:10)","    at Parser.parseSelectionSet (/home/user/repos/comp/node_modules/graphql/language/parser.js:271:24)","    at Parser.parseOperationDefinition (/home/user/repos/comp/node_modules/graphql/language/parser.js:199:26)","    at Parser.parseDefinition (/home/user/repos/comp/node_modules/graphql/language/parser.js:137:23)","    at Parser.many (/home/user/repos/comp/node_modules/graphql/language/parser.js:1523:26)"]}}}

答:
I changed my mutation to this and now it works. I still don't fully understand why the other format didn't work.</p>
```<code>mutation AddJob($title: String!, $company: String!, $description: String!)
{
    addJob(title: $title, company: $company, description: $description)
}
</code>```

Body:
I am using the following code:

const GQL_ADD_JOB = gql`
    mutation AddJob {
        addJob(title: $title, company: $company, description: $description) {
            title
            company
            description
        }
    }
    `;

And then using axios, I attempt to POST using GraphQL's print function:

request.post(
  GQL_ENDPOINT,
  {
    query: print(GQL_ADD_JOB),
    variables: {
      title: job.title,
      company: job.company,
      description: job.description,
    },
  }
)

Where job.title, job.company, and job.description can all be strings containing any character, including newlines, quotes, etc. However, calling this results in a JSON parse error. The error shows that the request sent the following data:

'{"query":"mutation AddJob {\n  addJob(title: $title, company: $company, description: $description) {\n    title\n    company\n    description\n  }\n}","variables":{"title":"Route Service Sales Representative - 3rd Shift","company":"Cintas","description":"test desc"}}'

When I use this data and manually perform a POST via curl, I get the following error:

{"message":"Syntax Error: Cannot parse the unexpected character "\\".","extensions":{"code":"GRAPHQL_PARSE_FAILED","exception":{"stacktrace":["GraphQLError: Syntax Error: Cannot parse the unexpected character "\\".","    at syntaxError (/home/user/repos/comp/node_modules/graphql/error/syntaxError.js:15:10)","    at readToken (/home/user/repos/comp/node_modules/graphql/language/lexer.js:360:40)","    at Lexer.lookahead (/home/user/repos/comp/node_modules/graphql/language/lexer.js:75:108)","    at Lexer.advance (/home/user/repos/comp/node_modules/graphql/language/lexer.js:58:35)","    at Parser.expectToken (/home/user/repos/comp/node_modules/graphql/language/parser.js:1408:19)","    at Parser.many (/home/user/repos/comp/node_modules/graphql/language/parser.js:1519:10)","    at Parser.parseSelectionSet (/home/user/repos/comp/node_modules/graphql/language/parser.js:271:24)","    at Parser.parseOperationDefinition (/home/user/repos/comp/node_modules/graphql/language/parser.js:199:26)","    at Parser.parseDefinition (/home/user/repos/comp/node_modules/graphql/language/parser.js:137:23)","    at Parser.many (/home/user/repos/comp/node_modules/graphql/language/parser.js:1523:26)"]}}}

Body:
I changed my mutation to this and now it works. I still don't fully understand why the other format didn't work.

mutation AddJob($title: String!, $company: String!, $description: String!)
{
    addJob(title: $title, company: $company, description: $description)
}


问:
How we can filter the listview when typing in EditText?
I have a ListView and a EditText. I want to be search the name from listview when I type the name in EditText.

Please tell me.

Thanx in advance...!!!

答:
Did you google around any? I've found that google has taught me more than all my years of college :).

See this SO question for your answer.


问:
Supporting Core Identity Roles in IdentityServer4
I'm creating a Single-Sign-on server using IdentiyServer4. I've looked at their QuickStarts showing how to integrate MS Core Identity with ASP.NET Core 3.1 apps. But there's no examples showing whether ASP.NET roles are natively supported in MVC controllers. A few experiments seemed to indicate that they aren't. But when I discovered that role data can be returned in the Access Token, I wrote my own action filter that authorises users.

However, looking at the documentation for IdentityServer3, they do briefly show roles being used in MVC controllers. So now I'm completely confused. But apart from that, there's no documentation that I can find, and the only mention online I could find about roles with IdentityServer were about a different issue - using roles to control access to remote APIs.

My filter isn't working that well, and I'm worried it's the wrong approach and unnecessary. Can anyone either enlighten me, or point me to any resources that would help.

答:
I hope these codes will be useful for you.

I added ASP.NET Core Identity in the IdentityServer project.

Statup.cs in API Client

public class Startup
{
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers();
        services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:5001";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiScope", policy =>
            {
                policy.RequireAuthenticatedUser();
                policy.RequireClaim("scope", "api1");
            });
        });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                      .RequireAuthorization("ApiScope");
        });
    }
}
```
<p>Startup.cs in MVC Client</p>
<pre class="lang-cs prettyprint-override"><code>public class Startup
{
  public IConfiguration Configuration { get; }
  public Startup(IConfiguration configuration)
  {
    Configuration = configuration;
  }
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllersWithViews();
    JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
    services.AddAuthentication(options =>
    {
      options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
      options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
      options.Authority = "https://localhost:5001";
      options.ClientId = "mvc";
      options.ClientSecret = "secret";
      options.ResponseType = "code id_token";
      options.Scope.Add("email");
      options.Scope.Add("roles");
      options.ClaimActions.DeleteClaim("sid");
      options.ClaimActions.DeleteClaim("idp");
      options.ClaimActions.DeleteClaim("s_hash");
      options.ClaimActions.DeleteClaim("auth_time");
      options.ClaimActions.MapJsonKey("role", "role");
      options.Scope.Add("api1");
      options.SaveTokens = true;
      options.GetClaimsFromUserInfoEndpoint = true;
      options.TokenValidationParameters = new TokenValidationParameters
      {
        NameClaimType = "name",
        RoleClaimType = "role"
      };
    });
    services.AddTransient<AuthenticationDelegatingHandler>();
    services.AddHttpClient("ApplicationAPI", client =>
    {
      client.BaseAddress = new Uri("https://localhost:5002/");
      client.DefaultRequestHeaders.Clear();
      client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
    }).AddHttpMessageHandler<AuthenticationDelegatingHandler>();

    services.AddHttpClient("ApplicationIdentityServer", client =>
    {
      client.BaseAddress = new Uri("https://localhost:5001/");
      client.DefaultRequestHeaders.Clear();
      client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
    });
    services.AddHttpContextAccessor();
  }
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
    if (env.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }
    else
    {
      app.UseExceptionHandler("/Home/Error");
      app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{area=Admin}/{controller=Home}/{action=Index}/{id?}");
    });
  }
}

</code>```

AuthenticationDelegatingHandler in MVC Application

To prevent getting token again.

public class AuthenticationDelegatingHandler : DelegatingHandler
{
  private readonly IHttpContextAccessor _httpContextAccessor;

  public AuthenticationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
  {
    _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
  }

  protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  {
    var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

    if (!string.IsNullOrWhiteSpace(accessToken))
    {
      request.SetBearerToken(accessToken);
    }

    return await base.SendAsync(request, cancellationToken);
  }
}
```
<p>Config.cs in IdentityServer</p>
<pre class="lang-cs prettyprint-override"><code>public static class Config
{
  public static IEnumerable<IdentityResource> IdentityResources =>
      new List<IdentityResource>
      {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResources.Email(),
        new IdentityResource("roles", "Your role(s)", new List<string>() { "role" })
      };
  public static IEnumerable<ApiScope> ApiScopes =>
      new List<ApiScope>
      {
        new ApiScope("api1", "My API")
      };

  public static IEnumerable<Client> Clients =>
    new List<Client>
    {
      new Client
      {
          ClientId = "client",
          ClientSecrets = { new Secret("secret".Sha256()) },
          AllowedGrantTypes = GrantTypes.ClientCredentials,
          AllowedScopes = { "api1" }
      },
      new Client
      {
          ClientId = "mvc",
          ClientName = "Application Web",
          AllowedGrantTypes = GrantTypes.Hybrid,
          ClientSecrets = { new Secret("secret".Sha256()) },
          RequirePkce = false,
          AllowRememberConsent = false,
          RedirectUris = { "https://localhost:5003/signin-oidc" },
          PostLogoutRedirectUris = { "https://localhost:5003/signout-callback-oidc" },

          AllowedScopes = new List<string>
          {
              IdentityServerConstants.StandardScopes.OpenId,
              IdentityServerConstants.StandardScopes.Profile,
              IdentityServerConstants.StandardScopes.Email,
              "api1",
              "roles"
          }
      }
    };
}
</code>```

Startup.cs in IdentityServer

public class Startup
{
  public IWebHostEnvironment Environment { get; }
  public IConfiguration Configuration { get; }
  public Startup(IWebHostEnvironment environment, IConfiguration configuration)
  {
    Environment = environment;
    Configuration = configuration;
  }
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllersWithViews();
    services.AddRazorPages()
        .AddRazorPagesOptions(options =>
        {
          options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
        });
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
    {
      options.SignIn.RequireConfirmedEmail = true;
    })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    var builder = services.AddIdentityServer(options =>
    {
      options.Events.RaiseErrorEvents = true;
      options.Events.RaiseInformationEvents = true;
      options.Events.RaiseFailureEvents = true;
      options.Events.RaiseSuccessEvents = true;
      options.EmitStaticAudienceClaim = true;
      options.UserInteraction.LoginUrl = "/Account/Login";
      options.UserInteraction.LogoutUrl = "/Account/Logout";
      options.Authentication = new AuthenticationOptions()
      {
        CookieLifetime = TimeSpan.FromHours(10),
                CookieSlidingExpiration = true
      };
    })
        .AddInMemoryIdentityResources(Config.IdentityResources)
        .AddInMemoryApiScopes(Config.ApiScopes)
        .AddInMemoryClients(Config.Clients)
        .AddAspNetIdentity<ApplicationUser>();

    if (Environment.IsDevelopment())
    {
      builder.AddDeveloperSigningCredential();
    }
    services.AddAuthentication()
        .AddGoogle(options =>
        {
          options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
          options.ClientId = "copy client ID from Google here";
          options.ClientSecret = "copy client secret from Google here";
        });

    services.AddTransient<IEmailSender, EmailSender>();
  }
  public void Configure(IApplicationBuilder app)
  {
    if (Environment.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseIdentityServer();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{controller=Home}/{action=Index}/{id?}");
      endpoints.MapRazorPages();
    });
  }
}
```

Body:
I hope these codes will be useful for you.

I added ASP.NET Core Identity in the IdentityServer project.

Statup.cs in API Client

public class Startup
{
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers();
        services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:5001";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiScope", policy =>
            {
                policy.RequireAuthenticatedUser();
                policy.RequireClaim("scope", "api1");
            });
        });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                      .RequireAuthorization("ApiScope");
        });
    }
}

Startup.cs in MVC Client

public class Startup
{
  public IConfiguration Configuration { get; }
  public Startup(IConfiguration configuration)
  {
    Configuration = configuration;
  }
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllersWithViews();
    JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
    services.AddAuthentication(options =>
    {
      options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
      options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
      options.Authority = "https://localhost:5001";
      options.ClientId = "mvc";
      options.ClientSecret = "secret";
      options.ResponseType = "code id_token";
      options.Scope.Add("email");
      options.Scope.Add("roles");
      options.ClaimActions.DeleteClaim("sid");
      options.ClaimActions.DeleteClaim("idp");
      options.ClaimActions.DeleteClaim("s_hash");
      options.ClaimActions.DeleteClaim("auth_time");
      options.ClaimActions.MapJsonKey("role", "role");
      options.Scope.Add("api1");
      options.SaveTokens = true;
      options.GetClaimsFromUserInfoEndpoint = true;
      options.TokenValidationParameters = new TokenValidationParameters
      {
        NameClaimType = "name",
        RoleClaimType = "role"
      };
    });
    services.AddTransient<AuthenticationDelegatingHandler>();
    services.AddHttpClient("ApplicationAPI", client =>
    {
      client.BaseAddress = new Uri("https://localhost:5002/");
      client.DefaultRequestHeaders.Clear();
      client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
    }).AddHttpMessageHandler<AuthenticationDelegatingHandler>();

    services.AddHttpClient("ApplicationIdentityServer", client =>
    {
      client.BaseAddress = new Uri("https://localhost:5001/");
      client.DefaultRequestHeaders.Clear();
      client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
    });
    services.AddHttpContextAccessor();
  }
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
    if (env.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }
    else
    {
      app.UseExceptionHandler("/Home/Error");
      app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{area=Admin}/{controller=Home}/{action=Index}/{id?}");
    });
  }
}

AuthenticationDelegatingHandler in MVC Application

To prevent getting token again.

public class AuthenticationDelegatingHandler : DelegatingHandler
{
  private readonly IHttpContextAccessor _httpContextAccessor;

  public AuthenticationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
  {
    _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
  }

  protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  {
    var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

    if (!string.IsNullOrWhiteSpace(accessToken))
    {
      request.SetBearerToken(accessToken);
    }

    return await base.SendAsync(request, cancellationToken);
  }
}

Config.cs in IdentityServer

public static class Config
{
  public static IEnumerable<IdentityResource> IdentityResources =>
      new List<IdentityResource>
      {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResources.Email(),
        new IdentityResource("roles", "Your role(s)", new List<string>() { "role" })
      };
  public static IEnumerable<ApiScope> ApiScopes =>
      new List<ApiScope>
      {
        new ApiScope("api1", "My API")
      };

  public static IEnumerable<Client> Clients =>
    new List<Client>
    {
      new Client
      {
          ClientId = "client",
          ClientSecrets = { new Secret("secret".Sha256()) },
          AllowedGrantTypes = GrantTypes.ClientCredentials,
          AllowedScopes = { "api1" }
      },
      new Client
      {
          ClientId = "mvc",
          ClientName = "Application Web",
          AllowedGrantTypes = GrantTypes.Hybrid,
          ClientSecrets = { new Secret("secret".Sha256()) },
          RequirePkce = false,
          AllowRememberConsent = false,
          RedirectUris = { "https://localhost:5003/signin-oidc" },
          PostLogoutRedirectUris = { "https://localhost:5003/signout-callback-oidc" },

          AllowedScopes = new List<string>
          {
              IdentityServerConstants.StandardScopes.OpenId,
              IdentityServerConstants.StandardScopes.Profile,
              IdentityServerConstants.StandardScopes.Email,
              "api1",
              "roles"
          }
      }
    };
}

Startup.cs in IdentityServer

public class Startup
{
  public IWebHostEnvironment Environment { get; }
  public IConfiguration Configuration { get; }
  public Startup(IWebHostEnvironment environment, IConfiguration configuration)
  {
    Environment = environment;
    Configuration = configuration;
  }
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllersWithViews();
    services.AddRazorPages()
        .AddRazorPagesOptions(options =>
        {
          options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
        });
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
    {
      options.SignIn.RequireConfirmedEmail = true;
    })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    var builder = services.AddIdentityServer(options =>
    {
      options.Events.RaiseErrorEvents = true;
      options.Events.RaiseInformationEvents = true;
      options.Events.RaiseFailureEvents = true;
      options.Events.RaiseSuccessEvents = true;
      options.EmitStaticAudienceClaim = true;
      options.UserInteraction.LoginUrl = "/Account/Login";
      options.UserInteraction.LogoutUrl = "/Account/Logout";
      options.Authentication = new AuthenticationOptions()
      {
        CookieLifetime = TimeSpan.FromHours(10),
                CookieSlidingExpiration = true
      };
    })
        .AddInMemoryIdentityResources(Config.IdentityResources)
        .AddInMemoryApiScopes(Config.ApiScopes)
        .AddInMemoryClients(Config.Clients)
        .AddAspNetIdentity<ApplicationUser>();

    if (Environment.IsDevelopment())
    {
      builder.AddDeveloperSigningCredential();
    }
    services.AddAuthentication()
        .AddGoogle(options =>
        {
          options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
          options.ClientId = "copy client ID from Google here";
          options.ClientSecret = "copy client secret from Google here";
        });

    services.AddTransient<IEmailSender, EmailSender>();
  }
  public void Configure(IApplicationBuilder app)
  {
    if (Environment.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseIdentityServer();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{controller=Home}/{action=Index}/{id?}");
      endpoints.MapRazorPages();
    });
  }
}


答:
I believe friends[i].islower is giving you the bound method rather than the result of that method. If you want the result, you should call friends[i].islower():

```<code>friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0
while i < len(friends):
    if friends[i].islower() != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1
</code>```

Output:

```<code>Mohamed
Shady
Sherif
</code>```

Title: I wrote a loop that prints only the items in the list that begin with capital letter but islower() method doesnt return True if the item is lower case

Body:
friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0

while i < len(friends):
    if friends[i].islower != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1

print(f"The Number Of The Ignored Names Is {len(ignoredNames)}")

Body:
I believe friends[i].islower is giving you the bound method rather than the result of that method. If you want the result, you should call friends[i].islower():

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0
while i < len(friends):
    if friends[i].islower() != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1

Output:

Mohamed
Shady
Sherif


问:
Laravel: getting blade components syntax error, unexpected 'endif' (T_ENDIF), expecting end of file
I am learning laravel on Laracast however I am having some issues

I have this  code on file components/layout.blade.php

```<code><!DOCTYPE html>
<head>
    <title>Host Cloud Template - Services</title>
</head>

<body>
    {{$content}}
</body>
</code>```

And this on main.blade.php which is the page the view redirects to

```<code><x-layout content = "Hello There">

</x-layout>
</code>```

For some reason Laravel is returning this error:

```<code>syntax error, unexpected 'endif' (T_ENDIF), expecting end of file (View: C:\laragon\www\Conferencias\resources\views\template\main.blade.php)
</code>```

答: I crossed a similar problem, i was calling my component as <x-menu> closing the tag as   <x-menu /> solved the problem!

Body:
I am learning laravel on Laracast however I am having some issues

I have this  code on file components/layout.blade.php

<!DOCTYPE html>

    <title>Host Cloud Template - Services</title>

    {{$content}}

And this on main.blade.php which is the page the view redirects to

<x-layout content = "Hello There">

</x-layout>

For some reason Laravel is returning this error:

syntax error, unexpected 'endif' (T_ENDIF), expecting end of file (View: C:\laragon\www\Conferencias\resources\views\template\main.blade.php)


问:
Overriding the three slashes automatic documentation
Is there a way to automatically fill in the XML documentation created by Visual Studio when you type ///?

I want to auto fill the documentation like the variable name separated based on camel casing.

I could write a Visual Studio Add-In and bind it to different key combination, but wanted to see if there is any other way to do so.

答: You can use either GhostDoc or Resharper with the stylecop plugin.</p>


问:
Element "align" is obsolete or non-standard: what should I use instead?
I have this HTML code:

```<code><td align="center">
</code>```

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

答:
You could  try using .  However, table elements themselves are not really recommended, so it might be Visual Studio's way of trying to force you to use the
 element.

Body:
I have this HTML code:

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

Body: You could  try using <td style="text-align: center;">.  However, table elements themselves are not really recommended, so it might be Visual Studio's way of trying to force you to use the <div> element.


问:
Beginner in Realm Swift - How to instantiate a new Realm in SwiftUI
I have a class DataEntry that I want to store instances of in a Realm database, but i'm having issue instantiating a Realm. Here is my DataEntry class:

```<code>class DataEntry: Object {
    @objc dynamic var id = 0
    @objc dynamic var exercise = ""
    @objc dynamic var weightLBS = 0
    @objc dynamic var averageBarSpeed = 0
    @objc dynamic var topBarSpeed = 0

}
</code>```

Some context as to what I'll be using it for:
I'd like to have functions to write and delete instances of a DataEntry, but the documentation on that seems fairly simple.

Adding new dataEntry would be done by a user inputing data into a form

Deleting dataEntrys will simply be a button

Planning on reading the data to create graphs to track performance over time

The issue I'm having is instantiating a new Realm, and using the appropriate error handling. I've found a few simpler examples, but they all throw errors so i'm assuming there's something i'm missing. I know you're not supposed to use try!, so I'm wondering, what is a simple way to instantiate a new Realm, so I can then read/write/delete DataEntry's to the Realm Database.

This one gives me multiple "Expected Declaration" errors in lines 1 and 3.

```<code>do {
      let realm = try Realm()
    } catch let error as NSError {
      // handle error
    }
</code>```

This one gives me an "Expected Declaration" error on line 1

```<code>try {
    let realm = try Realm()
    } catch {
    print(error.localizedDescription)
    }
</code>```

Any additional pointers on how to best set up this would be amazing, wether or not I should have a RealmManager class that would aid in error handling. I've seen in some cases people create extensions of Realm, but this is a little too advanced for me right now.

Background in CS, but brand new to both Swift and Realm for context.

Edit/Update:

Quick clarification, I'm having issues with instantiating a Realm. Not a Realm object. I've updated above to be more clear.

To clarify my question, I'm getting errors for what appears to be good code above, so I assume I have it in the wrong place. I get errors when its inside the DataEntry class, when its inside of a view, and at the top level of a SwiftUI file. Any advice on where I should include the c ode for the instantiation would be great!

答:
I am not sure if this will help but knowing where to put things within a project can sometimes help understand the flow.

So I created a realm project in XCode that writes a person object with the name of Jay to realm when button 0 is clicked. Then when button 1 is clicked, it retrieves that data and prints to console.

There's no error checking here and I am force unwrapping an optional so don't do that in a real app.

```<code>import Cocoa
import RealmSwift

class PersonClass: Object {
    @Persisted var name = ""
}

class ViewController: NSViewController {

    @IBAction func button0Action(_ sender: Any) {
        let realm = try! Realm()

        let jay = PersonClass()
        jay.name = "Jay"
        try! realm.write {
            realm.add(jay)
        }
    }

    @IBAction func button1Action(_ sender: Any) {
        let realm = try! Realm()
        let jay = realm.objects(PersonClass.self).where { $0.name == "Jay" }.first!
        print(jay.name)  //outputs "Jay" to console
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
</code>```

The project starts with importing RealmSwift and then the Realm object(s) are defined outside of any other classes, so they are at a high level.

Then we have the ViewController with two button actions - as you can see, within each action function, we access realm with

```<code>let realm = try! Realm()
</code>```

and then interact with realm. When that function exits, the realm object is deallocated so it's a safe way to work with Realm and not leave it 'connected'.

Some developers create a singleton or a RealmService class to interact with Realm but singletons can be tricky. I suggest initially going with the pattern shown above (and in the docs).

Body:
I have a class DataEntry that I want to store instances of in a Realm database, but i'm having issue instantiating a Realm. Here is my DataEntry class:

class DataEntry: Object {
    @objc dynamic var id = 0
    @objc dynamic var exercise = ""
    @objc dynamic var weightLBS = 0
    @objc dynamic var averageBarSpeed = 0
    @objc dynamic var topBarSpeed = 0

}

Some context as to what I'll be using it for:
I'd like to have functions to write and delete instances of a DataEntry, but the documentation on that seems fairly simple.

Adding new dataEntry would be done by a user inputing data into a form

Deleting dataEntrys will simply be a button

Planning on reading the data to create graphs to track performance over time

The issue I'm having is instantiating a new Realm, and using the appropriate error handling. I've found a few simpler examples, but they all throw errors so i'm assuming there's something i'm missing. I know you're not supposed to use try!, so I'm wondering, what is a simple way to instantiate a new Realm, so I can then read/write/delete DataEntry's to the Realm Database.

This one gives me multiple "Expected Declaration" errors in lines 1 and 3.

do {
      let realm = try Realm()
    } catch let error as NSError {
      // handle error
    }

This one gives me an "Expected Declaration" error on line 1

try {
    let realm = try Realm()
    } catch {
    print(error.localizedDescription)
    }

Any additional pointers on how to best set up this would be amazing, wether or not I should have a RealmManager class that would aid in error handling. I've seen in some cases people create extensions of Realm, but this is a little too advanced for me right now.

Background in CS, but brand new to both Swift and Realm for context.

Edit/Update:

Quick clarification, I'm having issues with instantiating a Realm. Not a Realm object. I've updated above to be more clear.

To clarify my question, I'm getting errors for what appears to be good code above, so I assume I have it in the wrong place. I get errors when its inside the DataEntry class, when its inside of a view, and at the top level of a SwiftUI file. Any advice on where I should include the c ode for the instantiation would be great!

Body:
I am not sure if this will help but knowing where to put things within a project can sometimes help understand the flow.

So I created a realm project in XCode that writes a person object with the name of Jay to realm when button 0 is clicked. Then when button 1 is clicked, it retrieves that data and prints to console.

There's no error checking here and I am force unwrapping an optional so don't do that in a real app.

import Cocoa
import RealmSwift

class PersonClass: Object {
    @Persisted var name = ""
}

class ViewController: NSViewController {

    @IBAction func button0Action(_ sender: Any) {
        let realm = try! Realm()

        let jay = PersonClass()
        jay.name = "Jay"
        try! realm.write {
            realm.add(jay)
        }
    }

    @IBAction func button1Action(_ sender: Any) {
        let realm = try! Realm()
        let jay = realm.objects(PersonClass.self).where { $0.name == "Jay" }.first!
        print(jay.name)  //outputs "Jay" to console
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

The project starts with importing RealmSwift and then the Realm object(s) are defined outside of any other classes, so they are at a high level.

Then we have the ViewController with two button actions - as you can see, within each action function, we access realm with

let realm = try! Realm()

and then interact with realm. When that function exits, the realm object is deallocated so it's a safe way to work with Realm and not leave it 'connected'.

Some developers create a singleton or a RealmService class to interact with Realm but singletons can be tricky. I suggest initially going with the pattern shown above (and in the docs).


问:
calling subscribe on observable inside try catch block
Can someone explain to me why this is not getting caught by the catch block, I am thinking its because I have a switch map, which would unsubscribe from the first observable. Have commented it out with no luck. The first observable (this.apiPaymentService.deleteStoredPaymentMethod()) is the one causing a 403

```<code>try {
 this.apiPaymentService.deleteStoredPaymentMethod()
    .pipe(
      switchMap(() => this.apiPaymentService.getStoredAchPaymentMethods(),
      catchError((err) => { return throwError(err)})
      ).subscribe()

} catch (error) {
  console.log('I am never called ')
  this.errorModal(error);
}
</code>```

答:
First: Make sure your code parses

If I throw this into my IDE, I get a parsing error immediately. I'll assume you don't want an operator as a second parameter to switchMap and that you've simply forgotten an ) near the end of the line.

What's happening inside your try block?

Inside your try block, you subscribe to an observable. That's it. That's what happens there. The subscription happens without an error. So your try-catch will complete without an error.

If this.apiPaymentService.getStoredAchPaymentMethods() is asyncronous, the try block will have completed (and may not even be on the call stack anymore) before getStoredAchPaymentMethods() resolves with a value.

How to manage Asynchronous Errors

You're already most of the way there! Instead of catching and then rethrowing an error, you can manage it right there.

The following is a no-op:

catchError((err) => { return throwError(err)})
```
<p>But you can return something else instead, or you can retry or something like that :)</p>
<h3>Aside: not just observables</h3>
<p>Here's some old-skool code with the same underlying phenomenon.</p>
<pre class="lang-ts prettyprint-override"><code>function throwErrorFunction() {
  console.log("Throwing an error!");
  throw 'Throwing an error from my throw error function';
}

try {
  setTimeout(throwErrorFunction, 5000);
} catch (error) {
  console.log('I am never called ');
}
</code>```

Here's a way to think about this. The code above never calls the throwErrorFunction. Function application in JavaScript is done wiht parenthesis. So you'd need something like throwErrorFunction() somewhere in order to call the function. But that never happens here.

But somehow the console will still read "Throwing an error!". So how does that happen if we've not called throwErrorFunction? Well... setTimeout eventually calls throwErrorFunction for us! In this case, it waits 5 seconds and then calls the function.

But by the time five seconds have elapsed, the try-catch statement has already been executed. Same deal as before! :)

Body:
Can someone explain to me why this is not getting caught by the catch block, I am thinking its because I have a switch map, which would unsubscribe from the first observable. Have commented it out with no luck. The first observable (this.apiPaymentService.deleteStoredPaymentMethod()) is the one causing a 403

try {
 this.apiPaymentService.deleteStoredPaymentMethod()
    .pipe(
      switchMap(() => this.apiPaymentService.getStoredAchPaymentMethods(),
      catchError((err) => { return throwError(err)})
      ).subscribe()

} catch (error) {
  console.log('I am never called ')
  this.errorModal(error);
}

Body:
First: Make sure your code parses

If I throw this into my IDE, I get a parsing error immediately. I'll assume you don't want an operator as a second parameter to switchMap and that you've simply forgotten an ) near the end of the line.

What's happening inside your try block?

Inside your try block, you subscribe to an observable. That's it. That's what happens there. The subscription happens without an error. So your try-catch will complete without an error.

If this.apiPaymentService.getStoredAchPaymentMethods() is asyncronous, the try block will have completed (and may not even be on the call stack anymore) before getStoredAchPaymentMethods() resolves with a value.

How to manage Asynchronous Errors

You're already most of the way there! Instead of catching and then rethrowing an error, you can manage it right there.

The following is a no-op:

catchError((err) => { return throwError(err)})

But you can return something else instead, or you can retry or something like that :)

Aside: not just observables

Here's some old-skool code with the same underlying phenomenon.

function throwErrorFunction() {
  console.log("Throwing an error!");
  throw 'Throwing an error from my throw error function';
}

try {
  setTimeout(throwErrorFunction, 5000);
} catch (error) {
  console.log('I am never called ');
}

Here's a way to think about this. The code above never calls the throwErrorFunction. Function application in JavaScript is done wiht parenthesis. So you'd need something like throwErrorFunction() somewhere in order to call the function. But that never happens here.

But somehow the console will still read "Throwing an error!". So how does that happen if we've not called throwErrorFunction? Well... setTimeout eventually calls throwErrorFunction for us! In this case, it waits 5 seconds and then calls the function.

But by the time five seconds have elapsed, the try-catch statement has already been executed. Same deal as before! :)


问:
NumberOfDiscIntersections overflow in codility test
In the codility test NumberOfDiscIntersections I am getting perf 100% and correctness 87% with the one test failing being

```<code>overflow
arithmetic overflow tests
got -1 expected 2
</code>```

I can't see what is causing that given that I am using long which is 64-bit. And even if I can get it to 100% perf 100% correctness I am wondering if there is a better way to do this that is not as verbose in Java.

edit: figured out a much better way to do with with two arrays rather than a pair class

```<code>// you can also use imports, for example:
 import java.util.*;

// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
        int j = 0;
        Pair[] arr = new Pair[A.length * 2];
        for (int i = 0; i < A.length; i++) {
            Pair s = new Pair(i - A[i], true);
            arr[j] = s;
            j++;
            Pair e = new Pair(i + A[i], false);
            arr[j] = e;
            j++;
        }
        Arrays.sort(arr, new Pair(0, true));

        long numIntersect = 0;
        long currentCount = 0;
        for (Pair p: arr) {
            if (p.start) {
                numIntersect += currentCount;
                if (numIntersect > 10000000) {
                    return -1;
                }
                currentCount++;
            } else {
                currentCount--;
            }
        }

        return (int) numIntersect;
    }

    static private class Pair implements Comparator<Pair> {
        private long x;
        private boolean start;
        public Pair(long x, boolean start) {
            this.x = x;
            this.start = start;
        }

        public int compare(Pair p1, Pair p2) {
            if (p1.x < p2.x) {
                return -1;
            } else if (p1.x > p2.x) {
                return 1;
            } else {
                if (p1.start && p2.start == false) {
                    return -1;
                } else if (p1.start == false && p2.start) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }
}
</code>```

答:
This one in Python passed all "Correctness tests" and failed all "Performance tests" due to O(n²), so I got 50% score. But it is very simple to understand. I just used the right radius (maximum) and checked if it was bigger or equal to the left radius (minimum) of the next circles. I also avoided to use sort and did not check twice the same circle. Later I will try to improve performance, but the problem here for me was the algorithm. I tried to find a very easy solution to help explain the concept. Maybe this will help someone.</p>
```<code>def solution(A):
     n = len(A)
     cnt = 0

     for j in range(1,n):
         for i in range(n-j):
             if(i+A[i]>=i+j-A[i+j]):
                 cnt+=1

     if(cnt>1e7):
         return -1
     return cnt
</code>```

Body:
In the codility test NumberOfDiscIntersections I am getting perf 100% and correctness 87% with the one test failing being

overflow
arithmetic overflow tests
got -1 expected 2

I can't see what is causing that given that I am using long which is 64-bit. And even if I can get it to 100% perf 100% correctness I am wondering if there is a better way to do this that is not as verbose in Java.

edit: figured out a much better way to do with with two arrays rather than a pair class

// you can also use imports, for example:
 import java.util.*;

// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
        int j = 0;
        Pair[] arr = new Pair[A.length * 2];
        for (int i = 0; i  10000000) {
                    return -1;
                }
                currentCount++;
            } else {
                currentCount--;
            }
        }

        return (int) numIntersect;
    }

    static private class Pair implements Comparator<Pair> {
        private long x;
        private boolean start;
        public Pair(long x, boolean start) {
            this.x = x;
            this.start = start;
        }

        public int compare(Pair p1, Pair p2) {
            if (p1.x < p2.x) {
                return -1;
            } else if (p1.x > p2.x) {
                return 1;
            } else {
                if (p1.start && p2.start == false) {
                    return -1;
                } else if (p1.start == false && p2.start) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }
}

Body:
This one in Python passed all "Correctness tests" and failed all "Performance tests" due to O(n²), so I got 50% score. But it is very simple to understand. I just used the right radius (maximum) and checked if it was bigger or equal to the left radius (minimum) of the next circles. I also avoided to use sort and did not check twice the same circle. Later I will try to improve performance, but the problem here for me was the algorithm. I tried to find a very easy solution to help explain the concept. Maybe this will help someone.

def solution(A):
     n = len(A)
     cnt = 0

     for j in range(1,n):
         for i in range(n-j):
             if(i+A[i]>=i+j-A[i+j]):
                 cnt+=1

     if(cnt>1e7):
         return -1
     return cnt


问:
How to import a module that isn't in the same folder?
I'm having problem with a project, in order to organize it I'm subdividing it into diferentes folders and I'm not getting import a module that are in a different folder. Anyone knows how can I resolve this trouble ?</p>

答: Use import folder.modulename. This should work


问:
Why column must appear in the GROUP BY?
I have this:

```<code>SELECT name, value,
       MIN(value) as find_min
FROM history
WHERE date_num >= 1609459200
  AND date_num <= 1640995200
  AND name IN('A')
GROUP BY name
</code>```

Trying to get the minimum value between dates for each subject separately :

```<code>name value
A.    3
B     4
C     9
A     0
C     2
</code>```

I keep getting this popular error:

column "history.value" must appear in the GROUP BY clause or be used in an aggregate function

I read this must appear in the GROUP BY clause or be used in an aggregate function

and I still do not understand:

Why I have to include in GROUP BY everything? what is the logic?

Why is this not working?

is Min() over (partition by name) better, and if so, how can I get only a single result per name?

EDIT:

If I try:GROUP BY name, find_min it will fail as well, even though in this case he can produce a unique result (the all the same)

答:
try like below

```<code>SELECT name,
MIN(value) as find_min
FROM history
WHERE date_num >= 1609459200 AND date_num <= 1640995200
GROUP BY name
</code>```

I removed name in ('A') because your are searching for all name min value so it will restrict just A

Title: Why column must appear in the GROUP BY?

Body:
I have this:

SELECT name, value,
       MIN(value) as find_min
FROM history
WHERE date_num >= 1609459200
  AND date_num <= 1640995200
  AND name IN('A')
GROUP BY name

Trying to get the minimum value between dates for each subject separately :

name value
A.    3
B     4
C     9
A     0
C     2

I keep getting this popular error:

column "history.value" must appear in the GROUP BY clause or be used in an aggregate function

I read this must appear in the GROUP BY clause or be used in an aggregate function

and I still do not understand:

Why I have to include in GROUP BY everything? what is the logic?

Why is this not working?

is Min() over (partition by name) better, and if so, how can I get only a single result per name?

EDIT:

If I try:GROUP BY name, find_min it will fail as well, even though in this case he can produce a unique result (the all the same)

Body:
try like below

SELECT name,
MIN(value) as find_min
FROM history
WHERE date_num >= 1609459200 AND date_num <= 1640995200
GROUP BY name

I removed name in ('A') because your are searching for all name min value so it will restrict just A


问:
get the printers in java from the AS400 server
I can't get the printers on the AS400.

I tried :

```<code>PrintService[] services = PrinterJob.lookupPrintServices();
</code>```

No services has been found.

I also searched on JTOpen API. I didn't find anything.

Somebody can help me ?

答:
PrinterJob.lookupPrintService() defaults to DocFlavor.SERVICE_FORMATTED.PAGEABLE flavor. Could be you have no printers supporting that flavor.

Try running this to check if there are ANY printers found

```<code>PrintService[] allServices =
           PrintServiceLookup.lookupPrintServices(null, null);
       for (PrintService ps : allServices)
       {
           System.out.println(ps  " supports :");
           DocFlavor[] flavors = ps.getSupportedDocFlavors();
           for (int i = 0; i < flavors.length; i+</i>)
           {
               System.out.println("\t" + flavors[i]);
           }
       }
</code>```

And check what kinds of flavors they support.

Also, are you on iSeries? OS 400? And which Java?

Body:
I can't get the printers on the AS400.

I tried :

PrintService[] services = PrinterJob.lookupPrintServices();

No services has been found.

I also searched on JTOpen API. I didn't find anything.

Somebody can help me ?

Body:
PrinterJob.lookupPrintService() defaults to DocFlavor.SERVICE_FORMATTED.PAGEABLE flavor. Could be you have no printers supporting that flavor.

Try running this to check if there are ANY printers found

PrintService[] allServices =
           PrintServiceLookup.lookupPrintServices(null, null);
       for (PrintService ps : allServices)
       {
           System.out.println(ps  " supports :");
           DocFlavor[] flavors = ps.getSupportedDocFlavors();
           for (int i = 0; i < flavors.length; i+</i>)
           {
               System.out.println("\t" + flavors[i]);
           }
       }

And check what kinds of flavors they support.

Also, are you on iSeries? OS 400? And which Java?