问:
Why a sudden Run-time error '6' Overflow - Access VBA?
Just received Run-time error '6' Overflow for the first time in an Access Db that has been running without error for over a year. Nothing has changed in the code or data. I cannot figure out why this has suddenly popped up. This is creating an email. Can anyone help?

Below is my code where the error is occurring:

```<code>enter code here
Public Sub proc_AutomateEmail_EVerify()
On Error GoTo Err_MakeEmail_EV

Dim dbs As Database
Dim rsEMails As Recordset
Dim rsEE As Recordset

Dim objOutlook As Outlook.Application
Dim objEmail As Outlook.MailItem

Dim sHTML_Email As String
Dim sHTMLHead As String
Dim sHTMLClose As String
Dim sTableOpen As String
Dim sTableClose As String
Dim sTableExtra As String

Dim sLetterOpen As String
Dim sLetterClose As String
Dim sLetterClose2 As String

Dim sTableBody As String

Dim sAddresses As String
Dim sCC As String

Dim sPath As String
Dim sFile As String
Dim sAttach As String

Dim sBase As String
Dim sAsOf As String
Dim sPathAttach As String

Dim theEmailID As Integer
Dim theEMailQuery As String
Dim theHistQuery As String

Dim theEMailStatus As String
Dim theEmailCrit As String
Dim sqlEE As String

'Change status box to yellow and create initial message
Forms!frm_Email_Parts_Process!txtShowStatus.BackColor = RGB(255, 255, 200)
Forms!frm_Email_Parts_Process!txtShowStatus = "Creating Emails for the following person(Sector):"

Set dbs = CurrentDb
Set objOutlook = CreateObject("Outlook.Application")

'HTML Code to open and close the email - this has nothing to do with email content
sHTMLHead = DLookup("[ConfigVal]", "admin_Config_Memo", "ConfigVar='Email_Automate_Reverify_Head_01'")
sHTMLClose = DLookup("[ConfigVal]", "admin_Config_Memo", "ConfigVar='Email_Automate_Reverify_Close_01'")

sTableExtra = ""

sPathAttach = DLookup("[ConfigVal]", "Admin_Config", "[ConfigVar] = 'AttachmentPath'")

theEmailID = Nz(Forms!frm_Email_Parts_Process!lstPickEmail, 0)

theEmailCrit = "EMPartsID = " & theEmailID
Debug.Print "theEMailCrit: " & theEmailCrit

theEMailQuery = DLookup("[EMPartsQuery]", "data_EMail_Parts", theEmailCrit)
theHistQuery = DLookup("[EMPartsQuery_App]", "data_EMail_Parts", theEmailCrit)

theEMailStatus = DLookup("[EMPartsDisplayStatus]", "data_EMail_Parts", theEmailCrit)
Debug.Print "theEMailQuery: " & theEMailQuery

'Open and closing content and Subject line of the email
sLetterOpen = DLookup("[EMPartsIntro]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)
sLetterClose = DLookup("[EMPartsClose]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)
sLetterClose2 = DLookup("[EMPartsClose2]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)

sSubject = DLookup("[EMPartsSubject]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)
sAttach = DLookup("[EMPartsAttach]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)

'Table headers for the list of employees
sTableOpen = "<br /><br /><table>"
sTableClose = "</table><br /><br />"

'If theEmailID = 12 Then ' need extra 'table' for end of email
'
'    sTableExtra = "<table id='closereason'>"
'    sTableExtra = sTableExtra & "<tr class='theheader'><td>Employment Status</td><td>Authorized E-Verify Case Closure Reason</td></tr>"
'
'    sTableExtra = sTableExtra & "<tr><td>Active</td><td>The employee continues to work after receiving an Employment Authorized result.</td></tr>"
'    sTableExtra = sTableExtra & "<tr><td>Employee Resignation</td><td>The employee voluntarily quit working for the employer.</td></tr>"
'    sTableExtra = sTableExtra & "<tr><td>Termination UNRELATED to E-Verify Process</td><td>The employee was terminated by the employer for reasons other than E-Verify.</td></tr>"
'    sTableExtra = sTableExtra & "<tr><td rowspan='3'>Termination Related to  E-Verify Process</td><td>The employee was terminated by the employer for receiving a No Show result.</td></tr>"
'    sTableExtra = sTableExtra & "<tr><td>The employee was terminated by the employer for receiving a Final Nonconfirmation.</td></tr>"
'    sTableExtra = sTableExtra & "<tr><td>The employee was terminated by the employer for choosing NOT to contest a Tentative Nonconfirmation.</td></tr>"
'
'    sTableExtra = sTableExtra & "</table>"
'
'End If

'Get list of people for emailing - try without fully anotated : email_automate_Reverify_I9Expire_prior_90.
' for testing:  SELECT Top 5

sqlPeople = "SELECT [Emp Custom_ChiefEmail_Replace], " & _
                          "[Business Unit], " & _
                          "Count([Employee ID]) AS [CountIt] " & _
            "FROM " & theEMailQuery & " " & _
            "GROUP BY [Emp Custom_ChiefEmail_Replace], " & _
                     "[Business Unit] " & _
            "HAVING ((([Emp Custom_ChiefEmail_Replace]) Is Not Null));"

Set rsEMails = dbs.OpenRecordset(sqlPeople)

    If rsEMails.RecordCount > 0 Then
                rsEMails.MoveLast
                rsEMails.MoveFirst

            'Loop through people
            Do Until rsEMails.EOF

                Debug.Print "CHIEF: " & rsEMails![Emp Custom_ChiefEmail_Replace]

                Forms!frm_Email_Parts_Process!txtShowStatus = rsEMails![Emp Custom_ChiefEmail_Replace] & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus

                'Detail listing of people for the email
                sTableBody = "<tr><td class = 'colhead_loc'>Location</td>" & _
                                 "<td class = 'colhead_eename'>Employee Name</td>" & _
                                 "<td class = 'colhead_eeid'>Employee ID</td>" & _
                                 "<td class = 'colhead_eeid'>Date Hired</td>" & _
                                 "<td class = 'colhead_eename'>E-Verify Status</td></tr>"

                sTableBody = sTableBody & "<tr class='trblankrow'><td colspan='5'></td></tr>"

                'List Employees Section - FULL NAME : email_automate_Reverify_I9Expire_prior_90.
                sqlEE = "SELECT [Business Unit], " & _
                               "[Location Number], " & _
                               "[Location Name], " & _
                               "[Employee Name], " & _
                               "[Employee ID], " & _
                               "[Date Hired], " & _
                               "[EV Current Status] " & _
                        "From " & theEMailQuery & " " & _
                        "WHERE ((([Emp Custom_ChiefEmail_Replace])=" & Chr(34) & rsEMails![Emp Custom_ChiefEmail_Replace] & Chr(34) & "));"

                Set rsEE = dbs.OpenRecordset(sqlEE)

                          If rsEE.RecordCount > 0 Then
                                rsEE.MoveLast
                                rsEE.MoveFirst

                                'Loop through people
                                Do Until rsEE.EOF
                                Debug.Print "EE: " & rsEE![Employee Name]
                                    sTableBody = sTableBody & "<tr class='trplain'><td class='td_txt_left'>" & rsEE![Location Name] & " (" & rsEE![Location Number] & ")</td>" & _
                                                                                "<td class='td_txt_left'>" & rsEE![Employee Name] & "</td>" & _
                                                                                "<td class='td_txt_ctr'>" & rsEE![Employee ID] & "</td>" & _
                                                                                "<td class='td_txt_ctr'>" & rsEE![Date Hired] & "</td>" & _
                                                                                "<td class='td_txt_ctr'>" & theEMailStatus & "</td></tr>"
                                    rsEE.MoveNext
                                Loop 'rsEe
                                rsEE.Close

                            Else ' No email addresses
                                sTableBody = sTableBody & "<tr><td colspan='4' class = 'tblhead1boldit'>No Employees for this Chief</td></tr>"

                          End If

                'Get email addresses
                sAddresses = rsEMails![Emp Custom_ChiefEmail_Replace]
                'sCC = DLookup("BUN_Email_CC", "[data_BusinessUnit]", sCritAddresses)

                'Create the email
                sHTML_Email = sHTMLHead & sLetterOpen & sTableOpen & sTableBody & sTableClose & sLetterClose & sLetterClose2 & sHTMLClose
                'Debug.Print sHTML_Email

                Set objEmail = objOutlook.CreateItem(olMailItem)
                   With objEmail
                       .To = sAddresses
                       '.CC = sCC
                       .Subject = sSubject
                       If sAttach <> "none" Then
                        .Attachments.Add sPathAttach & sAttach
                       End If
                       .BodyFormat = olFormatHTML
                       .HTMLBody = sHTML_Email
                       .Save
                    End With
                 Set objEmail = Nothing

                 rsEMails.MoveNext

            Loop 'rsEMails
            rsEMails.Close

    Else ' No email addresses

    End If

dbs.Close

'Update status indicator - Adding names to history list
Forms!frm_Email_Parts_Process!txtShowStatus = "-------------------------------" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus
Forms!frm_Email_Parts_Process!txtShowStatus = "Adding names to history list" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus
Forms!frm_Email_Parts_Process!txtShowStatus = "-------------------------------" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus

DoCmd.SetWarnings False
DoCmd.OpenQuery theHistQuery
DoCmd.SetWarnings True

'Update status indicator - Set back color to green
Forms!frm_Email_Parts_Process!txtShowStatus.BackColor = RGB(200, 255, 200)
Forms!frm_Email_Parts_Process!txtShowStatus = "-- Process complete --" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus

Exit_MakeEmail_EV:
Exit Sub

Err_MakeEmail_EV:

DoCmd.SetWarnings True

Select Case Err.Number
      Case 6                           ' Overflow due to 0 in data
          Call LogError(Err.Number, Err.Description, "Sector: " & sCurrentSector)
          Resume Next                  ' Use this to just ignore the line.

      Case 94                           ' Overflow due to 0 in data
          Call LogError(Err.Number, Err.Description, "Sector: " & sCurrentSector)
          Resume Next                  ' Use this to just ignore the line.

      Case 3075                           ' Apostrophe Error ???
          Call LogError(Err.Number, rsEMails![Business Unit], "Apostrophe Error")
          Resume Next                  ' Use this to just ignore the line.

      Case 3420                           ' Overflow due to 0 in data
          Call LogError(Err.Number, "Error Log Error", "Unknown")
          Resume Next                  ' Use this to just ignore the line.

      Case 999
          Resume Exit_MakeEmail_EV         ' Use this to give up on the proc.

      Case Else                        ' Any unexpected error.
          Call LogError(Err.Number, Err.Description, "Sector: " & sCurrentSector)
          Resume Exit_MakeEmail_EV
End Select

End Sub
</code>```

