问:
How to get the column names along with the rows by using pivot stage in datastage
I have a table in format

```<code>Data:
ID Sev1 Sev2 Sev3
ABC 0.45 1 1
PQR 0.45 1 2
XYZ 0.45 1 1
</code>```

I want to change this to the new format as below by using horizontal pivot . How can  i get column names ( severity ) as well along with its data

Expected Output:

```<code>    ID Severity Values
    ABC Sev1 0.45
    ABC Sev2 1
    ABC Sev3 1
    PQR Sev1 0.45
    PQR Sev2 1
    PQR Sev3 2
    XYZ Sev1 0.45
    XYZ Sev2 1
    XYZ Sev3 1
</code>```

To bring the column names as rows and add along with the corresponding values

After converting using horizontal pivot and after then i am using CDC stage to define if its an insert or update record with CDC_Changecode = 1 or CdcChangeCode = 3. Please find below sample data

```<code>    ID Severity Values CDCCode
    ABC Sev1 0.45   1
    ABC Sev2 1      1
    ABC Sev3 1      1
    PQR Sev1 0.45   3
    PQR Sev2 1      3
    PQR Sev3 2      3
    XYZ Sev1 0.45   3
    XYZ Sev2 1      3
    XYZ Sev3 1      3
</code>```

Once i get this output after using CDC stage ( 1 = Insert record , 3 = Update record ) then i want to convert them columns to rows using vertical pivot. When

Expected output after vertical pivot

CDC Code = 1 ( insert record - i am trying to get below data as ouput )

```<code>    ID  Sev1   Sev2 Sev3
    ABC 0.45   1
    PQR        1
</code>```

CDC Code = 3 ( Update record - i am trying to get below data as ouput )

```<code>    ID  Sev1   Sev2 Sev3
    ABC             1
    PQR 0.45        2
    XYZ 0.45   1    1
</code>```

答:
Check the Pivot Index checkbox on the Pivot Properties tab.

Then add the additional column to your output on the mapping tab.
This will generate a column with a number - the index of the column pivoted.

In a additional step you could then transform the numbers back into column names

Body:
I have a table in format

Data:
ID Sev1 Sev2 Sev3
ABC 0.45 1 1
PQR 0.45 1 2
XYZ 0.45 1 1

I want to change this to the new format as below by using horizontal pivot . How can  i get column names ( severity ) as well along with its data

Expected Output:

    ID Severity Values
    ABC Sev1 0.45
    ABC Sev2 1
    ABC Sev3 1
    PQR Sev1 0.45
    PQR Sev2 1
    PQR Sev3 2
    XYZ Sev1 0.45
    XYZ Sev2 1
    XYZ Sev3 1

To bring the column names as rows and add along with the corresponding values

After converting using horizontal pivot and after then i am using CDC stage to define if its an insert or update record with CDC_Changecode = 1 or CdcChangeCode = 3. Please find below sample data

    ID Severity Values CDCCode
    ABC Sev1 0.45   1
    ABC Sev2 1      1
    ABC Sev3 1      1
    PQR Sev1 0.45   3
    PQR Sev2 1      3
    PQR Sev3 2      3
    XYZ Sev1 0.45   3
    XYZ Sev2 1      3
    XYZ Sev3 1      3

Once i get this output after using CDC stage ( 1 = Insert record , 3 = Update record ) then i want to convert them columns to rows using vertical pivot. When

Expected output after vertical pivot

CDC Code = 1 ( insert record - i am trying to get below data as ouput )

    ID  Sev1   Sev2 Sev3
    ABC 0.45   1
    PQR        1

CDC Code = 3 ( Update record - i am trying to get below data as ouput )

    ID  Sev1   Sev2 Sev3
    ABC             1
    PQR 0.45        2
    XYZ 0.45   1    1


来源: stackexchange

问:
Setting the character encoding in form submit for Internet Explorer
I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?

Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.

```<code><form accept-charset="ISO-8859-1">
  ...
</form>
</code>```

Edit: This form is created by server A and will be submitted to server B. I have no control over server B.

If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question about setting the encoding in server A.

答:
I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.

Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.

```<code><form accept-charset="ISO-8859-15">
  ...
</form>
</code>```

So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.

OwnerDisplayName: Juha

ContentLicense: CC BY-SA 2.5

Body:
I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?

Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.

<form accept-charset="ISO-8859-1">
  ...
</form>

Edit: This form is created by server A and will be submitted to server B. I have no control over server B.

If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question about setting the encoding in server A.

LastEditorDisplayName: Juha

Body:
I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.

Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.

<form accept-charset="ISO-8859-15">
  ...
</form>

So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.

ContentLicense: CC BY-SA 3.0


问:
Problem with configuring c++ project in QtCreator
I have some c++ code (Snowboy demo - demo.cc) and successfully build it on my RaspPI Zero using g++:

```<code>g++ -D_GLIBCXX_USE_CXX11_ABI=0 -fPIC -I../../ -std=c++0x -Wall -Wno-sign-compare -Wno-unused-local-typedefs -Winit-self -rdynamic -DHAVE_POSIX_MEMALIGN -Iportaudio/install/include -O3    demo.cc portaudio/install/lib/libportaudio.a ../..//lib/rpi/libsnowboy-detect.a   -ldl -lm -Wl,-Bstatic -Wl,-Bdynamic -lrt -lpthread portaudio/install/lib/libportaudio.a -L/usr/lib/atlas-base -lf77blas -lcblas -llapack_atlas -latlas -lasound -o demo
</code>```

To debug it I try to use QtCreator and create Qt project file:

```<code>QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle

HEADERS += demo.h
SOURCES += \
        demo.cc

INCLUDEPATH += ../../
INCLUDEPATH += portaudio/install/include

LIBS += -Lportaudio/install/lib \
    -lportaudio \
    -L../../lib/rpi -lsnowboy-detect \
    -L/usr/lib/atlas-base \
    -ldl -lm -lrt -lpthread \
    -lf77blas -lcblas -llapack_atlas -latlas -lasound
</code>```

But with this configuration in QtCreator I receive build errors:

```<code>/home/pi/Prj/snowboy/examples/C++/demo.cc:213: error: undefined reference to `snowboy::SnowboyDetect::SnowboyDetect(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
</code>```

Did I forget to specify any parameters that was used with g++ in Qt project file?

Is it possible you advise me a simple way to debug c++ code with external dependencies in Raspb Pi zero?

答:
Snowboy for some ungodly reason requires you to use -D_GLIBCXX_USE_CXX11_ABI=0 (google it). You have this flag in your command line, which is correct in the context of Snowboy, but are missing it in your .pro file. Add it.

```<code>QMAKE_CPPFLAGS += -D_GLIBCXX_USE_CXX11_ABI=0
</code>```

or something like that.

You can also try downgrading your language standard option to C++98 (not recommended but should work if your demo is not using any c++11-specific code).

I personally think that any software that is still using -D_GLIBCXX_USE_CXX11_ABI=0 in 2019 needs to be scrapped or forked, but whatever floats your boat.

ContentLicense: CC BY-SA 4.0

Body:
I have some c++ code (Snowboy demo - demo.cc) and successfully build it on my RaspPI Zero using g++:

g++ -D_GLIBCXX_USE_CXX11_ABI=0 -fPIC -I../../ -std=c++0x -Wall -Wno-sign-compare -Wno-unused-local-typedefs -Winit-self -rdynamic -DHAVE_POSIX_MEMALIGN -Iportaudio/install/include -O3    demo.cc portaudio/install/lib/libportaudio.a ../..//lib/rpi/libsnowboy-detect.a   -ldl -lm -Wl,-Bstatic -Wl,-Bdynamic -lrt -lpthread portaudio/install/lib/libportaudio.a -L/usr/lib/atlas-base -lf77blas -lcblas -llapack_atlas -latlas -lasound -o demo

To debug it I try to use QtCreator and create Qt project file:

QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle

HEADERS += demo.h
SOURCES += \
        demo.cc

INCLUDEPATH += ../../
INCLUDEPATH += portaudio/install/include

LIBS += -Lportaudio/install/lib \
    -lportaudio \
    -L../../lib/rpi -lsnowboy-detect \
    -L/usr/lib/atlas-base \
    -ldl -lm -lrt -lpthread \
    -lf77blas -lcblas -llapack_atlas -latlas -lasound

But with this configuration in QtCreator I receive build errors:

/home/pi/Prj/snowboy/examples/C++/demo.cc:213: error: undefined reference to `snowboy::SnowboyDetect::SnowboyDetect(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'

Did I forget to specify any parameters that was used with g++ in Qt project file?

Is it possible you advise me a simple way to debug c++ code with external dependencies in Raspb Pi zero?

Body:
Snowboy for some ungodly reason requires you to use -D_GLIBCXX_USE_CXX11_ABI=0 (google it). You have this flag in your command line, which is correct in the context of Snowboy, but are missing it in your .pro file. Add it.

QMAKE_CPPFLAGS += -D_GLIBCXX_USE_CXX11_ABI=0

or something like that.

You can also try downgrading your language standard option to C++98 (not recommended but should work if your demo is not using any c++11-specific code).

I personally think that any software that is still using -D_GLIBCXX_USE_CXX11_ABI=0 in 2019 needs to be scrapped or forked, but whatever floats your boat.


问:
Android vitals and exception handling
I have been writing a simple Android application (one Activity).

I would really like to gather crash reports from actual user sessions. I know there are some nice 3rd-party libraries. I also read that Google Play Console (Android vitals) should be providing some basic telemetry including crash reports. I was thinking that, to keep things simple, I would stick with the Android vitals for now.

I was wondering whether there is anything I need to do on the Application side to get the crash reports. Or should I just simply let the App crash?

I handle exception that can be handled, but there is always a possibility that one makes it to, say, onCreate. 'onCreate' does not allow throwing checked exceptions though. If I cannot handle it, should I just wrap it in Runtime exception and throw that instead?

Thanks.

答:
Here's an article for a similar approach, https://proandroiddev.com/hide-your-crashes-gracefully-and-still-report-them-9b1c85b25875 However it does not rely on the Android OS crash reporting process; i.e. I don't think you would see the crashes in Android Vitals if you follow the steps described in the article.

You might be able to adapt it though, mainly in terms of restarting the app after the crash occurs.

Title: Android vitals and exception handling


问:
How to avoid duplication record?
I'm using a 'save' button to insert new record to another sheet. But I want to avoid inserting same data (a data is same if name + lastname + birthday are equals to new data). I'm trying the following code but it's too slow and not working. What are wrong with the code below ? Thanks</p>

```<code>Sub saveFormData()

  Dim name As String, lastname As String, birthday As String

  ' Get last empty row
  lastRow = Sheets("saveData").Cells(Rows.Count, 1).End(xlUp).Row + 1
  name = Worksheets("form").Range("A1").Value
  lastname = Worksheets("form").Range("A2").Value
  birthday = Worksheets("form").Range("A3").Value

  For i = 2 To lastRow

    ' Check if data exist (record is unique if we have name + lastname + birthday

    If Worksheets("saveData").Range("A" & lastRow).Value = name and Worksheets("saveData").Range("B" & lastRow).Value = lastname and Worksheets("saveData").Range("C" & lastRow).Value = birthday Then

      MsgBox "Data already exist"

      Exit Sub 'Exit from Sub

  End If
 Next

' Save name
Worksheets("saveData").Range("A" & lastRow).Value = name

' Save lastname
Worksheets("saveData").Range("B" & lastRow).Value = lastname

   ' Save birthday
   Worksheets("saveData").Range("C" & lastRow).Value = birthday

   End Sub
</code>```

答:
Working with arrays and dictionaries is always the fastest way to read large amounts of data:

```<code>Option Explicit
Sub saveFormData()

    Dim arrSaveData
    Dim LastRow As Long
    Dim SavedData As New Scripting.Dictionary 'Need Microsoft Scripting Runtime reference to work
    Dim i As Long

    'store the saved data inside the array
    With ThisWorkbook.Sheets("saveData")
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        arrSaveData = .Range("A2:C" & LastRow)
    End With

    'Save every entry into the dictionary
    For i = LBound(arrSaveData) To UBound(arrSaveData)
        SavedData.Add arrSaveData(i, 1) & arrSaveData(i, 2) & arrSaveData(i, 3), 1
    Next i

    Dim name As String, lastname As String, birthday As String

    'store your variables
    With ThisWorkbook.Sheets("form")
        name = .Range("A1")
        lastname = .Range("A2")
        birthday = .Range("A3")
    End With

    'Check if the new entry doesn't exists and if it doesn't add it
    With ThisWorkbook.Sheets("SaveData")
        If Not SavedData.Exists(name & lastname & birthday) Then
            LastRow = LastRow + 1
            .Cells(LastRow, 1) = name
            .Cells(LastRow, 2) = lastname
            .Cells(LastRow, 3) = birthday
        Else
            MsgBox "Data already exists."
        End If
    End With

End Sub
</code>```

The code might not work if your birthdaydata are dates, the array will store them as dates and your birthdayvariable is a string, so in that case you should switch birthday As Date

Title: How to avoid duplication record?

Body:
I'm using a 'save' button to insert new record to another sheet. But I want to avoid inserting same data (a data is same if name + lastname + birthday are equals to new data). I'm trying the following code but it's too slow and not working. What are wrong with the code below ? Thanks

Sub saveFormData()

  Dim name As String, lastname As String, birthday As String

  ' Get last empty row
  lastRow = Sheets("saveData").Cells(Rows.Count, 1).End(xlUp).Row + 1
  name = Worksheets("form").Range("A1").Value
  lastname = Worksheets("form").Range("A2").Value
  birthday = Worksheets("form").Range("A3").Value

  For i = 2 To lastRow

    ' Check if data exist (record is unique if we have name + lastname + birthday

    If Worksheets("saveData").Range("A" & lastRow).Value = name and Worksheets("saveData").Range("B" & lastRow).Value = lastname and Worksheets("saveData").Range("C" & lastRow).Value = birthday Then

      MsgBox "Data already exist"

      Exit Sub 'Exit from Sub

  End If
 Next

' Save name
Worksheets("saveData").Range("A" & lastRow).Value = name

' Save lastname
Worksheets("saveData").Range("B" & lastRow).Value = lastname

   ' Save birthday
   Worksheets("saveData").Range("C" & lastRow).Value = birthday

   End Sub

Body:
Working with arrays and dictionaries is always the fastest way to read large amounts of data:

Option Explicit
Sub saveFormData()

    Dim arrSaveData
    Dim LastRow As Long
    Dim SavedData As New Scripting.Dictionary 'Need Microsoft Scripting Runtime reference to work
    Dim i As Long

    'store the saved data inside the array
    With ThisWorkbook.Sheets("saveData")
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        arrSaveData = .Range("A2:C" & LastRow)
    End With

    'Save every entry into the dictionary
    For i = LBound(arrSaveData) To UBound(arrSaveData)
        SavedData.Add arrSaveData(i, 1) & arrSaveData(i, 2) & arrSaveData(i, 3), 1
    Next i

    Dim name As String, lastname As String, birthday As String

    'store your variables
    With ThisWorkbook.Sheets("form")
        name = .Range("A1")
        lastname = .Range("A2")
        birthday = .Range("A3")
    End With

    'Check if the new entry doesn't exists and if it doesn't add it
    With ThisWorkbook.Sheets("SaveData")
        If Not SavedData.Exists(name & lastname & birthday) Then
            LastRow = LastRow + 1
            .Cells(LastRow, 1) = name
            .Cells(LastRow, 2) = lastname
            .Cells(LastRow, 3) = birthday
        Else
            MsgBox "Data already exists."
        End If
    End With

End Sub

The code might not work if your birthdaydata are dates, the array will store them as dates and your birthdayvariable is a string, so in that case you should switch birthday As Date


问:
Import null values in MongoDB Compass
I'm importing data with csv in MongoDB Compass, but some values must be null. In MySQL Workbench we use '\N' to import that null values, for MongoDB what i should use? </p>

答:
You can just insert null into mongo.

Note that this is different from not inserting the field at all.
See the docs below on 'null' and non-existent: https://docs.mongodb.com/manual/tutorial/query-for-null-fields/

Title: Import null values in MongoDB Compass


问:
How do I call a function passing in a matrix in APL?
How do i call a function that i just wrote in APL, passing in a matrix? I have already tried many things but I can't seem to find the solution. I would greatly appreciate any help.
I don't think this is a duplicate but please report if you find one :)
Thanks</p>

答:
Unless you declare otherwise, an APL function will accept any array as argument. For example, let's define a function which multiplies its argument by 2 and then adds 1:

```<code>      ∇ result←t2p1 argument
        result←1+2×argument
      ∇
</code>```

Now we define a 3-by-4 matrix of some numbers, and ask for its value:

```<code>      matrix←3 4⍴3 1 4 1 5
      matrix
3 1 4 1
5 3 1 4
1 5 3 1
</code>```

Finally, we apply the function to the matrix:

```<code>      t2p1 matrix
 7  3 9 3
11  7 3 9
 3 11 7 3
</code>```

Body:
Unless you declare otherwise, an APL function will accept any array as argument. For example, let's define a function which multiplies its argument by 2 and then adds 1:

      ∇ result←t2p1 argument
        result←1+2×argument
      ∇

Now we define a 3-by-4 matrix of some numbers, and ask for its value:

      matrix←3 4⍴3 1 4 1 5
      matrix
3 1 4 1
5 3 1 4
1 5 3 1

Finally, we apply the function to the matrix:

      t2p1 matrix
 7  3 9 3
11  7 3 9
 3 11 7 3


问:
How does a bin folder that is excluded from a project affect automated builds?
We do automated builds using Nant and CruiseControl.net. I'm very green when it comes to the process. While looking into some things, I noticed that for most(all?) of the solutions involved in the automated build process, the bin folders are included in the project. Is this a requirement for automated builds? If the bin folder is excluded, will the folder and any files in it need to be copied to the deployment servers manually?

Thanks.

答:
It is better to include bin folder in the automated build process, since it contains some external dlls like AjaxControlToolkit along with internal dlls.

We here excluded the Debug folder and user option files(*.suo) from the automated build.


问:
Alter query string param based off of checkboxes in react native
I'm able to successfully run this code when a box is checked to filter results:

```<code>changeCheck = (index, acronym) => {
        if(!this.state.checkedLeagues.includes(acronym)){
            this.state.checkedLeagues.push(acronym)
        } else {
            this.setState({checkedLeagues: this.state.checkedLeagues.filter(v => { return v !== acronym})})
        }
        this.state.checked[index] = !this.state.checked[index]
        this.setState({ checked: this.state.checked })

        queryString = []

        console.log('newLeagues', newLeagues)

        this.state.checkedLeagues.map(
            (v, i) => {
                if(queryString.length < 1) {
                    queryString.push(`?league=${v}`)
                } else if (queryString.length >= 1 ) {
                    queryString.push(`&league=${v}`)
                }
            }
        )

        // console.log(queryString.join(''))

        axios.get(`http://localhost:4000/reports${queryString.join('')}`)
                .then(response => {
                    this.props.loadCards(response.data)
                })
    }
</code>```

The issue comes when a box is unchecked.

I need a way to remove the box that was unchecked from queryString if it already exists in this.state.checked.

The value that is checked or unchecked is passed in on onPress/onClick through acronym.

Edit:

As an example:
If this.state.checkedLeagues is an array of leagues ['NBA', 'NFL'], I only want to set those as query string paramaters in the axios get request.

If I set the checkedLeagues to ['NBA', 'NFL'], it works. But when I uncheck it does not; lets say I uncheck 'NBA' (when I say uncheck, I mean remove from the queryString), it does not, because I do not have a mechanism remove the unchecked box from queryString.

答:
```<code> this.state = {
        checkList: [],
    };

checkInvoice = (index) => {
    const { checkList } = this.state
    const newCheckList = checkList;
    const indexElem = newCheckList.indexOf(index);
    if (indexElem > -1) {
        newCheckList.splice(indexElem, 1);
    } else {
        newCheckList.push(index);
    }
    this.setState({ checkList: newCheckList })
};
</code>```

From here you need to connect to your code and query...
tell me if it ok

Body:
I'm able to successfully run this code when a box is checked to filter results:

changeCheck = (index, acronym) => {
        if(!this.state.checkedLeagues.includes(acronym)){
            this.state.checkedLeagues.push(acronym)
        } else {
            this.setState({checkedLeagues: this.state.checkedLeagues.filter(v => { return v !== acronym})})
        }
        this.state.checked[index] = !this.state.checked[index]
        this.setState({ checked: this.state.checked })

        queryString = []

        console.log('newLeagues', newLeagues)

        this.state.checkedLeagues.map(
            (v, i) => {
                if(queryString.length < 1) {
                    queryString.push(`?league=${v}`)
                } else if (queryString.length >= 1 ) {
                    queryString.push(`&league=${v}`)
                }
            }
        )

        // console.log(queryString.join(''))

        axios.get(`http://localhost:4000/reports${queryString.join('')}`)
                .then(response => {
                    this.props.loadCards(response.data)
                })
    }