答:
Nothing has changed in the code or data.

So the data remains the same? I doubt that.

It could be that you have run out of Integer values. So try:

```<code>Dim theEmailID As Long
</code>```

Body:
Just received Run-time error '6' Overflow for the first time in an Access Db that has been running without error for over a year. Nothing has changed in the code or data. I cannot figure out why this has suddenly popped up. This is creating an email. Can anyone help?

Below is my code where the error is occurring:

enter code here
Public Sub proc_AutomateEmail_EVerify()
On Error GoTo Err_MakeEmail_EV

Dim dbs As Database
Dim rsEMails As Recordset
Dim rsEE As Recordset

Dim objOutlook As Outlook.Application
Dim objEmail As Outlook.MailItem

Dim sHTML_Email As String
Dim sHTMLHead As String
Dim sHTMLClose As String
Dim sTableOpen As String
Dim sTableClose As String
Dim sTableExtra As String

Dim sLetterOpen As String
Dim sLetterClose As String
Dim sLetterClose2 As String

Dim sTableBody As String

Dim sAddresses As String
Dim sCC As String

Dim sPath As String
Dim sFile As String
Dim sAttach As String

Dim sBase As String
Dim sAsOf As String
Dim sPathAttach As String

Dim theEmailID As Integer
Dim theEMailQuery As String
Dim theHistQuery As String

Dim theEMailStatus As String
Dim theEmailCrit As String
Dim sqlEE As String

'Change status box to yellow and create initial message
Forms!frm_Email_Parts_Process!txtShowStatus.BackColor = RGB(255, 255, 200)
Forms!frm_Email_Parts_Process!txtShowStatus = "Creating Emails for the following person(Sector):"

Set dbs = CurrentDb
Set objOutlook = CreateObject("Outlook.Application")

'HTML Code to open and close the email - this has nothing to do with email content
sHTMLHead = DLookup("[ConfigVal]", "admin_Config_Memo", "ConfigVar='Email_Automate_Reverify_Head_01'")
sHTMLClose = DLookup("[ConfigVal]", "admin_Config_Memo", "ConfigVar='Email_Automate_Reverify_Close_01'")

sTableExtra = ""

sPathAttach = DLookup("[ConfigVal]", "Admin_Config", "[ConfigVar] = 'AttachmentPath'")

theEmailID = Nz(Forms!frm_Email_Parts_Process!lstPickEmail, 0)

theEmailCrit = "EMPartsID = " & theEmailID
Debug.Print "theEMailCrit: " & theEmailCrit

theEMailQuery = DLookup("[EMPartsQuery]", "data_EMail_Parts", theEmailCrit)
theHistQuery = DLookup("[EMPartsQuery_App]", "data_EMail_Parts", theEmailCrit)

theEMailStatus = DLookup("[EMPartsDisplayStatus]", "data_EMail_Parts", theEmailCrit)
Debug.Print "theEMailQuery: " & theEMailQuery