The issue comes when a box is unchecked.

I need a way to remove the box that was unchecked from queryString if it already exists in this.state.checked.

The value that is checked or unchecked is passed in on onPress/onClick through acronym.

Edit:

As an example:
If this.state.checkedLeagues is an array of leagues ['NBA', 'NFL'], I only want to set those as query string paramaters in the axios get request.

If I set the checkedLeagues to ['NBA', 'NFL'], it works. But when I uncheck it does not; lets say I uncheck 'NBA' (when I say uncheck, I mean remove from the queryString), it does not, because I do not have a mechanism remove the unchecked box from queryString.

Body:
 this.state = {
        checkList: [],
    };

checkInvoice = (index) => {
    const { checkList } = this.state
    const newCheckList = checkList;
    const indexElem = newCheckList.indexOf(index);
    if (indexElem > -1) {
        newCheckList.splice(indexElem, 1);
    } else {
        newCheckList.push(index);
    }
    this.setState({ checkList: newCheckList })
};

From here you need to connect to your code and query...
tell me if it ok


问:
How to create sublist based on condition in Java
I have a list of String

```<code>List<String> strings = new ArrayList<>(Arrays.asList("C", "C++", "Java"));
</code>```

And now I want to create another list, which would contain all elements of strings that contain "C". So I believe that the condition would look like this:

```<code>(String a) -> a.contains("C");
</code>```

What is the fastest and most clear way to do that?

答:
I recommend streaming the List and then using Stream#filter to filter through any elements that contain the letter 'C':

```<code>List<String> filteredList = strings.stream()
        .filter(s -> s.contains("C"))
        .collect(Collectors.toList());
</code>```

Printing filteredList will yield the following:

```<code>[C, C++]
</code>```

Body:
I have a list of String

List<String> strings = new ArrayList<>(Arrays.asList("C", "C++", "Java"));

And now I want to create another list, which would contain all elements of strings that contain "C". So I believe that the condition would look like this:

(String a) -> a.contains("C");

What is the fastest and most clear way to do that?

Body:
I recommend streaming the List and then using Stream#filter to filter through any elements that contain the letter 'C':

List<String> filteredList = strings.stream()
        .filter(s -> s.contains("C"))
        .collect(Collectors.toList());

Printing filteredList will yield the following:

[C, C++]


问:
R: How to classify strings based on a set of regular expressions
I have a vector of text strings that describe the sources for images in a book, but not in an entirely consistent format--- they are captured from the LaTeX source & written to a text file.

I need to process these and collect information about the source attribution
and permission status.  A sample of strings looks like this:

```<code>strings <- '
GBD 2016 Alcohol Collaborators (2018)
\citet {DeBoldFriedman:2015}, permission required
Author graphic, using various public domain images
\url {http://www.histogames.com/HTML/inventaire/periodes-historiques/prehistoire.php}
\url {https://commons.wikimedia.org/wiki/File:Egyptmotionseries.jpg}
\url {http://commons.wikimedia.org}, public domain.
\citet {Plot:1685}, author image collection
Author image collection
 From \citet {Priestley:1765}, author image collection
 Author image collection
 Courtesy Library of Congress
\citet {Langren:1644}, image courtesy of the Koninklijke Bibliotheek van Belgi\"e
Public domain
Author graphic
Author graphic
Author graphic
Author image collection
Wikipedia, https://commons.wikimedia.org/wiki/File:Tablas\_alfonsies.jpg, public domain
'
</code>```

One main task is to create a variable status indicating permission status by finding
matches to simple regular expressions in the strings.  The categories can be defined by
the following patterns, all of which should be matched to the text of the strings
w/o regard to case.

```<code>AUpat <- "author (image|graphic|collection)"
PDpat <- "public domain"
REQpat <- "permission required"
LIBpat <- "courtesy|by permission"

# or as a list:
pats <- list(
  'AU' = "author (image|graphic|collection)",
  'PD' = "public domain",
  'REQ'= "permission required",
  'LIB'= "courtesy|by permission"
)
</code>```

Pseudo code to do what I want (doesn't work):

```<code>status <- rep("", length(strings))
for(i in seq_along(strings)) {
  if      (grep(AUpat, strings[i],  ignore.case=TRUE)) status[i] <- "AU"
  else if (grep(PDpat, strings[i],  ignore.case=TRUE)) status[i] <- "PD"
  else if (grep(REQpat, strings[i], ignore.case=TRUE)) status[i] <- "REQ"
  else if (grep(LIBpat, strings[i], ignore.case=TRUE)) status[i] <- "LIB"
}
</code>```

This is ugly, aside from the fact that it generates an error:

```<code>Error in if (grep(AUpat, strings[i])) status[i] <- "AU" else if (grep(PDpat,  :
  argument is of length zero
</code>```

Is there some better way to try to do this task, maybe with stringr or other tidyverse tools?

答:
It looks from your patterns as if strings can actually belong to zero or more, not just one. If that's true, then a first step would be to determine which categories (0 or more) a string possesses.

I don't have enough of your strings to really test, so I'll generate some simple data and patterns:

strings <- c("something", "something else", "nothing", "nothing here either",
             "something or nothing", "interesting",
             "something interesting", "nothing interesting")

pats <- c(p1 = "something", p2 = "nothing", p3 = "interesting")
```

<p>(The patterns are named as a convenience when the patterns themselves get cumbersome as labels.) Start with generating a <code>logical</code> matrix:</p>

<pre class="lang-r prettyprint-override"><code>m <- sapply(pats, grepl, strings, ignore.case = TRUE)
m
#         p1    p2    p3
# [1,]  TRUE FALSE FALSE
# [2,]  TRUE FALSE FALSE
# [3,] FALSE  TRUE FALSE
# [4,] FALSE  TRUE FALSE
# [5,]  TRUE  TRUE FALSE
# [6,] FALSE FALSE  TRUE
# [7,]  TRUE FALSE  TRUE
# [8,] FALSE  TRUE  TRUE
</code>```

If you must apply just one category to a string, then assuming the patterns are in order of priority, you can do:

apply(m, 1, function(a) head(c(which(a), NA), n = 1))
# [1] 1 1 2 2 1 3 1 2

names(pats)[ apply(m, 1, function(a) head(c(which(a), 0), n = 1)) ]
# [1] "p1" "p1" "p2" "p2" "p1" "p3" "p1" "p2"
```

<p>Note: this will create <code>NA</code>s when strings contain none of the patterns, demonstrating:</p>

<pre class="lang-r prettyprint-override"><code>m[8,] <- FALSE
apply(m, 1, function(a) head(c(which(a), NA), n = 1))
# [1]  1  1  2  2  1  3  1 NA
</code>```

You should guard against this in your assumptions. (I'll keep m with this change for now.)

If you need to preserve the categories per-string, then how you do it depends on how you intend to store said classifications. The start for this might be:

str(m2 <- apply(m, 1, function(r) names(which(r))))
# List of 8
#  $ : chr "p1"
#  $ : chr "p1"
#  $ : chr "p2"
#  $ : chr "p2"
#  $ : chr [1:2] "p1" "p2"
#  $ : chr "p3"
#  $ : chr [1:2] "p1" "p3"
#  $ : chr(0)
```

<p>This is one direct storage: each element of the <code>list</code> corresponds to <code>strings</code>, and it contains zero or more pattern names. If this is for human-eyes consumption, you might want to convert this into a comma-delimited set:</p>

<pre class="lang-r prettyprint-override"><code>sapply(m2, paste, collapse = ",")
# [1] "p1"    "p1"    "p2"    "p2"    "p1,p2" "p3"    "p1,p3" ""
</code>```

or for more formal database storage, how about

stringids <- seq_len(length(strings)) # perhaps you have something better?
d <- data.frame(
  stringid = rep(stringids, times = lengths(m2)),
  ptnmatch = unlist(m2),
  stringsAsFactors = FALSE
)
d
#   stringid ptnmatch
# 1        1       p1
# 2        2       p1
# 3        3       p2
# 4        4       p2
# 5        5       p1
# 6        5       p2
# 7        6       p3
# 8        7       p1
# 9        7       p3
```

<p>Notice how string 8 (that I modified to have no categories) is not included, this is by-design here. Once could always force it back in with:</p>

<pre class="lang-r prettyprint-override"><code>misses <- setdiff(stringids, unique(d$stringid))
misses
# [1] 8

d <- rbind(d, data.frame(stringid = misses, ptnmatch = rep(NA, length(misses))),
           stringsAsFactors = FALSE)
d
#    stringid ptnmatch
# 1         1       p1
# 2         2       p1
# 3         3       p2
# 4         4       p2
# 5         5       p1
# 6         5       p2
# 7         6       p3
# 8         7       p1
# 9         7       p3
# 10        8     <NA>

</code>```

Body:
I have a vector of text strings that describe the sources for images in a book, but not in an entirely consistent format--- they are captured from the LaTeX source & written to a text file.

I need to process these and collect information about the source attribution
and permission status.  A sample of strings looks like this:

strings <- '
GBD 2016 Alcohol Collaborators (2018)
\citet {DeBoldFriedman:2015}, permission required
Author graphic, using various public domain images
\url {http://www.histogames.com/HTML/inventaire/periodes-historiques/prehistoire.php}
\url {https://commons.wikimedia.org/wiki/File:Egyptmotionseries.jpg}
\url {http://commons.wikimedia.org}, public domain.
\citet {Plot:1685}, author image collection
Author image collection
 From \citet {Priestley:1765}, author image collection
 Author image collection
 Courtesy Library of Congress
\citet {Langren:1644}, image courtesy of the Koninklijke Bibliotheek van Belgi\"e
Public domain
Author graphic
Author graphic
Author graphic
Author image collection
Wikipedia, https://commons.wikimedia.org/wiki/File:Tablas\_alfonsies.jpg, public domain
'

One main task is to create a variable status indicating permission status by finding
matches to simple regular expressions in the strings.  The categories can be defined by
the following patterns, all of which should be matched to the text of the strings
w/o regard to case.

AUpat <- "author (image|graphic|collection)"
PDpat <- "public domain"
REQpat <- "permission required"
LIBpat <- "courtesy|by permission"

# or as a list:
pats <- list(
  'AU' = "author (image|graphic|collection)",
  'PD' = "public domain",
  'REQ'= "permission required",
  'LIB'= "courtesy|by permission"
)

Pseudo code to do what I want (doesn't work):

status <- rep("", length(strings))
for(i in seq_along(strings)) {
  if      (grep(AUpat, strings[i],  ignore.case=TRUE)) status[i] <- "AU"
  else if (grep(PDpat, strings[i],  ignore.case=TRUE)) status[i] <- "PD"
  else if (grep(REQpat, strings[i], ignore.case=TRUE)) status[i] <- "REQ"
  else if (grep(LIBpat, strings[i], ignore.case=TRUE)) status[i] <- "LIB"
}

This is ugly, aside from the fact that it generates an error:

Error in if (grep(AUpat, strings[i])) status[i] <- "AU" else if (grep(PDpat,  :
  argument is of length zero

Is there some better way to try to do this task, maybe with stringr or other tidyverse tools?

Body:
It looks from your patterns as if strings can actually belong to zero or more, not just one. If that's true, then a first step would be to determine which categories (0 or more) a string possesses.

I don't have enough of your strings to really test, so I'll generate some simple data and patterns:

strings <- c("something", "something else", "nothing", "nothing here either",
             "something or nothing", "interesting",
             "something interesting", "nothing interesting")

pats <- c(p1 = "something", p2 = "nothing", p3 = "interesting")

(The patterns are named as a convenience when the patterns themselves get cumbersome as labels.) Start with generating a logical matrix:

m <- sapply(pats, grepl, strings, ignore.case = TRUE)
m
#         p1    p2    p3
# [1,]  TRUE FALSE FALSE
# [2,]  TRUE FALSE FALSE
# [3,] FALSE  TRUE FALSE
# [4,] FALSE  TRUE FALSE
# [5,]  TRUE  TRUE FALSE
# [6,] FALSE FALSE  TRUE
# [7,]  TRUE FALSE  TRUE
# [8,] FALSE  TRUE  TRUE

If you must apply just one category to a string, then assuming the patterns are in order of priority, you can do:

apply(m, 1, function(a) head(c(which(a), NA), n = 1))
# [1] 1 1 2 2 1 3 1 2

names(pats)[ apply(m, 1, function(a) head(c(which(a), 0), n = 1)) ]
# [1] "p1" "p1" "p2" "p2" "p1" "p3" "p1" "p2"

Note: this will create NAs when strings contain none of the patterns, demonstrating:

m[8,] <- FALSE
apply(m, 1, function(a) head(c(which(a), NA), n = 1))
# [1]  1  1  2  2  1  3  1 NA

You should guard against this in your assumptions. (I'll keep m with this change for now.)

If you need to preserve the categories per-string, then how you do it depends on how you intend to store said classifications. The start for this might be:

str(m2 <- apply(m, 1, function(r) names(which(r))))
# List of 8
#  $ : chr "p1"
#  $ : chr "p1"
#  $ : chr "p2"
#  $ : chr "p2"
#  $ : chr [1:2] "p1" "p2"
#  $ : chr "p3"
#  $ : chr [1:2] "p1" "p3"
#  $ : chr(0)

This is one direct storage: each element of the list corresponds to strings, and it contains zero or more pattern names. If this is for human-eyes consumption, you might want to convert this into a comma-delimited set:

sapply(m2, paste, collapse = ",")
# [1] "p1"    "p1"    "p2"    "p2"    "p1,p2" "p3"    "p1,p3" ""

or for more formal database storage, how about

stringids <- seq_len(length(strings)) # perhaps you have something better?
d <- data.frame(
  stringid = rep(stringids, times = lengths(m2)),
  ptnmatch = unlist(m2),
  stringsAsFactors = FALSE
)
d
#   stringid ptnmatch
# 1        1       p1
# 2        2       p1
# 3        3       p2
# 4        4       p2
# 5        5       p1
# 6        5       p2
# 7        6       p3
# 8        7       p1
# 9        7       p3

Notice how string 8 (that I modified to have no categories) is not included, this is by-design here. Once could always force it back in with:

misses <- setdiff(stringids, unique(d$stringid))
misses
# [1] 8

d <- rbind(d, data.frame(stringid = misses, ptnmatch = rep(NA, length(misses))),
           stringsAsFactors = FALSE)
d
#    stringid ptnmatch
# 1         1       p1
# 2         2       p1
# 3         3       p2
# 4         4       p2
# 5         5       p1
# 6         5       p2
# 7         6       p3
# 8         7       p1
# 9         7       p3
# 10        8     <NA>


答:
Please try the code below:</p>

```<code>Sub saveFormData()

Dim name As String, lastname As String, birthday As String

'Declare the worksheets
Dim sdSH As Worksheet, fSH As Worksheet
Set sdSH = ThisWorkbook.Sheets("saveData")
Set fSH = ThisWorkbook.Sheets("form")

' Get last empty row
lastrow = sdSH.Cells(Rows.Count, 1).End(xlUp).Row + 1
name = fSH.Range("A1").Value
lastname = fSH.Range("A2").Value
birthday = fSH.Range("A3").Value

 'Transfer the data for 'saveData to array
Dim saveData() As String
ReDim Preserve saveData(1 To lastrow, 1 To 3) As String
For a = 1 To lastrow
  For b = 1 To 3
      saveData(a, b) = sdSH.Cells(a, b).Value
  Next b
Next a

For i = 2 To UBound(saveData)

  ' Check if data exist (record is unique if we have name + lastname + birthday

  If saveData(i, 1) = name And saveData(i, 2) = lastname And saveData(i, 3) = birthday Then

      MsgBox "Data already exist"

      Exit Sub 'Exit from Sub

  End If
Next

' Save name
sdSH.Range("A" & lastrow).Value = name

' Save lastname
sdSH.Range("B" & lastrow).Value = lastname

   ' Save birthday
sdSH.Range("C" & lastrow).Value = birthday

End Sub
</code>```

Title: How to avoid duplication record?

Body:
Please try the code below:

Sub saveFormData()

Dim name As String, lastname As String, birthday As String

'Declare the worksheets
Dim sdSH As Worksheet, fSH As Worksheet
Set sdSH = ThisWorkbook.Sheets("saveData")
Set fSH = ThisWorkbook.Sheets("form")

' Get last empty row
lastrow = sdSH.Cells(Rows.Count, 1).End(xlUp).Row + 1
name = fSH.Range("A1").Value
lastname = fSH.Range("A2").Value
birthday = fSH.Range("A3").Value

 'Transfer the data for 'saveData to array
Dim saveData() As String
ReDim Preserve saveData(1 To lastrow, 1 To 3) As String
For a = 1 To lastrow
  For b = 1 To 3
      saveData(a, b) = sdSH.Cells(a, b).Value
  Next b
Next a

For i = 2 To UBound(saveData)

  ' Check if data exist (record is unique if we have name + lastname + birthday

  If saveData(i, 1) = name And saveData(i, 2) = lastname And saveData(i, 3) = birthday Then

      MsgBox "Data already exist"

      Exit Sub 'Exit from Sub

  End If
Next

' Save name
sdSH.Range("A" & lastrow).Value = name

' Save lastname
sdSH.Range("B" & lastrow).Value = lastname

   ' Save birthday
sdSH.Range("C" & lastrow).Value = birthday

End Sub


问:
How to fix a React search filter that doesn't update on backspace
The issue:

I'm trying to create a search filter in React, based on first and last name. The search is working when I initially type a matching name, but the results don't update whenever I backspace. Component and additional details included below:

```<code>class People extends Component {
    state = {
        people: [],
        searchValue: ''
    };

    componentDidMount() {
        axios.get('/metadata.json').then(response => {
            const updatedPeople = response.data.map(person => {
                return {
                    ...person
                };
            });
            this.setState({ people: updatedPeople });
        }).catch(error => { console.log(error); });
    }

    searchHandler = (event) => {
        let searchResults = this.state.people;
        searchResults = searchResults.filter(result => {
            return result.name.toLowerCase().search(
                event.target.value.toLowerCase()) !== -1;
        });

        this.setState({
            people: searchResults,
            searchValue: event.target.value.toLowerCase()
        }, () => console.log('state', this.state))
    };

    render() {
        let people = this.state.people.map((person, index) => {
            return (
                <Person
                    key={index}
                    name={person.name} />
            );
        });

        return (
            <React.Fragment>
                <input
                    type="search"
                    value={this.state.searchValue}
                    onChange={this.searchHandler} />
                <div className={classes.People}>
                    {people}
                </div>
            </React.Fragment>
        );
    }
}
</code>```

What I've tried:

creating a search handler that filters names matching event.target.value and updating state based on the results.

adding a second property to state, filteredPeople, to store the filtered list of names while keeping the original list in state.people. However, I ran into issues reconciling these two

writing a function to check the search query and return a value based on whether there's a match, but I questioned if this was needed given the check I'm already doing in searchHandler.

What do I need to do to get my search filter fully functional?

答:
Yes you do need a second property of state to contain the filtered list of people

```<code>state = {
    people: [],
    searchValue: '',
    filtered_people: []
};

searchHandler = (event) => {
    this.setState({filtered_people: [] })

    let searchResults = [...this.state.people];

    searchResults = searchResults.filter(result => {
        return result.name.toLowerCase().search(
            event.target.value.toLowerCase()) !== -1;
    });

    this.setState({
        filtered_people: searchResults,
        searchValue: event.target.value.toLowerCase()
    }, () => console.log('state', this.state))
};
</code>```

Clearing the filtered_people array on every onChange event is how you can delete the results on a backspace.

Body:
The issue:

I'm trying to create a search filter in React, based on first and last name. The search is working when I initially type a matching name, but the results don't update whenever I backspace. Component and additional details included below:

class People extends Component {
    state = {
        people: [],
        searchValue: ''
    };

    componentDidMount() {
        axios.get('/metadata.json').then(response => {
            const updatedPeople = response.data.map(person => {
                return {
                    ...person
                };
            });
            this.setState({ people: updatedPeople });
        }).catch(error => { console.log(error); });
    }

    searchHandler = (event) => {
        let searchResults = this.state.people;
        searchResults = searchResults.filter(result => {
            return result.name.toLowerCase().search(
                event.target.value.toLowerCase()) !== -1;
        });

        this.setState({
            people: searchResults,
            searchValue: event.target.value.toLowerCase()
        }, () => console.log('state', this.state))
    };

    render() {
        let people = this.state.people.map((person, index) => {
            return (
                <Person
                    key={index}
                    name={person.name} />
            );
        });

        return (
            <React.Fragment>
                <input
                    type="search"
                    value={this.state.searchValue}
                    onChange={this.searchHandler} />

                    {people}

            </React.Fragment>
        );
    }
}

What I've tried:

creating a search handler that filters names matching event.target.value and updating state based on the results.

adding a second property to state, filteredPeople, to store the filtered list of names while keeping the original list in state.people. However, I ran into issues reconciling these two

writing a function to check the search query and return a value based on whether there's a match, but I questioned if this was needed given the check I'm already doing in searchHandler.

What do I need to do to get my search filter fully functional?

Body:
Yes you do need a second property of state to contain the filtered list of people

state = {
    people: [],
    searchValue: '',
    filtered_people: []
};

searchHandler = (event) => {
    this.setState({filtered_people: [] })

    let searchResults = [...this.state.people];

    searchResults = searchResults.filter(result => {
        return result.name.toLowerCase().search(
            event.target.value.toLowerCase()) !== -1;
    });

    this.setState({
        filtered_people: searchResults,
        searchValue: event.target.value.toLowerCase()
    }, () => console.log('state', this.state))
};

Clearing the filtered_people array on every onChange event is how you can delete the results on a backspace.


问:
mysql rand with condition
Could someone help me out with the correct syntax for this query please.

I have, table1:

```<code>id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)
</code>```

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

答:
```<code>SELECT id, name FROM table1 WHERE `on` = 1 ORDER BY RAND() LIMIT 0,10;
</code>```

Title: mysql rand with condition

Body:
Could someone help me out with the correct syntax for this query please.

I have, table1:

id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?


问:
How to make a square with text inside using MigraDoc + PDFsharp
I'm using the table class in unison with columns and cells to add data inside, being images or text but I have to draw something really weird I don't know how to replicate it using borders (if it is possible even).

It's the following:

So its a square, inside the square 2 paragraphs I would say horizontally centred.

My idea... the only one I can think of (but I don't know if it is the best solution) would be to make a table with N rows and each row a cell with left and right border except the first one and the last one where it will have top and bottom, then .AddParagraph() for the 1st and last cell.

答:
A possible solution would be:</p>

```<code>private static Table DibujarSelloYFirma(Section sec)
{
    Table table = new Table();

    Column column = table.AddColumn(Unit.FromCentimeter(3));

    Row row = table.AddRow();

    Cell cell = row.Cells[0];
    cell.AddParagraph("SEAL COMMERCE");

    cell.Format.Alignment = ParagraphAlignment.Center;
    cell.VerticalAlignment = VerticalAlignment.Center;
    cell.Format.Font.Bold = true;
    cell.Format.Font.Size = 3;
    cell.Format.Font.Name = "Verdana";
    cell.Format.Font.Italic = true;
    cell.Borders.Right.Width = 0.5;
    cell.Borders.Left.Width = 0.5;
    cell.Borders.Top.Width = 0.5;

    for (int i = 0; i < 5; i++)
    {
        Row rowEmpty = table.AddRow();
        cell = rowEmpty.Cells[0];
        cell = rowEmpty.Cells[0];
        cell.Borders.Right.Width = 0.5;
        cell.Borders.Left.Width = 0.5;
    }

    Row rowFinal = table.AddRow();
    cell = rowFinal.Cells[0];
    cell.AddParagraph("FIRMA");
    cell.Format.Alignment = ParagraphAlignment.Center;
    cell.VerticalAlignment = VerticalAlignment.Center;
    cell.Format.Font.Bold = true;
    cell.Format.Font.Size = 3;
    cell.Format.Font.Name = "Verdana";
    cell.Format.Font.Italic = true;
    cell.Borders.Right.Width = 0.5;
    cell.Borders.Left.Width = 0.5;
    cell.Borders.Bottom.Width = 0.5;

    return table;
}
</code>```

Body:
A possible solution would be:

private static Table DibujarSelloYFirma(Section sec)
{
    Table table = new Table();

    Column column = table.AddColumn(Unit.FromCentimeter(3));

    Row row = table.AddRow();

    Cell cell = row.Cells[0];
    cell.AddParagraph("SEAL COMMERCE");

    cell.Format.Alignment = ParagraphAlignment.Center;
    cell.VerticalAlignment = VerticalAlignment.Center;
    cell.Format.Font.Bold = true;
    cell.Format.Font.Size = 3;
    cell.Format.Font.Name = "Verdana";
    cell.Format.Font.Italic = true;
    cell.Borders.Right.Width = 0.5;
    cell.Borders.Left.Width = 0.5;
    cell.Borders.Top.Width = 0.5;

    for (int i = 0; i < 5; i++)
    {
        Row rowEmpty = table.AddRow();
        cell = rowEmpty.Cells[0];
        cell = rowEmpty.Cells[0];
        cell.Borders.Right.Width = 0.5;
        cell.Borders.Left.Width = 0.5;
    }

    Row rowFinal = table.AddRow();
    cell = rowFinal.Cells[0];
    cell.AddParagraph("FIRMA");
    cell.Format.Alignment = ParagraphAlignment.Center;
    cell.VerticalAlignment = VerticalAlignment.Center;
    cell.Format.Font.Bold = true;
    cell.Format.Font.Size = 3;
    cell.Format.Font.Name = "Verdana";
    cell.Format.Font.Italic = true;
    cell.Borders.Right.Width = 0.5;
    cell.Borders.Left.Width = 0.5;
    cell.Borders.Bottom.Width = 0.5;

    return table;
}


问:
Error: The method eth_sendTransaction does not exist/is not available
Showing an error while calling solidity contract, which is deployed already in ropsten-infura. I'm using web3(@0.19.1) for calling contract.

Anybody faced the same issue?

答:
You will need to sign the transaction before and that is how I did it using web3 1.0.0.

I used the web3-provider-engine from MetaMask:

```<code>getWalletEthTxSubprovider() {
    return new HookedWalletEthTxSubprovider({
        getAccounts: callback => {
            callback(null, [this.web3.eth.defaultAccount]);
        },
        getPrivateKey: (address, callback) => {
            if (address.toLowerCase() === this.web3.eth.defaultAccount.toLowerCase()) {
                return callback(
                    null,
                    Buffer.from(
                        this.web3.eth.accounts.wallet[address].privateKey.replace('0x', ''),
                        'hex'
                    )
                );
            }
            return callback(new Error('not private key supplied for that account'));
        }
    });
}
</code>```

You can see the full code here

Body:
You will need to sign the transaction before and that is how I did it using web3 1.0.0.

I used the web3-provider-engine from MetaMask:

getWalletEthTxSubprovider() {
    return new HookedWalletEthTxSubprovider({
        getAccounts: callback => {
            callback(null, [this.web3.eth.defaultAccount]);
        },
        getPrivateKey: (address, callback) => {
            if (address.toLowerCase() === this.web3.eth.defaultAccount.toLowerCase()) {
                return callback(
                    null,
                    Buffer.from(
                        this.web3.eth.accounts.wallet[address].privateKey.replace('0x', ''),
                        'hex'
                    )
                );
            }
            return callback(new Error('not private key supplied for that account'));
        }
    });
}

You can see the full code here


问:
How to validate date in Reactive Forms?(Angular)
How can I validate a date to get error message if the date is before today date. I used Reactive Forms and I would like to display an error based on the date entered in the input field. I attached the code below(the component html and typescript). I would appreciate any help.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-cpi',
  templateUrl: './cpi.component.html',
  styleUrls: ['./cpi.component.scss']
})
export class MyComponent implements OnInit {

  public myForm: FormGroup;
  private today: Date = new Date();

  get date_cancelled() { return this.myForm.get('date_cancelled').value; }

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      emp_cancelled: [''],
      reg_employed: [''],
      date_cancelled: ['', this.dateValidator],
    });
  }

  dateValidator() {
      let from = new Date();
      let to = this.date_cancelled;
      if (from > to) {
        return false;
      }
    return true;

  }

  ngOnInit() {

}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="form">
  <form [formGroup]="myForm">
        <mat-radio-group formControlName="emp_cancelled">
          <mat-radio-button value="emp_cancelled">Cancelled</mat-radio-button>
        </mat-radio-group>
        <mat-radio-group formControlName="reg_employed">
          <mat-radio-button value="reg_employed">Regularly employed</mat-radio-button>
        </mat-radio-group>
      </div>
      <br />
      <mat-form-field class="date_cancelled" *ngIf="myForm.controls.emp_cancelled?.touched">
        <input matInput [matDatepicker]="picker" placeholder="Taking effect at" formControlName="date_cancelled">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker></mat-datepicker>
      </mat-form-field>
      <mat-error *ngIf="!myForm.controls.date_cancelled?.valid">Error date</mat-error>
      <button type="submit">Submit</button>
  </form>
</section></code>```

答:
You can define a custom validator like

```<code>date_cancelled: ['', (c: AbstractControl) => (new Date(c.value).getTime() < Date.now() ? { invalid: true } : null)]
</code>```

And also use the mat-error without *ngIf since it automatically shows/hides error messages when there is a validation error.

Body:
How can I validate a date to get error message if the date is before today date. I used Reactive Forms and I would like to display an error based on the date entered in the input field. I attached the code below(the component html and typescript). I would appreciate any help.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-cpi',
  templateUrl: './cpi.component.html',
  styleUrls: ['./cpi.component.scss']
})
export class MyComponent implements OnInit {

  public myForm: FormGroup;
  private today: Date = new Date();

  get date_cancelled() { return this.myForm.get('date_cancelled').value; }

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      emp_cancelled: [''],
      reg_employed: [''],
      date_cancelled: ['', this.dateValidator],
    });
  }

  dateValidator() {
      let from = new Date();
      let to = this.date_cancelled;
      if (from > to) {
        return false;
      }
    return true;

  }

  ngOnInit() {

}

}

  <form [formGroup]="myForm">
        <mat-radio-group formControlName="emp_cancelled">
          <mat-radio-button value="emp_cancelled">Cancelled</mat-radio-button>
        </mat-radio-group>
        <mat-radio-group formControlName="reg_employed">
          <mat-radio-button value="reg_employed">Regularly employed</mat-radio-button>
        </mat-radio-group>

      <mat-form-field class="date_cancelled" *ngIf="myForm.controls.emp_cancelled?.touched">
        <input matInput [matDatepicker]="picker" placeholder="Taking effect at" formControlName="date_cancelled">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker></mat-datepicker>
      </mat-form-field>
      <mat-error *ngIf="!myForm.controls.date_cancelled?.valid">Error date</mat-error>
      <button type="submit">Submit</button>
  </form>

Body:
You can define a custom validator like

date_cancelled: ['', (c: AbstractControl) => (new Date(c.value).getTime() < Date.now() ? { invalid: true } : null)]

And also use the mat-error without *ngIf since it automatically shows/hides error messages when there is a validation error.


问:
Can a private base class member variable be modified in a derived class?
Is there a way to set a private member variable of a base class to a value in the constructor of a derived class?

I understand that's what getter and setter methods are for and what making the variable protected or public is for, but assuming you can't modify the base class, is there any alternate way to set it?

答:
Yes, we can do so by calling a getter function from the base class. Here is an example:</p>

```<code>#include<iostream>
using namespace std;

class A{
    int x;
public:
    void setx(int x1) {
        x = x1;
    }

    int getx() {
        return x;
    }

};

class B: public A {

};

int main() {
    B b;
    b.setx(1000);
    cout << b.getx();
    return 0;
}
</code>```

Body:
Yes, we can do so by calling a getter function from the base class. Here is an example:

#include<iostream>
using namespace std;

class A{
    int x;
public:
    void setx(int x1) {
        x = x1;
    }

    int getx() {
        return x;
    }

};

class B: public A {

};

int main() {
    B b;
    b.setx(1000);
    cout << b.getx();
    return 0;
}


问:
Launch Metro style apps using powershell
I am trying to write a powershell script for windows 10 that will automatically launch a Metro-style app.
The Start-Process cmdlet seems like it should work, but I cannot get it to launch anything unless I provide a path to the .exe

For example, the following input works:

```<code>    Start-Process 'C:\Program Files\Internet Explorer\iexplore.exe'
</code>```

Unfortunately, Metro-style apps do not have an executable file. What file do I need to use to launch them?
If I wanted to launch Windows Store for example, how would I do that?

Thanks

答:
It's asserted the Metro style "App Store" apps don't have traditional executable files so I started digging a little and they do.  From an old skool Administrative cmd.exe try:

```<code> dir "%ProgramW6432%\WindowsApps"
 dir "%ProgramW6432%\WindowsApps\Microsoft.WindowsCalculator_10.1903.21.0_x64__8wekyb3d8bbwe"      Directory of C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1903.21.0_x64__8wekyb3d8bbwe

 04/30/2019  05:58 PM    <DIR>          .
 04/30/2019  05:58 PM    <DIR>          ..
 04/30/2019  05:58 PM            35,314 AppxBlockMap.xml
 04/30/2019  05:58 PM             3,860 AppxManifest.xml
 04/30/2019  05:58 PM    <DIR>          AppxMetadata
 04/30/2019  05:58 PM            11,296 AppxSignature.p7x
 04/30/2019  05:58 PM    <DIR>          Assets
 04/30/2019  05:58 PM         4,188,672 Calculator.exe
 04/30/2019  05:58 PM            95,744 CalculatorApp.winmd
 04/30/2019  05:58 PM           286,920 resources.pri
 04/30/2019  05:58 PM    <DIR>          WinMetadata
</code>```

Helped me to find the exe for Ubuntu, "%ProgramW6432%\WindowsApps\CanonicalGroupLimited.Ubuntu18.04onWindows_1804.2019.522.0_x64__79rhkp1fndgsc\ubuntu1804.exe"

Body:
I am trying to write a powershell script for windows 10 that will automatically launch a Metro-style app.
The Start-Process cmdlet seems like it should work, but I cannot get it to launch anything unless I provide a path to the .exe

For example, the following input works:

    Start-Process 'C:\Program Files\Internet Explorer\iexplore.exe'

Unfortunately, Metro-style apps do not have an executable file. What file do I need to use to launch them?
If I wanted to launch Windows Store for example, how would I do that?

Thanks

Body:
It's asserted the Metro style "App Store" apps don't have traditional executable files so I started digging a little and they do.  From an old skool Administrative cmd.exe try:

 dir "%ProgramW6432%\WindowsApps"
 dir "%ProgramW6432%\WindowsApps\Microsoft.WindowsCalculator_10.1903.21.0_x64__8wekyb3d8bbwe"      Directory of C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1903.21.0_x64__8wekyb3d8bbwe

 04/30/2019  05:58 PM    <DIR>          .
 04/30/2019  05:58 PM    <DIR>          ..
 04/30/2019  05:58 PM            35,314 AppxBlockMap.xml
 04/30/2019  05:58 PM             3,860 AppxManifest.xml
 04/30/2019  05:58 PM    <DIR>          AppxMetadata
 04/30/2019  05:58 PM            11,296 AppxSignature.p7x
 04/30/2019  05:58 PM    <DIR>          Assets
 04/30/2019  05:58 PM         4,188,672 Calculator.exe
 04/30/2019  05:58 PM            95,744 CalculatorApp.winmd
 04/30/2019  05:58 PM           286,920 resources.pri
 04/30/2019  05:58 PM    <DIR>          WinMetadata

Helped me to find the exe for Ubuntu, "%ProgramW6432%\WindowsApps\CanonicalGroupLimited.Ubuntu18.04onWindows_1804.2019.522.0_x64__79rhkp1fndgsc\ubuntu1804.exe"


问:
Django cannot find any valid urlpatterns
I'm trying to include a second urls.py in my main Django urls.py, and it's throwing this error whenever I try to do it:

```<code>Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/user/app/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/user/app/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/user/app/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/user/app/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/user/app/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/user/app/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/user/app/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/home/user/app/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/home/user/app/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/user/app/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'app.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
</code>```

Here's the main urls.py:

```<code>from django.urls import path, include

urlpatterns = [
    path('', include('app_main.urls')),
]
</code>```

Thanks! I don't think I have any circular imports, as I haven't really started creating the meat of the app yet. All help is appreciated. I'm curious as to why Django is doing this, as I'm pretty sure what I entered was a valid urlpattern (I checked it against one I knew to be valid).

答:
As stated by Carlton Gibson here, this bug is only present on Python 3.6.0 and earlier versions.
As Django currently supports 3.6.8 and later, you can either:

Update the python version

Reverse the commit that's causing error-masking behavior, by removing try/except in site-packages/django/utils/autoreload.py.

Body:
I'm trying to include a second urls.py in my main Django urls.py, and it's throwing this error whenever I try to do it:

Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/user/app/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/user/app/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/user/app/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/user/app/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/user/app/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/user/app/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/user/app/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/home/user/app/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/home/user/app/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/user/app/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'app.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

Here's the main urls.py:

from django.urls import path, include

urlpatterns = [
    path('', include('app_main.urls')),
]

Thanks! I don't think I have any circular imports, as I haven't really started creating the meat of the app yet. All help is appreciated. I'm curious as to why Django is doing this, as I'm pretty sure what I entered was a valid urlpattern (I checked it against one I knew to be valid).


问:
Xfinium remove the border in the specific table cell
I want to remove borders in the specific table cells, so I set borders width to 0, like in the code below

cell.Borders = new PdfFlowContentBorders(new PdfPen(PdfRgbColor.Black, 0));

I expect that those borders will disappear, but instead I got thin black border.

And here is what I get when set the border color to white

答:
You have to set a border to null if you do not want that border to be drawn.

Disclaimer: I work for the company that develops XFINIUM.PDF library.


问:
Populate a listbox using mySQL and PHP
I am trying to populate a listbox with the results of a MySQL query. This is what I have tried:

```<code> <select>
 <?php
 $type = "processors";
 $stmt2 = mysqli_prepare($link, "SELECT id, name, price FROM products WHERE type=?");
 $stmt2->bind_param("s", $type);
 $stmt2->execute();
 echo "<select class name='productlist'>";
 $stmt2->bind_result($products_id, $products_name, $products_price);
 while($stmt2->fetch()){
 echo "<option value='".$row[$products_id]."'>".$row[$products_name]."</option>";
 }
 $stmt2->close();
 ?>
 </select>
</code>```

I have an error with this line:

```<code>echo "<option value='".$row[$products_id]."'>".$row[$products_name]."</option>";
</code>```

Error:

Notice: Undefined variable: row

This should load the data into the listbox; however, no data is populated as I have this above error. How can I fix this? Thanks.

答:
You bind the results of your query to scalar variables, so now all you have to do is use them. You have no $row in your code.

```<code>$stmt2->bind_result($products_id, $products_name, $products_price);
while($stmt2->fetch()){
    echo "<option value='$products_id'>$products_name</option>";
}
$stmt2->close();
?>
</code>```

Title: Populate a listbox using mySQL and PHP

Body:
I am trying to populate a listbox with the results of a MySQL query. This is what I have tried:

 <select>
 <?php
 $type = "processors";
 $stmt2 = mysqli_prepare($link, "SELECT id, name, price FROM products WHERE type=?");
 $stmt2->bind_param("s", $type);
 $stmt2->execute();
 echo "<select class name='productlist'>";
 $stmt2->bind_result($products_id, $products_name, $products_price);
 while($stmt2->fetch()){
 echo "<option value='".$row[$products_id]."'>".$row[$products_name]."</option>";
 }
 $stmt2->close();
 ?>
 </select>

I have an error with this line:

echo "<option value='".$row[$products_id]."'>".$row[$products_name]."</option>";

Error:

Notice: Undefined variable: row

This should load the data into the listbox; however, no data is populated as I have this above error. How can I fix this? Thanks.

Body:
You bind the results of your query to scalar variables, so now all you have to do is use them. You have no $row in your code.

$stmt2->bind_result($products_id, $products_name, $products_price);
while($stmt2->fetch()){
    echo "<option value='$products_id'>$products_name</option>";
}
$stmt2->close();
?>


问:
how to use n model in one root in reactjs?
hi i have one root like this code

```<code><body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<button >Platform</button>
<button >Game</button>
<button >Score</button>
<hr />

<div id="root"></div>
</code>```

index.js code

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();
</code>```

app.js code

```<code>    import React ,{Component} from 'react';
import axios from 'axios';
import { Modal,ModalHeader,ModalBody,ModalFooter,FormGroup,Label,Input,Table ,Button} from 'reactstrap';

class App extends Component{
  state={
    books:[],
    NewBookData:{
      Title:'',
      Rating:''
    },
    EditBookData:{
      Id:'',
      Title:'',
      Rating:''
    },

    NewBookModal:false,
    EditBookModal:false
  }
....
</code>```

this root is ok for default jobs,but i want ovveride this root base on platform ,game , ...
how i can this work?

答: You should make an outter react component which contains the buttons and all nested components for 'Platform', 'Game', 'Score'. You should recomponentize your app and not 'override'. </p>

Body:
hi i have one root like this code

You need to enable JavaScript to run this app.
<button >Platform</button>
<button >Game</button>
<button >Score</button>

index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

app.js code

    import React ,{Component} from 'react';
import axios from 'axios';
import { Modal,ModalHeader,ModalBody,ModalFooter,FormGroup,Label,Input,Table ,Button} from 'reactstrap';

class App extends Component{
  state={
    books:[],
    NewBookData:{
      Title:'',
      Rating:''
    },
    EditBookData:{
      Id:'',
      Title:'',
      Rating:''
    },

    NewBookModal:false,
    EditBookModal:false
  }
....

this root is ok for default jobs,but i want ovveride this root base on platform ,game , ...
how i can this work?


问:
Manually reporting a crash to Android Vitals
Is it possible to manually report a crash or error to the Android Vitals statistics. As for now I've been able to close my application nicely with an error message for the user, where it used to crash.

However, I would still like to have these "soft" crashes reported to Android Vitals, is this possible?

(Note that the app I'm developing is a pure NDK/C++ application)

答:
As I mentioned in an answer to Android vitals and exception handling the approach from https://proandroiddev.com/hide-your-crashes-gracefully-and-still-report-them-9b1c85b25875 might be a partial solution.

I don't know enough about how and when crashes are reported (i.e. sent from the Android device to Google) to have confidence the approach will work for you. Do please post your progress here.


问:
Cross Product Confusion
I have a question regarding a tutorial that I have been following on the rotation of the camera's view direction in OpenGL.

Whilst I appreciate that prospective respondents are not the authors of the tutorial, I think that this is likely to be a situation which most intermediate-experienced graphics programmers have encountered before so I will seek the advice of members on this topic.

Here is a link to the video to which I refer: https://www.youtube.com/watch?v=7oNLw9Bct1k.

The goal of the tutorial is to create a basic first person camera which the user controls via movement of the mouse.

Here is the function that handles cursor movement (with some variables/members renamed to conform with my personal conventions):

```<code>glm::vec2 Movement { OldCursorPosition - NewCursorPosition };

// camera rotates on y-axis when mouse moved left/right (orientation is { 0.0F, 1.0F, 0.0F }):

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.x) / 2, MVP.view.orientation)
                   * glm::vec4(MVP.view.direction, 0.0F);

glm::vec3 RotateAround { glm::cross(MVP.view.direction, MVP.view.orientation) };

/* why is camera rotating around cross product of view direction and view orientation
rather than just rotating around x-axis when mouse is moved up/down..? : */

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);

OldCursorPosition = NewCursorPosition;
</code>```

What I struggle to understand is why obtaining the cross product is even required. What I would naturally expect is for the camera to rotate around the y-axis when the mouse is moved from left to right, and for the camera to rotate around the x-axis when the mouse is moved up and down. I just can't get my head around why the cross product is even relevant.

From my understanding, the cross product will return a vector which is perpendicular to two other vectors; in this case that is the cross product of the view direction and view orientation, but why would one want a cross product of these two vectors? Shouldn't the camera just rotate on the x-axis for up/down movement and then on the y-axis for left/right movement...? What am I missing/overlooking here?

Finally, when I run the program, I can't visually detect any rotation on the z-axis despite the fact that the rotation scalar 'RotateAround' has a z-value greater than or less than 0 on every call to the the function subsequent to the first (which suggests that the camera should rotate at least partially on the z-axis).

Perhaps this is just due to my lack of intuition, but if I change the line:

```<code>MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);
</code>```

To:

```<code>MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, glm::vec3(1.0F, 0.0F, 0.0F))
                   * glm::vec4(MVP.view.direction, 0.0F);
</code>```

So that the rotation only happens on the x-axis rather than partially on the x-axis and partially on the z-axis, and then run the program, I can't really notice much of a difference to the workings of the camera. It feels like maybe there is a difference but I can't articulate what this is.

答: You have to do the cross product because after multiple mouse moves the camera is now differently oriented. The original x-axis you wanted to rotate around is NOT the same x-axis you want to rotate around now. You must calculate the vector that is currently pointed straight out the side of the camera and rotate around that. This is considered the "right" vector. This is the cross product of the view and up vectors, where view is the "target" vector (down the camera's z axis, where you are looking) and up is straight up out of the camera up the camera's y-axis. These axes must be updated as the camera moves. Calculating the view and up vectors does not require a cross product as you should be applying rotations to these depending on your movements along the way. The view and up should update by rotations, but if you want to rotate around the x-axis (pitch) you must do a cross product. </p>

Title: Cross Product Confusion

Body:
I have a question regarding a tutorial that I have been following on the rotation of the camera's view direction in OpenGL.

Whilst I appreciate that prospective respondents are not the authors of the tutorial, I think that this is likely to be a situation which most intermediate-experienced graphics programmers have encountered before so I will seek the advice of members on this topic.

Here is a link to the video to which I refer: https://www.youtube.com/watch?v=7oNLw9Bct1k.

The goal of the tutorial is to create a basic first person camera which the user controls via movement of the mouse.

Here is the function that handles cursor movement (with some variables/members renamed to conform with my personal conventions):

glm::vec2 Movement { OldCursorPosition - NewCursorPosition };

// camera rotates on y-axis when mouse moved left/right (orientation is { 0.0F, 1.0F, 0.0F }):

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.x) / 2, MVP.view.orientation)
                   * glm::vec4(MVP.view.direction, 0.0F);

glm::vec3 RotateAround { glm::cross(MVP.view.direction, MVP.view.orientation) };

/* why is camera rotating around cross product of view direction and view orientation
rather than just rotating around x-axis when mouse is moved up/down..? : */

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);

OldCursorPosition = NewCursorPosition;

What I struggle to understand is why obtaining the cross product is even required. What I would naturally expect is for the camera to rotate around the y-axis when the mouse is moved from left to right, and for the camera to rotate around the x-axis when the mouse is moved up and down. I just can't get my head around why the cross product is even relevant.

From my understanding, the cross product will return a vector which is perpendicular to two other vectors; in this case that is the cross product of the view direction and view orientation, but why would one want a cross product of these two vectors? Shouldn't the camera just rotate on the x-axis for up/down movement and then on the y-axis for left/right movement...? What am I missing/overlooking here?

Finally, when I run the program, I can't visually detect any rotation on the z-axis despite the fact that the rotation scalar 'RotateAround' has a z-value greater than or less than 0 on every call to the the function subsequent to the first (which suggests that the camera should rotate at least partially on the z-axis).

Perhaps this is just due to my lack of intuition, but if I change the line:

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);

To:

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, glm::vec3(1.0F, 0.0F, 0.0F))
                   * glm::vec4(MVP.view.direction, 0.0F);

So that the rotation only happens on the x-axis rather than partially on the x-axis and partially on the z-axis, and then run the program, I can't really notice much of a difference to the workings of the camera. It feels like maybe there is a difference but I can't articulate what this is.


问:
Remove null objects from a List of Student objects
I was exploring Java 8 feature to remove null objects from a List of say Student objects and I have the following code

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class Student {

    private String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student {" + "name=" + name + "}";
    }

    public static Comparator<Student> getNameComparator() {

        return (s1, s2) -> s1.name.compareTo(s2.name);
        // return Comparator.comparing(x -> x.name,
        // Comparator.nullsLast(Comparator.naturalOrder()));
    }

    public static void main(String[] args) {

        List<Student> ls = new ArrayList<>(
                Arrays.asList(new Student("Dino"), new Student(null), new Student("Fred"), new Student("Amy")));
        // ls.removeAll(Collections.singleton(null));
        ls.removeIf(Objects::isNull);
        ls.forEach(s -> System.out.println(s));
        System.out.println("...............................");
        ls.sort(Student.getNameComparator());
        ls.forEach(s -> System.out.println(s));

    }

}
</code>```

I have used java 8 specific isNull i.e ls.removeIf(Objects::isNull); still in the o/p I see null value
i.e
O/p is

Student {name=Dino} Student {name=null} Student {name=Fred} Student
  {name=Amy}

Am I missing on something specific ?

Thanks
Ronan

答: removeIf(Objects::isNull) is removing any Student object in the given list that is null, not every Student whichs name is null. You can achieve what you want with .removeIf(student -> student.getName() == null)

Body:
I was exploring Java 8 feature to remove null objects from a List of say Student objects and I have the following code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class Student {

    private String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student {" + "name=" + name + "}";
    }

    public static Comparator<Student> getNameComparator() {

        return (s1, s2) -> s1.name.compareTo(s2.name);
        // return Comparator.comparing(x -> x.name,
        // Comparator.nullsLast(Comparator.naturalOrder()));
    }

    public static void main(String[] args) {

        List<Student> ls = new ArrayList<>(
                Arrays.asList(new Student("Dino"), new Student(null), new Student("Fred"), new Student("Amy")));
        // ls.removeAll(Collections.singleton(null));
        ls.removeIf(Objects::isNull);
        ls.forEach(s -> System.out.println(s));
        System.out.println("...............................");
        ls.sort(Student.getNameComparator());
        ls.forEach(s -> System.out.println(s));

    }

}

I have used java 8 specific isNull i.e ls.removeIf(Objects::isNull); still in the o/p I see null value
i.e
O/p is

Student {name=Dino} Student {name=null} Student {name=Fred} Student
  {name=Amy}

Am I missing on something specific ?

Thanks
Ronan


问:
Generate all natural numbers that have 3 digits whose 3rd digit - 1st digit=2nd digit
The problem's in the title.
If possible please give me exaplanations on what I did wrong and why correct solution is correct.

My attempt at solving it is in the code below... it was supposed get me all the 3 digit numbers then extract digit1, digit2 and digit3 from each number after which it should show the numbers that respect the digit3-digit1==digit2.
The program runs without errors but at the same time it doesn't really do anything.

```<code>#include <iostream>

using namespace std;

int main()
{
    int Number,digit1,digit2,digit3,h;
    for (Number=100; Number<=999; Number++)
    {
        h=Number;
    }
    digit1=h/100;
    digit2=(h/10)%10;
    digit3=h%10;
    if (digit3-digit1==digit2)
        cout<<digit1<<digit2<<digit3;
    return 0;
}
</code>```

答:
The code that comes after the loop (other than return 0) has to go inside the loop. If it's outside the loop then it only works on the value 999, because that is the last value that h is set to before the loop exits. To print a new line you have to do cout << endl or just place << endl at the end of the print statement before the semicolon.

A few optimizations can be made here. You don't need to loop through all 899 numbers. Given the constraints the the third digit has to be greater than or equal to the first digit, so you can just run a loop for the first digit, and nested loop for the third digit that starts from the first digit.

for (int a = 1; a < 10; a++) {
  for (int c = a; c < 10; c++) {
    int b = c - a;
    cout << a << b << c << endl;
  }
}
```

Body:
The problem's in the title.
If possible please give me exaplanations on what I did wrong and why correct solution is correct.

My attempt at solving it is in the code below... it was supposed get me all the 3 digit numbers then extract digit1, digit2 and digit3 from each number after which it should show the numbers that respect the digit3-digit1==digit2.
The program runs without errors but at the same time it doesn't really do anything.

#include <iostream>

using namespace std;

int main()
{
    int Number,digit1,digit2,digit3,h;
    for (Number=100; Number<=999; Number++)
    {
        h=Number;
    }
    digit1=h/100;
    digit2=(h/10)%10;
    digit3=h%10;
    if (digit3-digit1==digit2)
        cout<<digit1<<digit2<<digit3;
    return 0;
}


问:
Is there any way to carry over background color between HTML documents?
My background color for my HTML page is white by default, and I have an option to set it to black via an anchor with no href attached to it. I also have another anchor with a link to another HTML page, however if the background color is black and you click the link to the second HTML page, the background color of the second page does not stay black. Is there a way to have the background color transfer over?

Here is the JavaScript function:

```<code>function changeBG(colour) {
  document.body.style.backgroundColor = colour;
}
</script>
</code>```

Here are the anchors to change the background color:

```<code><a href="#" onClick="javascript: changeBG('white')">Light Theme</a>

<a href="#" onClick="javascript: changeBG('black')">Dark Theme</a>
</div>
</code>```

Here is the anchor to go to the next HTML page:

Next Page

答:
You can utilize the browser's localStorage to save & retrieve the background colour.

To do this you need to modify the changeBG() function a little:

```<code>function changeBG(colour) {
  document.body.style.backgroundColor = colour;
  localStorage.setItem('backColour', colour);
}
</code>```

This will save the background colour into the localStarge, accessible using the variable backColour.

In your other html file you can do something like this

```<code>if (localStorage.getItem('backColour') != null) {
  document.body.style.backgroundColor = localStorage.getItem('backColour');
}
</code>```

So in case there is a value for backColour inside localStorage, use it as the background colour.

Body:
My background color for my HTML page is white by default, and I have an option to set it to black via an anchor with no href attached to it. I also have another anchor with a link to another HTML page, however if the background color is black and you click the link to the second HTML page, the background color of the second page does not stay black. Is there a way to have the background color transfer over?

Here is the JavaScript function:

function changeBG(colour) {
  document.body.style.backgroundColor = colour;
}
</script>

Here are the anchors to change the background color:

Light Theme

Dark Theme

Here is the anchor to go to the next HTML page:

Next Page

Body:
You can utilize the browser's localStorage to save & retrieve the background colour.

To do this you need to modify the changeBG() function a little:

function changeBG(colour) {
  document.body.style.backgroundColor = colour;
  localStorage.setItem('backColour', colour);
}

This will save the background colour into the localStarge, accessible using the variable backColour.

In your other html file you can do something like this

if (localStorage.getItem('backColour') != null) {
  document.body.style.backgroundColor = localStorage.getItem('backColour');
}

So in case there is a value for backColour inside localStorage, use it as the background colour.


问:
How to get the mouse pos relative to the background img
I need to get the mouse position on a divs background img.

This is the css:

```<code>width: 100%;
height: 100%;
background-image: url("default.png");
background-size: contain;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
</code>```

This is the html:

Any help would really be appreciated.

-----------------Edit--------------------
The img has a fixed size so it doesn't fill up the whole browser screen.

答:
Use an EventListener!

div.addEventListener("mousemove", function(e) {
  console.log(e.layerX, e.layerY)
}, false)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
  width: 400px;
  height: 400px;
  border: 1px black dotted
}</code>```

```

Body:
I need to get the mouse position on a divs background img.

This is the css:

width: 100%;
height: 100%;
background-image: url("default.png");
background-size: contain;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;

This is the html:

Any help would really be appreciated.

-----------------Edit--------------------
The img has a fixed size so it doesn't fill up the whole browser screen.

Body:
Use an EventListener!

div.addEventListener("mousemove", function(e) {
  console.log(e.layerX, e.layerY)
}, false)

#div {
  width: 400px;
  height: 400px;
  border: 1px black dotted
}

<div id="div"></div>


问:
Rails 4: Insert Attribute Into Params
In Rails 3, it was possible to insert an attribute into params like so:

```<code>params[:post][:user_id] = current_user.id
</code>```

I'm attempting to do something similar in Rails 4, but having no luck:

```<code>post_params[:user_id] = current_user.id

. . . .

private

  def post_params
    params.require(:post).permit(:user_id)
  end
</code>```

Rails is ignoring this insertion. It doesn't throw any errors, it just quietly fails.

答:
If anyone is trying to figure out how to add/edit a nested attribute in a Rails 5 attributes hash, I found this to be the most straight-forward (alternate) approach. Don't bother with merge or deep_merge...it's a pain due to the strong parameters. In this example, I needed to copy the group_id and vendor_id to the associated invoice (nested parameters) prior to saving.</p>

```<code>def create
  my_params = order_params
  @order = Order.new
  @order.attributes = my_params
  @order.invoice.group_id = my_params[:group_id]
  @order.invoice.vendor_id = my_params[:vendor_id]
  @order.save
end

private

# Permit like normal
def order_params
  params.require(:order).permit([:vendor_id, :group_id, :amount, :shipping,:invoice_attributes => [:invoice_number, :invoice_date, :due_date, :vendor_id, :group_id]])
end
</code>```

Title: Rails 4: Insert Attribute Into Params

Body:
In Rails 3, it was possible to insert an attribute into params like so:

params[:post][:user_id] = current_user.id

I'm attempting to do something similar in Rails 4, but having no luck:

post_params[:user_id] = current_user.id

. . . .

private

  def post_params
    params.require(:post).permit(:user_id)
  end

Rails is ignoring this insertion. It doesn't throw any errors, it just quietly fails.

Body:
If anyone is trying to figure out how to add/edit a nested attribute in a Rails 5 attributes hash, I found this to be the most straight-forward (alternate) approach. Don't bother with merge or deep_merge...it's a pain due to the strong parameters. In this example, I needed to copy the group_id and vendor_id to the associated invoice (nested parameters) prior to saving.

def create
  my_params = order_params
  @order = Order.new
  @order.attributes = my_params
  @order.invoice.group_id = my_params[:group_id]
  @order.invoice.vendor_id = my_params[:vendor_id]
  @order.save
end

private

# Permit like normal
def order_params
  params.require(:order).permit([:vendor_id, :group_id, :amount, :shipping,:invoice_attributes => [:invoice_number, :invoice_date, :due_date, :vendor_id, :group_id]])
end