'Open and closing content and Subject line of the email
sLetterOpen = DLookup("[EMPartsIntro]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)
sLetterClose = DLookup("[EMPartsClose]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)
sLetterClose2 = DLookup("[EMPartsClose2]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)

sSubject = DLookup("[EMPartsSubject]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)
sAttach = DLookup("[EMPartsAttach]", "data_EMail_Parts", "[EMPartsID] = " & theEmailID)

'Table headers for the list of employees
sTableOpen = "

"
sTableClose = "

"

'If theEmailID = 12 Then ' need extra 'table' for end of email
'
'    sTableExtra = "
"
'    sTableExtra = sTableExtra & "
Employment Status	Authorized E-Verify Case Closure Reason
"
'
'    sTableExtra = sTableExtra & "
Active	The employee continues to work after receiving an Employment Authorized result.
"
'    sTableExtra = sTableExtra & "
Employee Resignation	The employee voluntarily quit working for the employer.
"
'    sTableExtra = sTableExtra & "
Termination UNRELATED to E-Verify Process	The employee was terminated by the employer for reasons other than E-Verify.
"
'    sTableExtra = sTableExtra & "
Termination Related to  E-Verify Process	The employee was terminated by the employer for receiving a No Show result.
"
'    sTableExtra = sTableExtra & "
The employee was terminated by the employer for receiving a Final Nonconfirmation.
"
'    sTableExtra = sTableExtra & "
The employee was terminated by the employer for choosing NOT to contest a Tentative Nonconfirmation.
"
'
'    sTableExtra = sTableExtra & "
"
'
'End If

'Get list of people for emailing - try without fully anotated : email_automate_Reverify_I9Expire_prior_90.
' for testing:  SELECT Top 5

sqlPeople = "SELECT [Emp Custom_ChiefEmail_Replace], " & _
                          "[Business Unit], " & _
                          "Count([Employee ID]) AS [CountIt] " & _
            "FROM " & theEMailQuery & " " & _
            "GROUP BY [Emp Custom_ChiefEmail_Replace], " & _
                     "[Business Unit] " & _
            "HAVING ((([Emp Custom_ChiefEmail_Replace]) Is Not Null));"

Set rsEMails = dbs.OpenRecordset(sqlPeople)

    If rsEMails.RecordCount > 0 Then
                rsEMails.MoveLast
                rsEMails.MoveFirst

            'Loop through people
            Do Until rsEMails.EOF

                Debug.Print "CHIEF: " & rsEMails![Emp Custom_ChiefEmail_Replace]

                Forms!frm_Email_Parts_Process!txtShowStatus = rsEMails![Emp Custom_ChiefEmail_Replace] & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus

                'Detail listing of people for the email
                sTableBody = "
Location	" & _
                                 "Employee Name	" & _
                                 "Employee ID	" & _
                                 "Date Hired	" & _
                                 "E-Verify Status
"

                sTableBody = sTableBody & "

"

                'List Employees Section - FULL NAME : email_automate_Reverify_I9Expire_prior_90.
                sqlEE = "SELECT [Business Unit], " & _
                               "[Location Number], " & _
                               "[Location Name], " & _
                               "[Employee Name], " & _
                               "[Employee ID], " & _
                               "[Date Hired], " & _
                               "[EV Current Status] " & _
                        "From " & theEMailQuery & " " & _
                        "WHERE ((([Emp Custom_ChiefEmail_Replace])=" & Chr(34) & rsEMails![Emp Custom_ChiefEmail_Replace] & Chr(34) & "));"

                Set rsEE = dbs.OpenRecordset(sqlEE)

                          If rsEE.RecordCount > 0 Then
                                rsEE.MoveLast
                                rsEE.MoveFirst

                                'Loop through people
                                Do Until rsEE.EOF
                                Debug.Print "EE: " & rsEE![Employee Name]
                                    sTableBody = sTableBody & "
" & rsEE![Location Name] & " (" & rsEE![Location Number] & ")	" & _
                                                                                "" & rsEE![Employee Name] & "	" & _
                                                                                "" & rsEE![Employee ID] & "	" & _
                                                                                "" & rsEE![Date Hired] & "	" & _
                                                                                "" & theEMailStatus & "
"
                                    rsEE.MoveNext
                                Loop 'rsEe
                                rsEE.Close

                            Else ' No email addresses
                                sTableBody = sTableBody & "
No Employees for this Chief
"

                          End If

                'Get email addresses
                sAddresses = rsEMails![Emp Custom_ChiefEmail_Replace]
                'sCC = DLookup("BUN_Email_CC", "[data_BusinessUnit]", sCritAddresses)

                'Create the email
                sHTML_Email = sHTMLHead & sLetterOpen & sTableOpen & sTableBody & sTableClose & sLetterClose & sLetterClose2 & sHTMLClose
                'Debug.Print sHTML_Email

                Set objEmail = objOutlook.CreateItem(olMailItem)
                   With objEmail
                       .To = sAddresses
                       '.CC = sCC
                       .Subject = sSubject
                       If sAttach <> "none" Then
                        .Attachments.Add sPathAttach & sAttach
                       End If
                       .BodyFormat = olFormatHTML
                       .HTMLBody = sHTML_Email
                       .Save
                    End With
                 Set objEmail = Nothing

                 rsEMails.MoveNext

            Loop 'rsEMails
            rsEMails.Close

    Else ' No email addresses

    End If

dbs.Close

'Update status indicator - Adding names to history list
Forms!frm_Email_Parts_Process!txtShowStatus = "-------------------------------" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus
Forms!frm_Email_Parts_Process!txtShowStatus = "Adding names to history list" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus
Forms!frm_Email_Parts_Process!txtShowStatus = "-------------------------------" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus

DoCmd.SetWarnings False
DoCmd.OpenQuery theHistQuery
DoCmd.SetWarnings True

'Update status indicator - Set back color to green
Forms!frm_Email_Parts_Process!txtShowStatus.BackColor = RGB(200, 255, 200)
Forms!frm_Email_Parts_Process!txtShowStatus = "-- Process complete --" & vbCr & vbLf & Forms!frm_Email_Parts_Process!txtShowStatus

Exit_MakeEmail_EV:
Exit Sub

Err_MakeEmail_EV:

DoCmd.SetWarnings True

Select Case Err.Number
      Case 6                           ' Overflow due to 0 in data
          Call LogError(Err.Number, Err.Description, "Sector: " & sCurrentSector)
          Resume Next                  ' Use this to just ignore the line.

      Case 94                           ' Overflow due to 0 in data
          Call LogError(Err.Number, Err.Description, "Sector: " & sCurrentSector)
          Resume Next                  ' Use this to just ignore the line.

      Case 3075                           ' Apostrophe Error ???
          Call LogError(Err.Number, rsEMails![Business Unit], "Apostrophe Error")
          Resume Next                  ' Use this to just ignore the line.

      Case 3420                           ' Overflow due to 0 in data
          Call LogError(Err.Number, "Error Log Error", "Unknown")
          Resume Next                  ' Use this to just ignore the line.

      Case 999
          Resume Exit_MakeEmail_EV         ' Use this to give up on the proc.

      Case Else                        ' Any unexpected error.
          Call LogError(Err.Number, Err.Description, "Sector: " & sCurrentSector)
          Resume Exit_MakeEmail_EV
End Select

End Sub

Body:
Nothing has changed in the code or data.

So the data remains the same? I doubt that.

It could be that you have run out of Integer values. So try:

Dim theEmailID As Long


来源: stackexchange

问:
How to delete a paragraph using XWPF - Apache POI
I am trying to delete a paragraph from the .docx document i have generated using the Apache poi XWPF. I can do it easily with the .doc word document using HWPF as below :

```<code>    for (String paraCount : plcHoldrPargrafDletdLst) {
        Paragraph ph = doc.getRange().getParagraph(Integer.parseInt(paraCount));
        System.out.println("Deleted Paragraph Start & End: " + ph.getStartOffset() +" & " + ph.getEndOffset());
        System.out.println("Deleted Paragraph Test: " + ph.text());
        ph.delete();
    }
</code>```

I tried to do the same with

doc.removeBodyElement(Integer.parseInt(paraCount));

But unfortunatley not successful enough to get the result as i want. The result document, i cannot see the paragraph deleted.
Any suggestions on how to accompolish the similar functionality in XWPF.

答:
I like Apache POI, and for the most part its great, however I have found the documentation a little scatty to say the least.

The elusive way of deleting a paragraph I found to be quite a nightmare, giving me the following exception error when try to remove a paragraph:

java.util.ConcurrentModificationException

As mention in Ugo Delle Donne example, I solved this by first recording the paragraph that I wanted to delete, and then using the removeBodyElement method the document.

e.g.

```<code>List<XWPFParagraph> record = new ArrayList<XWPFParagraph>();
String text = "";

for (XWPFParagraph p : doc.getParagraphs()){
    for (XWPFRun r : p.getRuns()){

       text += r.text();
       // I saw so many examples as r.getText(pos), don't use that

       // Find some unique text in the paragraph
       //
       if (!(text==null) && (text.contains("SOME-UNIQUE-TEXT")) {
        // Save the Paragraph to delete for later
        record.add(  p );
       }
    }
}

// Now delete the paragraph and anything within it.
    for(int i=0; i< record.size(); i++)
    {
        // Remove the Paragraph and everything within it
        doc.removeBodyElement(doc.getPosOfParagraph( record.get(i) ));
    }
</code>```

// Shaaazam, I hope this helps !

ContentLicense: CC BY-SA 3.0

Body:
I am trying to delete a paragraph from the .docx document i have generated using the Apache poi XWPF. I can do it easily with the .doc word document using HWPF as below :

    for (String paraCount : plcHoldrPargrafDletdLst) {
        Paragraph ph = doc.getRange().getParagraph(Integer.parseInt(paraCount));
        System.out.println("Deleted Paragraph Start & End: " + ph.getStartOffset() +" & " + ph.getEndOffset());
        System.out.println("Deleted Paragraph Test: " + ph.text());
        ph.delete();
    }

I tried to do the same with

doc.removeBodyElement(Integer.parseInt(paraCount));

But unfortunatley not successful enough to get the result as i want. The result document, i cannot see the paragraph deleted.
Any suggestions on how to accompolish the similar functionality in XWPF.

Body:
I like Apache POI, and for the most part its great, however I have found the documentation a little scatty to say the least.

The elusive way of deleting a paragraph I found to be quite a nightmare, giving me the following exception error when try to remove a paragraph:

java.util.ConcurrentModificationException

As mention in Ugo Delle Donne example, I solved this by first recording the paragraph that I wanted to delete, and then using the removeBodyElement method the document.

e.g.

List<XWPFParagraph> record = new ArrayList<XWPFParagraph>();
String text = "";

for (XWPFParagraph p : doc.getParagraphs()){
    for (XWPFRun r : p.getRuns()){

       text += r.text();
       // I saw so many examples as r.getText(pos), don't use that

       // Find some unique text in the paragraph
       //
       if (!(text==null) && (text.contains("SOME-UNIQUE-TEXT")) {
        // Save the Paragraph to delete for later
        record.add(  p );
       }
    }
}

// Now delete the paragraph and anything within it.
    for(int i=0; i< record.size(); i++)
    {
        // Remove the Paragraph and everything within it
        doc.removeBodyElement(doc.getPosOfParagraph( record.get(i) ));
    }

// Shaaazam, I hope this helps !

ContentLicense: CC BY-SA 4.0


问:
Unclear Bad Request messages from Asp.Net Core API model binding when there is a JSON parser error (e.g. type mismatch)?
If I send a JSON body with a wrong type (e.g. integer where a string is expected in a model by Asp.Net Core), I get a following message:

"$.name": [
              "The JSON value could not be converted to System.String. Path: $.name | LineNumber: 1 | BytePositionInLine: 11."
          ]

This information is not very clear for a random user of a Web Api. Additionally if the same error happens with enum, it will also leak information about fully qualified name of the enum (including namespace) and is even more meaningless for a user than System.String.

Is there any better way to handle this in WebApi? E.g. to change all messages to a generic Value was not of expected type or something like that?

I know of two possible solutions, but both are rather cumbersome:

All models should accept string (though we'll still get the one with string, but it's at least more or less understandable) or object (if it's possible). Then all the validation and mapping should be done manually

Wringing a Converter for each type that is used in model and supplying it to WebApi to use

I really hope there is a better way that allows us to e.g "catch" the exception from parser or inherit from a default converter, etc.

答:
Your test/debug version of the API should provide detailed information about how a request is wrong, and you should also put information about these errors in your public documentation.

Your release version should hide all of these details and return some sort of 4XX.

This means every public API should be something like:

```<code>public IActionResult MyApiFunction()
{
 try
 {
    ... do something
 }
 catch(Exception ex)
 {
   ... do some logging
   return BadRequest();
 }
}
</code>```

The bottom line is that the user of the API didn't follow the spec, therefore it was a bad request, end of.

Body:
Your test/debug version of the API should provide detailed information about how a request is wrong, and you should also put information about these errors in your public documentation.

Your release version should hide all of these details and return some sort of 4XX.

This means every public API should be something like:

public IActionResult MyApiFunction()
{
 try
 {
    ... do something
 }
 catch(Exception ex)
 {
   ... do some logging
   return BadRequest();
 }
}

The bottom line is that the user of the API didn't follow the spec, therefore it was a bad request, end of.


问:
React Native - Error using Chart Kit (Exception thrown while executing UI block: __NSCFNumber firstObject: unrecognized selector sent to instance)
Im trying to run a basic React Native App using the Chart Kit library I get this error:
CLICK FOR IMAGE: Exception thrown while executing UI block: __NSCFNumber firstObject: unrecognized selector sent to instance 0xa3576e305374b97e

Does someone know how to fix it?

This is my code:

```<code>import React from 'react';
import { View, StyleSheet } from 'react-native';
import { LineChart, Grid } from 'react-native-svg-charts';

class LineChartExample extends React.PureComponent {
  render() {
    const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80];

    return (
        <LineChart
            style={{ height: 200 }}
            data={data}
            svg={{ stroke: 'rgb(134, 65, 244)' }}
            contentInset={{ top: 20, bottom: 20 }}
        >
          <Grid />
        </LineChart>
    )
  }
}

export default LineChartExample;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

答:
I have the same issue, but did not solved using "expo install install react-native-chart-kit"

the issue  continue

Exception thrown while executing UI block: __NSCFNumber firstObject: unrecognized selector sent to instance 0x9d7ca23b6657dd3d

EDITING: I solved my issue, steps:

1 - use CMD aways... create your expo-project and all dependences and library using CMD prompt comand windows... dont use PowerShell

2 - install react-native-svg-charts, react-native-chart-kit, react-native-svg-charts,   using "expo instal ...." DON'T use yarn add or npm install

I hope this help everyone to create charts with expo....

Body:
Im trying to run a basic React Native App using the Chart Kit library I get this error:
CLICK FOR IMAGE: Exception thrown while executing UI block: __NSCFNumber firstObject: unrecognized selector sent to instance 0xa3576e305374b97e

Does someone know how to fix it?

This is my code:

import React from 'react';
import { View, StyleSheet } from 'react-native';
import { LineChart, Grid } from 'react-native-svg-charts';

class LineChartExample extends React.PureComponent {
  render() {
    const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80];

    return (
        <LineChart
            style={{ height: 200 }}
            data={data}
            svg={{ stroke: 'rgb(134, 65, 244)' }}
            contentInset={{ top: 20, bottom: 20 }}
        >
          <Grid />
        </LineChart>
    )
  }
}

export default LineChartExample;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


问:
How to dockerize my flask web app with mysql database?Cannot connect mysql and cannot found render templete
I am new to docker and trying to deploy this web app but cannot find solution.
I’m running windows 10 and Docker Desktop. My docker-version is 19.03.5 and docker-compose version 1.25.4, build unknown.

My directory structure is:

```<code>  -docker-compose.yml
  -app
     -static
          js/
            script.js
          css/
              style.css
     -templates
            -index.html
     -app.py
     -dockerfile
     -requirements.txt
  -db
    -init.sql
</code>```

docker-compose.yml

```<code>version: "2"
services:
app:
  build: ./app
  links:
    - db
  ports:
    - "5000:5000"

db:
  image: mysql:5.7
  ports:
    - "32000:3306"
  environment:
    MYSQL_ROOT_PASSWORD: root
  volumes:
    - ./db:/docker-entrypoint-initdb.d/:ro
</code>```

dockerfile

```<code>FROM python:3.6
EXPOSE 5000
RUN mkdir -p /app
RUN ls /app
COPY static /app/static
COPY templates /app/templates
COPY app.py /app
COPY requirements.txt /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD python app.py
</code>```

requirements.txt

```<code>flask
mysql-connector
</code>```

app.py

```<code>from flask import Flask, render_template, request
import mysql.connector
import os

app = Flask(__name__, template_folder='/templates', static_folder='/static')
@app.route('/')
def index():
    connection = mysql.connector.connect(
        user = 'root',
        password = 'root',
        host= 'db',
        port = '3306',
        database = 'test'
    )
    cursor = connection.cursor()
    cursor.execute("SELECT name from place")
    names = cursor.fetchall()
    return render_template('index.html', names = names)
if __name__ == '__main__':
    app.run(host='0.0.0.0')
</code>```

My docker command is –

```<code>docker-compose up
</code>```

Then trying to access  http://0.0.0.0:5000/ but get mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'db:3306' and  jinja2.exceptions.TemplateNotFound:

答:
jinja2.exceptions.TemplateNotFound

Your flask folder paths are wrong, it should be either an absolute path like /app/templates and /app/static or a relative one like templates abnd static.

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'db:3306'

If your init.sql script is correct then there is nothing wrong with your database, you just have let it initialize properly (wait for the mysqld: ready for connections message) before sending your first request.

Body:
I am new to docker and trying to deploy this web app but cannot find solution.
I’m running windows 10 and Docker Desktop. My docker-version is 19.03.5 and docker-compose version 1.25.4, build unknown.

My directory structure is:

  -docker-compose.yml
  -app
     -static
          js/
            script.js
          css/
              style.css
     -templates
            -index.html
     -app.py
     -dockerfile
     -requirements.txt
  -db
    -init.sql

docker-compose.yml

version: "2"
services:
app:
  build: ./app
  links:
    - db
  ports:
    - "5000:5000"

db:
  image: mysql:5.7
  ports:
    - "32000:3306"
  environment:
    MYSQL_ROOT_PASSWORD: root
  volumes:
    - ./db:/docker-entrypoint-initdb.d/:ro

dockerfile

FROM python:3.6
EXPOSE 5000
RUN mkdir -p /app
RUN ls /app
COPY static /app/static
COPY templates /app/templates
COPY app.py /app
COPY requirements.txt /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD python app.py

requirements.txt

flask
mysql-connector

app.py

from flask import Flask, render_template, request
import mysql.connector
import os

app = Flask(__name__, template_folder='/templates', static_folder='/static')
@app.route('/')
def index():
    connection = mysql.connector.connect(
        user = 'root',
        password = 'root',
        host= 'db',
        port = '3306',
        database = 'test'
    )
    cursor = connection.cursor()
    cursor.execute("SELECT name from place")
    names = cursor.fetchall()
    return render_template('index.html', names = names)
if __name__ == '__main__':
    app.run(host='0.0.0.0')

My docker command is –

docker-compose up

Then trying to access  http://0.0.0.0:5000/ but get mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'db:3306' and  jinja2.exceptions.TemplateNotFound:


问:
Angular CLI - changing where my components get generated
Is there anyway to change the default location of my generated components in angular cli config?

I want to change where my angular CLI defaults its generated components to a specific components folder.  After upgrading to angular 9 I get the following error when trying to generate a component outside of the root folder, which I never used to get:

```<code>Could not find an NgModule. Use the skip-import option to skip importing in NgModule.
</code>```

I can only seem to generate components and services from the root/src folder and nowhere else.

Just upgraded my angular and angular cli.  Currently running:

```<code>@angular-devkit/architect         0.900.2
@angular-devkit/build-angular     0.900.2
@angular-devkit/build-optimizer   0.900.2
@angular-devkit/build-webpack     0.900.2
@angular-devkit/core              9.0.2
@angular-devkit/schematics        9.0.2
@angular/cli                      9.0.2
@ngtools/webpack                  9.0.2
@schematics/angular               9.0.2
@schematics/update                0.900.2
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2
</code>```

答:
Yes like this =>
ng generate component folder/nameComponent</p>

Body:
Is there anyway to change the default location of my generated components in angular cli config?

I want to change where my angular CLI defaults its generated components to a specific components folder.  After upgrading to angular 9 I get the following error when trying to generate a component outside of the root folder, which I never used to get:

Could not find an NgModule. Use the skip-import option to skip importing in NgModule.

I can only seem to generate components and services from the root/src folder and nowhere else.

Just upgraded my angular and angular cli.  Currently running:

@angular-devkit/architect         0.900.2
@angular-devkit/build-angular     0.900.2
@angular-devkit/build-optimizer   0.900.2
@angular-devkit/build-webpack     0.900.2
@angular-devkit/core              9.0.2
@angular-devkit/schematics        9.0.2
@angular/cli                      9.0.2
@ngtools/webpack                  9.0.2
@schematics/angular               9.0.2
@schematics/update                0.900.2
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2


问:
Visual Studio Code Intellisense Mode
What are valid values for the c_cpp_properties.json tag "intelliSenseMode" ?

It defaults to clang-x64, but I am compiling with g++ so is there another value I can use there? I can not find any documentation about it.

答:
Since v0.25, 32 bit modes are supported. The valid options are msvc-x64, gcc-x64, clang-x64 and their 32 bit counterparts msvc-x86, gcc-x86, clang-x86. There's also the ${default} option that Fábio Lobão mentions.

(Source: https://github.com/microsoft/vscode-cpptools/issues/2312)

Title: Visual Studio Code Intellisense Mode


问:
Implicit conversions in row.getAs[Long]
When I try to apply a filter function on a dataframe , I have met a confused problem.

If the fields of a row are null, isNotNull1 will be false, and isNotNull2 will be true. Here is the code:

```<code>      val res = df.filter(row => {
        val isNotNull1 = (row.getAs[Long]("video_id") != null)
        val videoId = row.getAs[Long]("video_id")
        val isNotNull2 = (videoId != null)
        isNotNull2
      })
</code>```

Idea debug result:

I can understand isNotNull2 is true, as the doc of getAs[T](fieldName: String) says For primitive types if value is null it returns 'zero value' specific for primitive.

Are there scala implicit conversions happened here? Thanks for you help.

答:
The underlying issue is that generics don't really work with primitive types. The Scala compiler tries to present the illusion that they do but you've stumbled on a case where it fails.

So row.getAs[Long]("video_id") is "really" row.getAs[java.lang.Long]("video_id") which returns null in your case, so the val isNotNull1 line compares null != null which is false.

In the val videoId line, because its type is Long, it becomes row.getAs[java.lang.Long]("video_id").asInstanceOf[Long]. This is 0, and in the next line you do 0.asInstanceOf[java.lang.Long] != null which is true.

Title: Implicit conversions in row.getAs[Long]

Body:
When I try to apply a filter function on a dataframe , I have met a confused problem.

If the fields of a row are null, isNotNull1 will be false, and isNotNull2 will be true. Here is the code:

      val res = df.filter(row => {
        val isNotNull1 = (row.getAs[Long]("video_id") != null)
        val videoId = row.getAs[Long]("video_id")
        val isNotNull2 = (videoId != null)
        isNotNull2
      })

Idea debug result:

I can understand isNotNull2 is true, as the doc of getAs[T](fieldName: String) says For primitive types if value is null it returns 'zero value' specific for primitive.

Are there scala implicit conversions happened here? Thanks for you help.


问:
Change the output of the Knex rawquery
I am forced to use raw query with the Knex, since there is an issue with the union

One query, is not that bad. But now I have other type of issue.

All other Knex queries (non raw ones), they simply return an array with the results

For example:

```<code>knex('user_subscription_plan')
        .select('*')
        .where('paused_days', '>', 91)
        .where('status', 'N_PAUSED')
</code>```

will return an array, empty of there is no results.

However, if I run raw query, for example:

```<code>mySqlClient.raw('select * from user')
</code>```

it will return an array, with two arrays inside it.
First one is the normal result, while other one contains some catalogue definitions.

That interferes with my logic. At the end of each call to knex, I have:

```<code>if (result.length > 0) {
   // send email
}
</code>```

Now, when I run the raw Query, the result is always greater then zero.
How can I tell Knex not to send the catalogue definitions, in other words, just send results back, exactly like it does on non raw queries?

答:
According to https://github.com/knex/knex/issues/1802 there is no way around it, just do </p>

```<code>mySqlClient.raw('select * from user')[0]
</code>```

Title: Change the output of the Knex rawquery

Body:
I am forced to use raw query with the Knex, since there is an issue with the union

One query, is not that bad. But now I have other type of issue.

All other Knex queries (non raw ones), they simply return an array with the results

For example:

knex('user_subscription_plan')
        .select('*')
        .where('paused_days', '>', 91)
        .where('status', 'N_PAUSED')

will return an array, empty of there is no results.

However, if I run raw query, for example:

mySqlClient.raw('select * from user')

it will return an array, with two arrays inside it.
First one is the normal result, while other one contains some catalogue definitions.

That interferes with my logic. At the end of each call to knex, I have:

if (result.length > 0) {
   // send email
}

Now, when I run the raw Query, the result is always greater then zero.
How can I tell Knex not to send the catalogue definitions, in other words, just send results back, exactly like it does on non raw queries?

Body:
According to https://github.com/knex/knex/issues/1802 there is no way around it, just do

mySqlClient.raw('select * from user')[0]


问:
Stream raw audio data from server to client
I am working on an audio simulator application for the browser. It is supposed to play a WAV file(or any other raw audio binary format) to the user, but the user is capable of changing certain parameters of the signal in real time and hear the change in the already playing audio file.

The algorithm that changes the sound is proprietary and already has a working solution as a desktop app in Java, but I will have to set this up online. I am looking for a solution where most of this would be done server-side and have the client only send the parameters.

My goal is not to open for example '/something.wav' on server and play it, but to extract the audio data (which I already have) and somehow send that raw audio data to the client to play it. Is this possible and if so what is the best way to achieve it?

答:
On the client, the easiest thing to do is a simple HTML5 audio tag:

```<code><audio src="https://your-audio-server/some-id" preload="none" controls></audio>
</code>```

The preload="none" prevents the audio from being buffered early.  (This is live, so you don't want to be buffering data from the past for seconds or minutes until the user hits play!)

Most browsers support WAV file playback.  Therefore, all you need to do is send a WAV stream live.  Your server should take this PCM input, send the appropriate headers, and then start sending PCM data.  The client will buffer this for a couple seconds and then begin playback.

That is, your server will mux to a live WAV stream and stream that output in realtime to the client.  The client doesn't know or care whether it's receiving a file or a live stream.

Body:
On the client, the easiest thing to do is a simple HTML5 audio tag:

<audio src="https://your-audio-server/some-id" preload="none" controls></audio>

The preload="none" prevents the audio from being buffered early.  (This is live, so you don't want to be buffering data from the past for seconds or minutes until the user hits play!)

Most browsers support WAV file playback.  Therefore, all you need to do is send a WAV stream live.  Your server should take this PCM input, send the appropriate headers, and then start sending PCM data.  The client will buffer this for a couple seconds and then begin playback.

That is, your server will mux to a live WAV stream and stream that output in realtime to the client.  The client doesn't know or care whether it's receiving a file or a live stream.


答:
Let me assume you are starting with a table that has the first four columns.

Then you can use window functions.  If I understand the conditions, they boil down to:

flag = -1 when zscore20 < -2.0 or

flag = -1 when zscore20 < 0.0 and there is no non-negative value since the most recent time with a score less than -2.0

And then similar logic for flag = 1.

If I'm understanding this correctly, then you can use window functions and case expressions:

```<code>select t.*,
       (case when zscore20 > 2.0
             then 1
             when zscore20 > 0 and
                  (max(case when zscore20 > 2.0 then date end) over (partition by stock1, stock2 order by date) >
                   max(case when zscore20 < 0 then date end) over (partition by stock1, stock2 order by date)
                  )
             then 1
             when zscore20 < -2.0
             then -1
             when zscore20 < 0 and
                  (max(case when zscore20 < -2.0 then date end) over (partition by stock1, stock2 order by date) >
                   max(case when zscore20 > 0 then date end) over (partition by stock1, stock2 order by date)
                  )
             then 1
             else 0
       end) as flag
from t;
</code>```

Title: Testing Trade Entries in BigQuery/SQL

Body:
I have a data set in BigQuery of various pairs of stock prices, and their relative zscores (ordered by date, and in the millions of rows):

   +-----+--------+--------+------------+---------------+------------------+---------------+
1  | Row | stock1 | stock2 |    date    |  spreadclose  | logspreadreturn  |   zscore20    |
   +-----+--------+--------+------------+---------------+------------------+---------------+
2  | 1   | AJRD   | MAS    | 27/12/2010 |  0.537230704  |  0.017358199     | -0.251654379  |
3  | 2   | ABEV   | EFOI   | 27/12/2010 | 41.00585106   |  0.014929275     |  1.950810153  |
4  | 3   | AIRI   | REFR   | 27/12/2010 |  0.537688889  |  0.003638617     |  0.707555834  |
5  | 4   | AEO    | RJF    | 27/12/2010 |  0.35009565   | -0.004321474     |  0.265411543  |
6  | 5   | AFL    | TSU    | 27/12/2010 |  0.771122788  | -0.028202112     |  0.247268645  |
   +----+---------+--------+------------+---------------+------------------+---------------+

I then take a sample of the stock prices as per below. I am trying to calculate the trade entries as per the "What I want column" in Big query, but can only seem to achieve the numbers as per the "(Current(Wrong))" column.

   Stock1 Stock2     date       zscore20     (Current wrong)   What I want
1    FITB     MS  4/01/2010     -1.5               1           0
2    FITB     MS  5/01/2010     -1.9               1           0
3    FITB     MS  6/01/2010     -2.3               1           1
4    FITB     MS  7/01/2010     -2.0               1           1
5    FITB     MS  8/01/2010     -1.0               1           1
6    FITB     MS 11/01/2010      0.5              -1           0
7    FITB     MS 12/01/2010      1.5              -1           0
8    FITB     MS 13/01/2010      1.8              -1           0
9    FITB     MS 14/01/2010      2.1              -1          -1
10   FITB     MS 15/01/2010      1.5              -1          -1
11   FITB     MS 19/01/2010      1.3              -1          -1
12   FITB     MS 20/01/2010      0.4              -1          -1
13   FITB     MS 21/01/2010     -0.1               1           0

The logic in the "What I want column" is as follows:

In the time series, when zscore > 2.0, flag -1; then exit (0) when zscore next crosses zero into negative

In the time series, when zscore < -2.0, flag +1; then exit (0) when zscore next crosses zero into postitve

My current query that I run on the larger dataset (setting process year to 2010):

DECLARE processyear date;

SET processyear = '2012-01-01';

INSERT INTO `dataset.main.tradetime`(

-- Calculate tradetimeparameters
WITH tradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    LN(spreadclose) - LN(LAG(spreadclose) OVER (PARTITION BY stock1, stock2 ORDER BY date ASC)) as logspreadreturn,
    SAFE_DIVIDE((spreadclose - sma20), stdev20) as zscore20
FROM `rw-algotrader-264713.mlbprices.dailyspreads`
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

secondtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    CASE WHEN zscore20 > 0 THEN -1 WHEN zscore20 < 0 THEN 1 END as tradesignal20
FROM tradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

thirdtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    LEAD(tradesignal20) OVER (PARTITION BY stock1, stock2 ORDER BY date ASC) as tradesignal20
FROM secondtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

fourthtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    CASE WHEN tradesignal20 < 0 THEN 0 ELSE tradesignal20 END as positivesignals,
    CASE WHEN tradesignal20 > 0 THEN 0 ELSE tradesignal20 END as negativesignals
FROM thirdtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

fifthtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
       (case when positivesignals = 0 then 0
             else row_number() over (partition by stock1,stock2, positivesignals, grp order by date ASC)
        end) as positivedaysintrade
from (select stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals, countif(positivesignals = 0) over (partition by stock1,stock2 order by date ASC) as grp
      from fourthtradetimeparameters
     ) fourthtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

sixthtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
    positivedaysintrade,
       (case when negativesignals = 0 then 0
             else row_number() over (partition by stock1,stock2, negativesignals, grp order by date ASC)
        end) as negativedaysintrade
from (select stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
    positivedaysintrade,countif(negativesignals = 0) over (partition by stock1,stock2 order by date ASC) as grp
      from fifthtradetimeparameters
     ) fifthtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

seventhtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
    positivedaysintrade,
    negativedaysintrade,
    (positivedaysintrade + negativedaysintrade) as daysintrade,
    (tradesignal20 * logspreadreturn) as sdcreturn20

FROM sixthtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
)

SELECT
  stock1,
  stock2,
  date,
  spreadclose,
  logspreadreturn,
  zscore20,
  tradesignal20,
  positivesignals,
  negativesignals,
  positivedaysintrade,
  negativedaysintrade,
  daysintrade,
  sdcreturn20
FROM seventhtradetimeparameters)

The second shorter table is as follows:

SELECT * FROM `dataset.tradetime` WHERE stock1 = 'FITB' and stock2 = 'MS' and date >= '2010-01-01'

Will appreciate if someone can guide me on the Bigquery/SQL code that can achieve the above. Many thanks in advance,

Body:
Let me assume you are starting with a table that has the first four columns.

Then you can use window functions.  If I understand the conditions, they boil down to:

flag = -1 when zscore20 < -2.0 or

flag = -1 when zscore20 < 0.0 and there is no non-negative value since the most recent time with a score less than -2.0

And then similar logic for flag = 1.

If I'm understanding this correctly, then you can use window functions and case expressions:

select t.*,
       (case when zscore20 > 2.0
             then 1
             when zscore20 > 0 and
                  (max(case when zscore20 > 2.0 then date end) over (partition by stock1, stock2 order by date) >
                   max(case when zscore20 < 0 then date end) over (partition by stock1, stock2 order by date)
                  )
             then 1
             when zscore20 < -2.0
             then -1
             when zscore20 < 0 and
                  (max(case when zscore20 < -2.0 then date end) over (partition by stock1, stock2 order by date) >
                   max(case when zscore20 > 0 then date end) over (partition by stock1, stock2 order by date)
                  )
             then 1
             else 0
       end) as flag
from t;


问:
C++ expression must have a constant value. (i was writing a code in C in Visual Studio 2019)
I tried to initialize a 2D array in C using integers inputted by the user but Visual Studio 2019 is showing me this error? The code worked fine on Codelite using a gcc compiler.
List of errors</p>

```<code> error C2057: expected constant expression
 error C2466: cannot allocate an array of constant size 0
 error C2057: expected constant expression
 error C2466: cannot allocate an array of constant size 0
 error C2087: 'board': missing subscript
 error C2133: 'board': unknown size
</code>```

答:
MSVC has minimal support for the C99 standard.  A consequence of this is that it does not support variable length arrays (VLA).

You'll need to allocate space dynamically.

```<code>int n=5,m=5;
int i;
int **arr;

arr = malloc(n * sizeof(int *));
for (i=0; i<n; i++) {
    arr[i] = malloc(m * sizeof(int));
}
</code>```

Body:
I tried to initialize a 2D array in C using integers inputted by the user but Visual Studio 2019 is showing me this error? The code worked fine on Codelite using a gcc compiler.
List of errors

 error C2057: expected constant expression
 error C2466: cannot allocate an array of constant size 0
 error C2057: expected constant expression
 error C2466: cannot allocate an array of constant size 0
 error C2087: 'board': missing subscript
 error C2133: 'board': unknown size

Body:
MSVC has minimal support for the C99 standard.  A consequence of this is that it does not support variable length arrays (VLA).

You'll need to allocate space dynamically.

int n=5,m=5;
int i;
int **arr;

arr = malloc(n * sizeof(int *));
for (i=0; i<n; i++) {
    arr[i] = malloc(m * sizeof(int));
}


问:
How to fix SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference in Internet Explorer 11?
my code works fine on other browsers but on Internet Explorer 11 I get SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference. Does anyone know how to fix that bug? Here is my code:

var selected

function dragOver(e) {
  if (isBefore(selected, e.target)) e.target.parentNode.insertBefore(selected, e.target)
  else e.target.parentNode.insertBefore(selected, e.target.nextSibling)
}

function dragEnd() {
  selected = null
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move"
  e.dataTransfer.setData("text/plain", null)
  selected = e.target
}

function isBefore(el1, el2) {
  var cur;
  if (el2.parentNode === el1.parentNode) {
    for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
      if (cur === el2) return true
    }
  } else return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sequence">
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="3">Yellow</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="5">Red</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="2">Green</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="1">Blue</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="4">Orange</div>
</div></code>```

答:
Try something like this in your event handlers:

function dragOver( e ) {
  if (!e) e = window.event;
  if ( isBefore( selected, e.target ) ) e.target.parentNode.insertBefore( selected, e.target )
  else e.target.parentNode.insertBefore( selected, e.target.nextSibling )
}
```

Reference:
https://docstore.mik.ua/orelly/webprog/jscript/ch19_03.htm (19.3.2. The IE Event Object as a Global Variable)

Body:
my code works fine on other browsers but on Internet Explorer 11 I get SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference. Does anyone know how to fix that bug? Here is my code:

var selected

function dragOver(e) {
  if (isBefore(selected, e.target)) e.target.parentNode.insertBefore(selected, e.target)
  else e.target.parentNode.insertBefore(selected, e.target.nextSibling)
}

function dragEnd() {
  selected = null
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move"
  e.dataTransfer.setData("text/plain", null)
  selected = e.target
}

function isBefore(el1, el2) {
  var cur;
  if (el2.parentNode === el1.parentNode) {
    for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
      if (cur === el2) return true
    }
  } else return false;
}

Yellow

Red

Green

Blue

Orange

Body:
Try something like this in your event handlers:

function dragOver( e ) {
  if (!e) e = window.event;
  if ( isBefore( selected, e.target ) ) e.target.parentNode.insertBefore( selected, e.target )
  else e.target.parentNode.insertBefore( selected, e.target.nextSibling )
}

Reference:
https://docstore.mik.ua/orelly/webprog/jscript/ch19_03.htm (19.3.2. The IE Event Object as a Global Variable)


问:
Docker build from Dockerfile shows "ADD failed - No such file or directory"
When I try to build the following (simple) NGINX docker container https://github.com/MarvAmBass/docker-nginx-ssl-secure, it always fails with the following error: stat /var/lib/docker/tmp/docker-builder00Whatever/basic.conf: no such file or directory

My directory looks like this:

```<code>├── basic.conf
├── Dockerfile
├── entrypoint.sh
├── LICENSE
├── README.md
└── ssl.conf
</code>```

Running the command sudo docker build - < Dockerfile as root user doesn't change a thing.
Does anyone have a solution here?

答:
Hells bells all - for further clarification, because I needed it and it took me a bit to figure this out on my own:

With an ADD in the Dockerfile, you need to be in the directory relative to wherever you're adding - not relative to the Dockerfile.

```<code>ADD directory1\directory2\filename.jar app.jar
</code>```

And your file structure is:

```<code>home
|-directory1
  |-directory2
</code>```

You need to be in home when you use:

```<code>docker build . -f filepathToDocker/Dockerfile
</code>```

I imagine this might be true for COPY as well, but I haven't tested it.

Body:
When I try to build the following (simple) NGINX docker container https://github.com/MarvAmBass/docker-nginx-ssl-secure, it always fails with the following error: stat /var/lib/docker/tmp/docker-builder00Whatever/basic.conf: no such file or directory

My directory looks like this:

├── basic.conf
├── Dockerfile
├── entrypoint.sh
├── LICENSE
├── README.md
└── ssl.conf

Running the command sudo docker build - < Dockerfile as root user doesn't change a thing.
Does anyone have a solution here?

Body:
Hells bells all - for further clarification, because I needed it and it took me a bit to figure this out on my own:

With an ADD in the Dockerfile, you need to be in the directory relative to wherever you're adding - not relative to the Dockerfile.

ADD directory1\directory2\filename.jar app.jar

And your file structure is:

home
|-directory1
  |-directory2

You need to be in home when you use:

docker build . -f filepathToDocker/Dockerfile

I imagine this might be true for COPY as well, but I haven't tested it.


问:
Get base64 data of file from Salesforce
I need to get opportunity files from Salesforce and copy them to some folder. I am using .NET library for connecting to Salesforcre. I can get any data I want, except the [VersionData] field in [ContentVersion] table, which contains base64 data of the files I want. I can get the data with Workbench tool, but the only thing I get via .NET library is a link to file. I could create HttpClient with appropriate headers and invoke that URL, but I don't like to go this ways. Can I get the file via .NET library?

答:
In REST API it has to be pulled through that url you got. It'll be a raw binary stream of data which would be tricky to represent together within JSON of normal query results. REST API is focused on mobile apps, minimizing network usage and base64 decode is some processing power I guess.

It shouldn't be tricky though? Just a GET to the URL you got with header Authorization: Bearer <session id here>

If you want base64 you need to make it a SOAP API request (which is what Workbench really uses, note that "REST explorer" is a separate menu option).

POST request to https://<redacted>.my.salesforce.com/services/Soap/u/48.0

with payload like

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com">
   <soapenv:Header>
      <urn:SessionHeader>
         <urn:sessionId>nice try ;) you can reuse same session id</urn:sessionId>
      </urn:SessionHeader>
   </soapenv:Header>
   <soapenv:Body>
      <urn:query>
         <urn:queryString>SELECT VersionData FROM ContentVersion WHERE Id = '068...'</urn:queryString>
      </urn:query>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

Will give you something like this back

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sf="urn:sobject.partner.soap.sforce.com">
   <soapenv:Header>
      <LimitInfoHeader>
         <limitInfo>
            <current>12</current>
            <limit>5000000</limit>
            <type>API REQUESTS</type>
         </limitInfo>
      </LimitInfoHeader>
   </soapenv:Header>
   <soapenv:Body>
      <queryResponse>
         <result xsi:type="QueryResult">
            <done>true</done>
            <queryLocator xsi:nil="true"/>
            <records xsi:type="sf:sObject">
               <sf:type>ContentVersion</sf:type>
               <sf:Id xsi:nil="true"/>
               <sf:VersionData>/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/
(bla bla bla)
/X/lf0eG9Kl61//Z</sf:VersionData>
            </records>
            <size>1</size>
         </result>
      </queryResponse>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

Title: Get base64 data of file from Salesforce

Body:
In REST API it has to be pulled through that url you got. It'll be a raw binary stream of data which would be tricky to represent together within JSON of normal query results. REST API is focused on mobile apps, minimizing network usage and base64 decode is some processing power I guess.

It shouldn't be tricky though? Just a GET to the URL you got with header Authorization: Bearer <session id here>

If you want base64 you need to make it a SOAP API request (which is what Workbench really uses, note that "REST explorer" is a separate menu option).

POST request to https://<redacted>.my.salesforce.com/services/Soap/u/48.0

with payload like

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com">
   <soapenv:Header>
      <urn:SessionHeader>
         <urn:sessionId>nice try ;) you can reuse same session id</urn:sessionId>
      </urn:SessionHeader>
   </soapenv:Header>
   <soapenv:Body>
      <urn:query>
         <urn:queryString>SELECT VersionData FROM ContentVersion WHERE Id = '068...'</urn:queryString>
      </urn:query>
   </soapenv:Body>
</soapenv:Envelope>

Will give you something like this back

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sf="urn:sobject.partner.soap.sforce.com">
   <soapenv:Header>
      <LimitInfoHeader>
         <limitInfo>
            <current>12</current>
            <limit>5000000</limit>
            <type>API REQUESTS</type>
         </limitInfo>
      </LimitInfoHeader>
   </soapenv:Header>
   <soapenv:Body>
      <queryResponse>
         <result xsi:type="QueryResult">
            <done>true</done>
            <queryLocator xsi:nil="true"/>
            <records xsi:type="sf:sObject">
               <sf:type>ContentVersion</sf:type>
               <sf:Id xsi:nil="true"/>
               <sf:VersionData>/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/
(bla bla bla)
/X/lf0eG9Kl61//Z</sf:VersionData>
            </records>
            <size>1</size>
         </result>
      </queryResponse>
   </soapenv:Body>
</soapenv:Envelope>


问:
R: Why am I getting an extra column titled "X.1" in my dataframe after reading my .txt file?
I have got this .txt file outputed by a microscope to process.

```<code>#read the .txt file generated by microscope, skipping the first 9 lines of garbage information
df <- read.csv("Objects_Population - AllCells.txt", sep="\t", skip = 9,header=TRUE, fill = T)
</code>```

Then I started looking at the structure of the dataframe, everything seems fine except I now found an extra column in the end of the data frame named "x.1" and all rows of it are NA values. I don't see this column when I open the .txt file in excel. I suspect the problem has something to do with the column names generated by microscope, they contain quite some special characters

Below is the dataframe read by Excel(only showing the last 2 columns since I have 132 columns, and their names are disgustingly long):

```<code>AllCells - Cell Contact Area with Neighbors [%] AllCells - Nucleus Nearest Neighbor Distance [Âµm]
0                                               4.82083
21.9512                                         0
15.7895                                         0
29.4118                                         0.584611
0                                               4.21569
0                                               1.99599
0                                               3.50767
...
</code>```

This has happened to me before but I never took it too serious as I was always interested in a subset of my data frame. Now I'm looking at all columns then this starts to bothering me.

Is there any way I can read them correctly without R attaching that additional "X.1" column in the end? Preferably not manually delete or subset out the last column...

Cheers,
ML

答:
This is almost certainly because you've got an extra empty column in your spreadsheet.

In Excel, open your sheet and press Ctrl-End. If you end up in an empty cell outside the range of your data, there's the problem. Select the column (Ctrl-Space), right-click, and choose Delete.

Body:
I have got this .txt file outputed by a microscope to process.

#read the .txt file generated by microscope, skipping the first 9 lines of garbage information
df <- read.csv("Objects_Population - AllCells.txt", sep="\t", skip = 9,header=TRUE, fill = T)

Then I started looking at the structure of the dataframe, everything seems fine except I now found an extra column in the end of the data frame named "x.1" and all rows of it are NA values. I don't see this column when I open the .txt file in excel. I suspect the problem has something to do with the column names generated by microscope, they contain quite some special characters

Below is the dataframe read by Excel(only showing the last 2 columns since I have 132 columns, and their names are disgustingly long):

AllCells - Cell Contact Area with Neighbors [%] AllCells - Nucleus Nearest Neighbor Distance [Âµm]
0                                               4.82083
21.9512                                         0
15.7895                                         0
29.4118                                         0.584611
0                                               4.21569
0                                               1.99599
0                                               3.50767
...

This has happened to me before but I never took it too serious as I was always interested in a subset of my data frame. Now I'm looking at all columns then this starts to bothering me.

Is there any way I can read them correctly without R attaching that additional "X.1" column in the end? Preferably not manually delete or subset out the last column...

Cheers,
ML


问:
Laravel database relationships not working
What am I doing wrong here?

My entradas table:

Schema::create('entradas', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('categoria_id');
            $table->string('descricao', 200);
            $table->double('valor');
            $table->timestamps();
        });
```

<p>My <code>categorias</code> table:</p>

<pre class="lang-php prettyprint-override"><code>Schema::create('categorias', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('titulo', 100);
            $table->enum('tipo', ['debito', 'credito']);
            $table->timestamps();
        });
</code>```

My Entrada model:

public function categoria()
    {
        return $this->belongsTo('App\Categoria');
    }
```

<p>My <code>Categoria</code> model:</p>

<pre class="lang-php prettyprint-override"><code>public function entradas()
    {
        return $this->hasMany('App\Entrada');
    }
</code>```

Returning this on my EntradaController:

public function index() {
        return(Entrada::find(1));
    }
```

<p>I get the following result:</p>

```{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quia ea voluptatem pariatur et. Tenetur maiores mollitia molestias asperiores. Exercitationem maiores voluptas id dolore rerum unde. Ipsum dolorem facere aut ut quos.",
    "valor": 108,
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}
```

Why don't I get the categoria property?

答:
Try updating your foreign key column definition like so:

```<code>Schema::create('entradas', function (Blueprint $table) {
    // ...
    $table->bigInteger('categoria_id')->unsigned();
    //                                ^^^^^^^^^^^^^
    // You could also do:
    // $table->unsignedBigInteger('categoria_id');
    // ...
});
</code>```

Also, to access the relationship you need to load it. So as an answer to this

Why don't I get the categoria property?

You could make use of Eager Loading:

```<code>public function index()
{
    return Entrada::with('categoria')->find(1);
}  //               ^^^^^^^^^^^^^^^^
</code>```

This should give you the expected json:

```<code>{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quos.",
    "valor": 108,
    "categoria": {
        // ...
    },
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}
</code>```

Body:
What am I doing wrong here?

My entradas table:

Schema::create('entradas', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('categoria_id');
            $table->string('descricao', 200);
            $table->double('valor');
            $table->timestamps();
        });

My categorias table:

Schema::create('categorias', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('titulo', 100);
            $table->enum('tipo', ['debito', 'credito']);
            $table->timestamps();
        });

My Entrada model:

public function categoria()
    {
        return $this->belongsTo('App\Categoria');
    }

My Categoria model:

public function entradas()
    {
        return $this->hasMany('App\Entrada');
    }

Returning this on my EntradaController:

public function index() {
        return(Entrada::find(1));
    }

I get the following result:

{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quia ea voluptatem pariatur et. Tenetur maiores mollitia molestias asperiores. Exercitationem maiores voluptas id dolore rerum unde. Ipsum dolorem facere aut ut quos.",
    "valor": 108,
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}

Why don't I get the categoria property?

Body:
Try updating your foreign key column definition like so:

Schema::create('entradas', function (Blueprint $table) {
    // ...
    $table->bigInteger('categoria_id')->unsigned();
    //                                ^^^^^^^^^^^^^
    // You could also do:
    // $table->unsignedBigInteger('categoria_id');
    // ...
});

Also, to access the relationship you need to load it. So as an answer to this

Why don't I get the categoria property?

You could make use of Eager Loading:

public function index()
{
    return Entrada::with('categoria')->find(1);
}  //               ^^^^^^^^^^^^^^^^

This should give you the expected json:

{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quos.",
    "valor": 108,
    "categoria": {
        // ...
    },
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}


问:
cannot connect to database with sqlserver?
I have ampp3.9-PHP7.3 and SQLserver-2014 12.0.2269.0. I am not able to connect the database. I getting the following error

Fatal error: Uncaught Error: Call to undefined function
  sqlsrv_connect() in E:\Ampps\Ampps\www\backend scripts\database.php:4
  Stack trace: #0 {main} thrown in E:\Ampps\Ampps\www\backend
  scripts\database.php on line 4

Here is my code

```<code><?php
$serverName = "DESKTOP-VDSPQT9"; //serverName\instanceName
$connectionInfo = array( "Database"=>"railway", "UID"=>"sa", "PWD"=>"bhanu123");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>
</code>```

答:
I believe that you should install the driver.

https://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=20098

Body:
I have ampp3.9-PHP7.3 and SQLserver-2014 12.0.2269.0. I am not able to connect the database. I getting the following error

Fatal error: Uncaught Error: Call to undefined function
  sqlsrv_connect() in E:\Ampps\Ampps\www\backend scripts\database.php:4
  Stack trace: #0 {main} thrown in E:\Ampps\Ampps\www\backend
  scripts\database.php on line 4

Here is my code

<?php
$serverName = "DESKTOP-VDSPQT9"; //serverName\instanceName
$connectionInfo = array( "Database"=>"railway", "UID"=>"sa", "PWD"=>"bhanu123");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.
";
}else{
     echo "Connection could not be established.
";
     die( print_r( sqlsrv_errors(), true));
}
?>


问:
How can I use a specific version of a Haskell package with Nix?
I just want to be able to use the latest version of pandoc, the Haskell package, in my project which I'm building with Nix.

Here's my shell.nix file. The commented-out section is where I attempt to override the package version, but it doesn't seem to work.

```<code>with import <nixpkgs> {};

( let
    colormath = pkgs.python3Packages.buildPythonPackage rec {
      pname = "colormath";
      version = "3.0.0";

      src = pkgs.python3Packages.fetchPypi{
        inherit version;
        inherit pname;
        sha256 = "05qjycgxp3p2f9n6lmic68sxmsyvgnnlyl4z9w7dl9s56jphaiix";
      };

      buildInputs = [ pkgs.python3Packages.numpy pkgs.python3Packages.networkx ];
    };
    spacy_conll = pkgs.python3Packages.buildPythonPackage rec {
      pname = "spacy_conll";
      version = "1.0.1";

      src = pkgs.python3Packages.fetchPypi{
        inherit version;
        inherit pname;
        sha256 = "1wffwp539i3yvqx6dl3ki5fmmbrpqpnf0ymg5806czk0rh7843j7";
      };

      buildInputs = [ pkgs.python3Packages.spacy pkgs.python3Packages.packaging ];
    };
    # pandoc = pkgs.haskellPackages.pandoc.override {
    #   version = "2.9.1.1";
    #   };

  in pkgs.mkShell {
    shellHook = "eval $(egrep ^export ${ghc}/bin/ghc)";
    buildInputs = with pkgs; [
        (python3.withPackages (ps: with ps; [
          matplotlib
          spacy
          pandas
          spacy_models.en_core_web_md
          jupyter
          scikitlearn
          nltk
          altair
          vega_datasets
          cherrypy
          dominate
          plotly
          colormath
          falcon # Spacy server from Haskell Cookbook
          spacy_conll
          ]))
        (haskellPackages.ghcWithPackages (ps: with ps; [ lens pandoc roman-numerals doclayout ] ))
        ];
      }
  )
</code>```

答:
Pandoc 2.9.1.1 is available in nixpkgs as haskellPackages.pandoc_2_9_1_1. I'd advise you to use this instead of trying to override the package as there are some differences in dependencies. For reference though, here's how you would go about overriding haskellPackages:

```<code>let
  hsPkgs = pkgs.haskellPackages.override {
    overrides = self: super: {
      pandoc = pkgs.haskell.lib.overrideCabal super.pandoc {
        version = "2.9.1.1";
        sha256 = "0vc1ld57nv27gwq4mq0wdal8k2wxvsc0f3m2jwq9nkq7wbpwa8cx";
      };
    };
  };
in pkgs.mkShell {
  buildInputs = with pkgs; [
    (hsPkgs.ghcWithPackages (ps: with ps; [ pandoc ] ))
  ];
}
</code>```

Body:
I just want to be able to use the latest version of pandoc, the Haskell package, in my project which I'm building with Nix.

Here's my shell.nix file. The commented-out section is where I attempt to override the package version, but it doesn't seem to work.

with import <nixpkgs> {};

( let
    colormath = pkgs.python3Packages.buildPythonPackage rec {
      pname = "colormath";
      version = "3.0.0";

      src = pkgs.python3Packages.fetchPypi{
        inherit version;
        inherit pname;
        sha256 = "05qjycgxp3p2f9n6lmic68sxmsyvgnnlyl4z9w7dl9s56jphaiix";
      };

      buildInputs = [ pkgs.python3Packages.numpy pkgs.python3Packages.networkx ];
    };
    spacy_conll = pkgs.python3Packages.buildPythonPackage rec {
      pname = "spacy_conll";
      version = "1.0.1";

      src = pkgs.python3Packages.fetchPypi{
        inherit version;
        inherit pname;
        sha256 = "1wffwp539i3yvqx6dl3ki5fmmbrpqpnf0ymg5806czk0rh7843j7";
      };

      buildInputs = [ pkgs.python3Packages.spacy pkgs.python3Packages.packaging ];
    };
    # pandoc = pkgs.haskellPackages.pandoc.override {
    #   version = "2.9.1.1";
    #   };

  in pkgs.mkShell {
    shellHook = "eval $(egrep ^export ${ghc}/bin/ghc)";
    buildInputs = with pkgs; [
        (python3.withPackages (ps: with ps; [
          matplotlib
          spacy
          pandas
          spacy_models.en_core_web_md
          jupyter
          scikitlearn
          nltk
          altair
          vega_datasets
          cherrypy
          dominate
          plotly
          colormath
          falcon # Spacy server from Haskell Cookbook
          spacy_conll
          ]))
        (haskellPackages.ghcWithPackages (ps: with ps; [ lens pandoc roman-numerals doclayout ] ))
        ];
      }
  )

Body:
Pandoc 2.9.1.1 is available in nixpkgs as haskellPackages.pandoc_2_9_1_1. I'd advise you to use this instead of trying to override the package as there are some differences in dependencies. For reference though, here's how you would go about overriding haskellPackages:

let
  hsPkgs = pkgs.haskellPackages.override {
    overrides = self: super: {
      pandoc = pkgs.haskell.lib.overrideCabal super.pandoc {
        version = "2.9.1.1";
        sha256 = "0vc1ld57nv27gwq4mq0wdal8k2wxvsc0f3m2jwq9nkq7wbpwa8cx";
      };
    };
  };
in pkgs.mkShell {
  buildInputs = with pkgs; [
    (hsPkgs.ghcWithPackages (ps: with ps; [ pandoc ] ))
  ];
}


问:
nginx serve a specific directory for a specific location
I need for development purpose (not for production of course), to serve my logs that are in my folder /app/logs/.

So I've setup a configuration like this :

```<code>    server {
        listen 80;
        server_name server-name.com;
        error_log  /app/logs/error.log warn;
        access_log /app/logs/access.log compression;
        root /var/www;

        location /info/logs/ {
            alias /app/logs/;
            autoindex on;
        }

        location / {
          // others route working
        }
    }
</code>```

But everytimes i try to access to something like /app/logs/django.log using http://server-name.com/info/logs/django.log, I get a 404 and not the file I asked for.

I've tried many things like chmod -R 755 the entire folder or setting the folder to the user nginx use (in my case for now root, I know it's bad), tried root or try_files but I just can't access it...

I've seen many topics here and there but can't find a clue...

Can you help me with this please ?

PS : I need the root /var/www at the beginning for others locations.

PS2 : I'm using a Docker based on Debian 9.

答:
Ok, I've found my problem, I had a route like this :

```<code># Any route containing a file extension (e.g. /devicesfile.js)
location ~ ^.+\..+$ {
    try_files $uri =404;
}
</code>```

And I didn't know that despite the fact it was after the first location, it would be choosen over the other location...

Thanks for your help anyway !

Body:
I need for development purpose (not for production of course), to serve my logs that are in my folder /app/logs/.

So I've setup a configuration like this :

    server {
        listen 80;
        server_name server-name.com;
        error_log  /app/logs/error.log warn;
        access_log /app/logs/access.log compression;
        root /var/www;

        location /info/logs/ {
            alias /app/logs/;
            autoindex on;
        }

        location / {
          // others route working
        }
    }

But everytimes i try to access to something like /app/logs/django.log using http://server-name.com/info/logs/django.log, I get a 404 and not the file I asked for.

I've tried many things like chmod -R 755 the entire folder or setting the folder to the user nginx use (in my case for now root, I know it's bad), tried root or try_files but I just can't access it...

I've seen many topics here and there but can't find a clue...

Can you help me with this please ?

PS : I need the root /var/www at the beginning for others locations.

PS2 : I'm using a Docker based on Debian 9.

Body:
Ok, I've found my problem, I had a route like this :

# Any route containing a file extension (e.g. /devicesfile.js)
location ~ ^.+\..+$ {
    try_files $uri =404;
}

And I didn't know that despite the fact it was after the first location, it would be choosen over the other location...

Thanks for your help anyway !


问:
Groovydoc produces blank documents
I'm writing a class in Groovy, and I want to generate Groovydoc for it (from the command line). In my class, I've written documentation for the methods like this:

```<code>/**
 * Returns blah blah blah
*/
def getFoo(){
    ...
}
</code>```

But when I run groovydoc -classpath C:\groovyStuff\ -d . *.groovy

It generates the HTML template, but no actual content.

What have I done wrong?

答:
If you application consists of Java & Groovy files you can leverage next bash script which lists all java & groovy files in the source directory (even skipping undesired ones)</p>

```<code>source_files=`find {path-to-your-dir}/ -type f \( \
    \( \
    -name "*.java" \
    -or -name "*.groovy" \
    \) \
    ! \
    \( \
     -name "UndesiredOne.java" \
     -or -name "UndesiredTwo.groovy" \
    \) \
    \)`

groovydoc -verbose --debug -public\
 -d {path-to-your-doc-dir}\
 -doctitle "Title"\
 -header "Header"\
 -footer "Footer"\
 -windowtitle "WindowTitle"\
 $source_files
</code>```

Title: Groovydoc produces blank documents

Body:
I'm writing a class in Groovy, and I want to generate Groovydoc for it (from the command line). In my class, I've written documentation for the methods like this:

/**
 * Returns blah blah blah
*/
def getFoo(){
    ...
}

But when I run groovydoc -classpath C:\groovyStuff\ -d . *.groovy

It generates the HTML template, but no actual content.

What have I done wrong?

Body:
If you application consists of Java & Groovy files you can leverage next bash script which lists all java & groovy files in the source directory (even skipping undesired ones)

source_files=`find {path-to-your-dir}/ -type f \( \
    \( \
    -name "*.java" \
    -or -name "*.groovy" \
    \) \
    ! \
    \( \
     -name "UndesiredOne.java" \
     -or -name "UndesiredTwo.groovy" \
    \) \
    \)`

groovydoc -verbose --debug -public\
 -d {path-to-your-doc-dir}\
 -doctitle "Title"\
 -header "Header"\
 -footer "Footer"\
 -windowtitle "WindowTitle"\
 $source_files


问:
When route was not implemented on server, should it return 404 or 501?
I always returned 404 when some route has not been implemented and no resource exists. For example, if I have a API that returns people at /api/people, if I try to get a object on /api/animals, I'm going to return 404.

A cowork of mine said 404 is only for not found resources, like if I try to get /api/people/100 but there's no people with ID 100. For the /api/animals he would return 501.

For me, the meaning for 501 is when I have a route that won't support one of the methods, like if I can get /api/people/3 but can't delete it.

I decided to look at the specification:

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.  A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.

The 501 (Not Implemented) status code indicates that the server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.

For me it seems the specification is a little ambiguous. At the same time it's arguable that /api/animals has not been found by the origin server (404), it's also true that the origin server did not implement the method to fullfill the request (501).

In this case, what is the most proper status code to return?

答:
If you went into a bookshop and asked the person behind the counter to get "The best 100 cakes" from the shelf and the book wasn't in stock, they would return and politely say "I'm sorry I can't find that book". Automate that in a book finding system and it would return 404.

The manager of the bookshop wouldn't appear, instead of the person looking for your book and tell you "I'm afraid we don't support looking for that particular book as our staff can only look for books we have" (501).

If you went into a bookshop and asked the person behind the counter to get you a lawnmower they would politely reply "I'm sorry I don't know how to do that". That would be a 501. If you asked the person in the bookshop to get rid of a book that you'd just seen on the shelf, that would be a 501 too.

A 404 is, "ok, I know how to get that but it isn't there". A 501 is a "WTF! What do you think this place is?".

Whether the 404 is permanent depends on what is answering the question. If it's a REST API, it could return JSON status saying something like the book is out of stock but is on order, with a likely due date.

The real reason it's a 501 when trying to get the book person to chuck out a book they have on a shelf is, if they just said 404, you'd just say, "there it is there!". They'd need to state the real reason they couldn't do that. They have no business policy that allows them to chuck out random books without buying them.

So, technically, the apparatus is there, they can walk up to the book, grab it but stop with a 501 as the policy hasn't been implemented.

"ok, I know how to turn a REST url into functionality, that's how I know what functionality you want, but hey, we only deal with people here, 501".


问:
How do you reference and dereference a cstring array in a function for C?
```<code>char *wordList[15];
</code>```

This is the char point array, my question is if I were to put in a function like this:

```<code>decodeMessage(input, wordList);
</code>```

how would I dereference it in the function so changes could be made to it?

答:
You would access it as you would any array.

char* wordList[15]; // ... initialization

char* firstItem = wordList[0];
char* secondItem = wordList[1];
// ... so on
```

Body:
char *wordList[15];

This is the char point array, my question is if I were to put in a function like this:

decodeMessage(input, wordList);

how would I dereference it in the function so changes could be made to it?


问:
Short question about CUDA memory access
hey there,
assuming I have a problem where each thread calculates something (reading some parameters out of the constant memory and using them for calculation) and than stores it to a global memory matrix. this matrix gets never read, just writing access... is there now any sense of using shared memory first to store all the calculated values in and than later write them to the global memory? I think no because the writes to global memory stay the same in complete, so the writes to shared memory just add to the writes which I had before already....
Thanks!</p>

答:
There can be, depending on the access patterns in the kernel code. Using a shared memory buffer to "stage" output can be a useful way of ensure writes are coalesced, when the naive write would not be coalesced. This was pretty crucial for performance in the first couple of generations of CUDA compatible hardware (G80/G90). In newer hardware, the case for this is a lot less strong. Fermi cards have a pretty effective L1 and L2 cache scheme which can (within reason) get close to what used to be only achievable using shared memory without any extra code.

There isn't really a general answer to this question, because it depends a lot of the specifics of what any given code does, and what target hardware it is expected to run well on.

Title: Short question about CUDA memory access


问:
How to deploy a C# (ClickOnce?) project that is a wrapper on a command line .exe
I have a C# project which is basically a GUI used to call other executable(s) with command line arguments. (The command line exe was actually built with cygwin and uses the cugwin DLL).

So the directory structure that needs to exist once the app is deployed (via setup.exe or whatever) is this:

```<code>install dir --->   MyApp.exe
                   MyApp.config
                   (dir) bin   ---> cmd1.exe
                                    cmd2.exe
                                    cygwin.dll
</code>```

Now this ought to be simple, but whatever I try, I cannot get the bin directory and its contents to be copied when I install on a second machine with setup.exe. I tried:
  - adding them as resources
  - setting "Build Action" to Content
  - setting "Copy To Output Directory" to Always

But the bin directory was never copied across when I did this. I have tried searching here and elsewhere but I am still at a loss.

Should this be a "ClickOnce" project? (what does this even mean - are there also ClickTwice and ClickUntilYouCanClickNoMore projects - ok, excuse me ...)

Also do I get setup.exe to put this app somewhere sane like C://Program Files/MyOrg/Myapp  - instead of being buried somewhere in the user's profile?

(Using VS 2019.)

答:
Since I cannot add an image in a comment, I am adding them here.  Here is how my folder structure looks like.

I have a .p12 file and have marked it as "Copy to Output Directory" to "Copy always"

When the project is built, the file gets copied inside bin folder with the file's folder structure which includes "keystore" folder as well.

As a curiosity, I just tried out renaming my folder "keystore" to "bin" (I had to delete existing bin folder), and then added the .p12 file to it.  The project compiled, generated new exe file and also copied .p12 file with appropriate folder structure.  I am not sure what means to building and generating a Setup.exe though. You can try and let us know if it worked for you.

Body:
I have a C# project which is basically a GUI used to call other executable(s) with command line arguments. (The command line exe was actually built with cygwin and uses the cugwin DLL).

So the directory structure that needs to exist once the app is deployed (via setup.exe or whatever) is this:

install dir --->   MyApp.exe
                   MyApp.config
                   (dir) bin   ---> cmd1.exe
                                    cmd2.exe
                                    cygwin.dll

Now this ought to be simple, but whatever I try, I cannot get the bin directory and its contents to be copied when I install on a second machine with setup.exe. I tried:
  - adding them as resources
  - setting "Build Action" to Content
  - setting "Copy To Output Directory" to Always

But the bin directory was never copied across when I did this. I have tried searching here and elsewhere but I am still at a loss.

Should this be a "ClickOnce" project? (what does this even mean - are there also ClickTwice and ClickUntilYouCanClickNoMore projects - ok, excuse me ...)

Also do I get setup.exe to put this app somewhere sane like C://Program Files/MyOrg/Myapp  - instead of being buried somewhere in the user's profile?

(Using VS 2019.)