问:
including font face for bold not working
I've added the 'circular' font family to my site shown in the first code snippet below, but it doesn't add any bold,  so I tried to include the bold .ttf and .woff for the bold 'circular' font but neither of my two approaches worked, the first approach made all the text bold and the second approach didn't do anything at all!

Here is how I added 'circular' to my asp.net mvc site's site.css file and it makes all the text circular, but not the bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}```
</div>
</div>
</p>

<p>Here I tried adding the bold but it makes everything bold</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}</code>```

The last thing I tried was adding a new 'font-face' and including it in the body like this but it doesn't change any of my 'font-weight: bold' css to bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

@font-face {
    font-family: 'Circular-bold';
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular, Circular-bold,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}```

答:
```<code>@font-face {
   font-family: 'Circular';
   src: url('../fonts/circular-book.ttf') format('truetype');
   src: url('../fonts/circular-book.woff') format('woff');
}
@font-face {
   font-family: 'Circular'; /*same name, yes*/
   font-weight: bold; /*config its weight*/
   src: url('../fonts/circular-bold.ttf') format('truetype');
   src: url('../fonts/circular-bold.woff') format('woff');
}

body {
  font-family: Circular; /*select font family normally*/
  font-weight: bold; /*select family's bold font face*/
}
</code>```

Or ask engine to generate (ugly) bold font face for us by font-synthesis:weight.

Here is an example showing how googlefonts configs font face.

```<code>@font-face {
  font-family: 'Spectral SC';
  font-style: normal;
  font-weight: 400;
  src: local('Spectral SC Regular'), local('SpectralSC-Regular'), url(https://fonts.gstatic.com/s/spectralsc/v2/yJ95fCBFs0v33GTJdYTk_zUj_cnvWIuuBMVgbX098Mw.woff2) format('woff2');
  unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}

@font-face {
  font-family: 'Spectral SC';
  font-style: normal;
  font-weight: 700;
  src: local('Spectral SC Bold'), local('SpectralSC-Bold'), url(https://fonts.gstatic.com/s/spectralsc/v2/J7mO0YbtyrIkp56FY15FDS_vZmeiCMnoWNN9rHBYaTc.woff2) format('woff2');
  unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
</code>```

Body:
I've added the 'circular' font family to my site shown in the first code snippet below, but it doesn't add any bold,  so I tried to include the bold .ttf and .woff for the bold 'circular' font but neither of my two approaches worked, the first approach made all the text bold and the second approach didn't do anything at all!

Here is how I added 'circular' to my asp.net mvc site's site.css file and it makes all the text circular, but not the bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}

Here I tried adding the bold but it makes everything bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}

The last thing I tried was adding a new 'font-face' and including it in the body like this but it doesn't change any of my 'font-weight: bold' css to bold

@font-face {
    font-family: 'Circular';
    src: url('../fonts/circular-book.ttf') format('truetype');
    src: url('../fonts/circular-book.woff') format('woff');

}

@font-face {
    font-family: 'Circular-bold';
    src: url('../fonts/circular-bold.ttf') format('truetype');
    src: url('../fonts/circular-bold.woff') format('woff');

}

body {
    font-family: Circular, Circular-bold,"Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 16px !important;
    -webkit-font-smoothing: antialiased !important;
    color: #484848 !important;
}

Body:
@font-face {
   font-family: 'Circular';
   src: url('../fonts/circular-book.ttf') format('truetype');
   src: url('../fonts/circular-book.woff') format('woff');
}
@font-face {
   font-family: 'Circular'; /*same name, yes*/
   font-weight: bold; /*config its weight*/
   src: url('../fonts/circular-bold.ttf') format('truetype');
   src: url('../fonts/circular-bold.woff') format('woff');
}

body {
  font-family: Circular; /*select font family normally*/
  font-weight: bold; /*select family's bold font face*/
}

Or ask engine to generate (ugly) bold font face for us by font-synthesis:weight.

Here is an example showing how googlefonts configs font face.

@font-face {
  font-family: 'Spectral SC';
  font-style: normal;
  font-weight: 400;
  src: local('Spectral SC Regular'), local('SpectralSC-Regular'), url(https://fonts.gstatic.com/s/spectralsc/v2/yJ95fCBFs0v33GTJdYTk_zUj_cnvWIuuBMVgbX098Mw.woff2) format('woff2');
  unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}

@font-face {
  font-family: 'Spectral SC';
  font-style: normal;
  font-weight: 700;
  src: local('Spectral SC Bold'), local('SpectralSC-Bold'), url(https://fonts.gstatic.com/s/spectralsc/v2/J7mO0YbtyrIkp56FY15FDS_vZmeiCMnoWNN9rHBYaTc.woff2) format('woff2');
  unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}


来源: stackexchange

问:
How renew ssl certificate on Tomcat?
Following the go-daddy documentation :

https://www.godaddy.com/help/tomcat-4x5x6x-renew-a-certificate-5355

The flow:

I've create myDomain.csr and send it to GoDaddy , got reply from them with 3 files ( gd_bundle-g2-g1.crt , gdig2.crt.pem ,59a41eaec32d2046.crt)

I mentioned that the old cert which was expired has a chain structure  , unfortunately Go-daddy give me  only "flat" certificates.

I tried to make a chain by myself :

```<code>cat 59a41eaec32d2046.crt gd_bundle-g2-g1.crt gdig2.crt.pem >> myDomain.crt
</code>```

after that :

```<code>sudo keytool -import -alias tomcat -keystore tomcat.keystore -trustcacerts -file myDomain.crt
sudo keytool -import -alias intermed -keystore tomcat.keystore -trustcacerts -file gdig2.crt
sudo keytool -import -alias root -keystore tomcat.keystore -trustcacerts -file gd_bundle-g2-g1.crt
</code>```

and change the server.xml exactly as in the documentation

I Attach pictures of how in my opinion it should appear

But Actually after my chain I had :

When I open the Browser GOT:

```<code>Secure Connection Failed

An error occurred during a connection to talenttribe.me. Cannot communicate securely with peer: no common encryption algorithm(s). Error code: SSL_ERROR_NO_CYPHER_OVERLAP

    The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
    Please contact the website owners to inform them of this problem.

Learn more…

Report errors like this to help Mozilla identify and block malicious sites
</code>```

Don't understand what I'm missing...is it Chain creation or tomcat issues ??

BR,

答:
The issue is that the tomcat.keystore is not being created with chaining intact.  To correct that, you will need to isolate the root and intermediate certificates in separate files, and then import them in a specific order.  To create a working example, here are some simplifying assumptions:

The 59a41eaec32d2046.crt file contains only the SSL certificate issued by Go Daddy, presumably for an internet facing web server.

The "gd_bundle-g2-g1.crt" file is a concatenation of the Go Daddy intermediate and root certificates.

The "gdig2.crt.pem" file contains a redundant copy of the Go Daddy root certificate.

There is only one intermediate certificate, and it is also the Issuer of your SSL certificate.

The crt files are the base 64 encoded, or "pem", format.

The tomcat.keystore file uses JKS format.

Here are the steps to create the tomcat.keystore, given the assumptions above:

List the contents of gd_bundle-g2-g1.crt:

sudo keytool -printcert -file gd_bundle-g2-g1.crt

The output will include delimiters for each certificate in the bundle.   The delimiter for the first certificate will be "Certificate[1]:", and the delimiter of the second certificate will be "Certificate[2]:".   Immediately following "Certificate[1]:", you will see the Owner and Issuer records for the first certificate.    Likewise, following "Certificate[2]:", you will see the Owner and Issuer records for the second certificate.   Also note:

The root certificate is unique in that the Owner is the same as the Issuer (in other words, it is self-signed).

The root certificate is also the Issuer of the intermediate certificate.

List the contents of gd_bundle-g2-g1.crt in "rfc" format:

sudo keytool -printcert -file gd_bundle-g2-g1.crt -rfc

Again, note the delimiters "Certificate[1]:" and "Certificate[2]:" are used with the same meaning as above.  But in rfc format, the certificates are listed using base 64 "pem" format starting  with "-----BEGIN CERTIFICATE-----" and ending with "-----END CERTIFICATE-----".  That is format that will be needed in the separate root and intermediate certificate files.

Redirect the output of step 2 to a temporary file.   Then use a text editor to save the Go Daddy root certificate in a separate file named gd_root.crt.

Be certain to include the entirety of the text beginning with "-----BEGIN CERTIFICATE-----" and ending with "-----END CERTIFICATE-----".

Likewise, save the Go Daddy intermediate certificate in a separate file named gd_intermediate.crt.

Use the "keytool -importcert" command to create the keystore incrementally:

sudo keytool -importcert -noprompt -file gd_intermediate.crt  -alias intermed -keystore tomcat.keystore -storepass '!q@wDDfll'

sudo keytool -importcert -noprompt -file gd_root.crt          -alias root     -keystore tomcat.keystore -storepass '!q@wDDfll'

sudo keytool -importcert -noprompt -file 59a41eaec32d2046.crt -alias tomcat   -keystore tomcat.keystore -storepass '!q@wDDfll'

The order of the commands above is important.  You need to create the keystore first using the intermediate certificate used by the CA to issue (sign) your SSL certificate.   (If there are additional intermediate certificates, those would be added next, until the final intermediate certificate, which is signed by the root certificate, is added.)  Next, you add the root certificate.  And finally, you add the SSL certificate issued by the CA for your application.

This will fix the issue with the tomcat.keystore file.   You might also consider building a custom trust store file, which requires the truststoreFile and truststorePass options within the connector element, as an alternative to relying on Java's cacerts trust store.  The commands to do that are similar to the fist 2 commands above, substituting the trust store file name along with the trust store password.

ContentLicense: CC BY-SA 3.0

Title: How renew ssl certificate on Tomcat?

Body:
Following the go-daddy documentation :

https://www.godaddy.com/help/tomcat-4x5x6x-renew-a-certificate-5355

The flow:

I've create myDomain.csr and send it to GoDaddy , got reply from them with 3 files ( gd_bundle-g2-g1.crt , gdig2.crt.pem ,59a41eaec32d2046.crt)

I mentioned that the old cert which was expired has a chain structure  , unfortunately Go-daddy give me  only "flat" certificates.

I tried to make a chain by myself :

cat 59a41eaec32d2046.crt gd_bundle-g2-g1.crt gdig2.crt.pem >> myDomain.crt

after that :

sudo keytool -import -alias tomcat -keystore tomcat.keystore -trustcacerts -file myDomain.crt
sudo keytool -import -alias intermed -keystore tomcat.keystore -trustcacerts -file gdig2.crt
sudo keytool -import -alias root -keystore tomcat.keystore -trustcacerts -file gd_bundle-g2-g1.crt

and change the server.xml exactly as in the documentation

I Attach pictures of how in my opinion it should appear

But Actually after my chain I had :

When I open the Browser GOT:

Secure Connection Failed

An error occurred during a connection to talenttribe.me. Cannot communicate securely with peer: no common encryption algorithm(s). Error code: SSL_ERROR_NO_CYPHER_OVERLAP

    The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
    Please contact the website owners to inform them of this problem.

Learn more…

Report errors like this to help Mozilla identify and block malicious sites

Don't understand what I'm missing...is it Chain creation or tomcat issues ??

BR,


问:
Designing programs to compile on both 32bit and 64bit in D
I have an open source project that I want to run/compile on both 32 bit and 64 bit architectures. But here comes the problem: it uses dynamic arrays a lot, and needs to mess with their length too. Dynamic arrays have length stored in type size_t, which is ulong on 64bit, and uint on 32 bit systems.

I have code that looks something like this:

```<code>int i = 0;//this HAS to be int, not uint for some reasons
i = dynArray.length;//error, can't implicitly cast ulong to uint
</code>```

I need i to int (on 32bit) and long on (64bit). size_t would have solved the problem, but it is unsigned (either uint or ulong).

So my question here is that: how do I create a integer data type that is int on 32 bit and long on 64 bit? Will it be something like this?:

```<code>32bit{
   //Declaration for 32 bit version
}else{
   //Declaration for 64 bit version
}
</code>```

答: As discussed in comments, there's already a signed pointer-width integer type.  It's called ptrdiff_t in D (and C and C++).  Don't define your own.

Body:
I have an open source project that I want to run/compile on both 32 bit and 64 bit architectures. But here comes the problem: it uses dynamic arrays a lot, and needs to mess with their length too. Dynamic arrays have length stored in type size_t, which is ulong on 64bit, and uint on 32 bit systems.

I have code that looks something like this:

int i = 0;//this HAS to be int, not uint for some reasons
i = dynArray.length;//error, can't implicitly cast ulong to uint

I need i to int (on 32bit) and long on (64bit). size_t would have solved the problem, but it is unsigned (either uint or ulong).

So my question here is that: how do I create a integer data type that is int on 32 bit and long on 64 bit? Will it be something like this?:

32bit{
   //Declaration for 32 bit version
}else{
   //Declaration for 64 bit version
}


问:
I need to use a variable to iterate through inserting into recordsets, but don't know how to do it
I am trying to iterate through inserting values into fields in a table.  I have tried using the code below (code like it, I generalized below), but it give me a Runtime error# 3265: "Item not found in this collection."  Any ideas how to accomplish this?</p>

```<code>Private Sub ImportRWPData_Click()
    Dim db As Database
    Dim rs As Recordset
    Dim rs2 As DAO.Recordset
    Dim File As Field
    Dim Location As String
    Set db = CurrentDb()
    Set rs = db.OpenRecordset("rwpT")
    Set rs2 = db.OpenRecordset("AIP&BOP")
    Set File = rs.Fields("File")
    Dim xls As Excel.Application
    Dim wkb As Excel.Workbook
    Dim wks As Excel.Worksheet
    Set xls = New Excel.Application

   'Declare variables for column values in RWP spreadsheets
    Dim orgSheetCol(7) As String
    orgSheetCol(0) = "$A$" 'Auto Isolation Point
    orgSheetCol(1) = "$D$" 'Customer Minutes Lost
    orgSheetCol(2) = "$H$" '% work plan fix
    orgSheetCol(3) = "$E$" 'Customers in Incident Sustained
    orgSheetCol(4) = "$C3$" 'Plan Title
    orgSheetCol(5) = "$B33$" 'Years of Data
    orgSheetCol(6) = "$B37$" 'Annual Improved CML
    'Declare variables for cell values attained from RWP spreadsheets
    Dim RWPSheetvalues(100) As String
    RWPSheetvalues(0) = "" 'Autoisolation Point 1
    RWPSheetvalues(1) = "" 'CML for Point 1
    RWPSheetvalues(2) = "" '% Work Plan Fix
    RWPSheetvalues(3) = "" 'CI For Point 1
    RWPSheetvalues(4) = "" 'Autoisolation Point 2
    RWPSheetvalues(5) = "" 'CML for Point 2
    RWPSheetvalues(6) = "" '% Work Plan Fix
    RWPSheetvalues(7) = "" 'CI For Point 2
    RWPSheetvalues(8) = "" 'Autoisolation Point 3
    RWPSheetvalues(9) = "" 'CML for Point 3
    RWPSheetvalues(10) = "" '% Work Plan Fix
    RWPSheetvalues(11) = "" 'CI For Point 3
    RWPSheetvalues(12) = "" 'Autoisolation Point 4
    RWPSheetvalues(13) = "" 'CML for Point 4
    RWPSheetvalues(14) = "" '% Work Plan Fix
    RWPSheetvalues(15) = "" 'CI For Point 4
    RWPSheetvalues(16) = "" 'Autoisolation Point 5
    RWPSheetvalues(17) = "" 'CML for Point 5
    RWPSheetvalues(18) = "" '% Work Plan Fix
    RWPSheetvalues(19) = "" 'CI For Point 5
    RWPSheetvalues(20) = "" 'Autoisolation Point 6
    RWPSheetvalues(21) = "" 'CML for Point 6
    RWPSheetvalues(22) = "" '% Work Plan Fix
    RWPSheetvalues(23) = "" 'CI For Point 6
    RWPSheetvalues(24) = "" 'Autoisolation Point 7
    RWPSheetvalues(25) = "" 'CML for Point 7
    RWPSheetvalues(26) = "" '% Work Plan Fix
    RWPSheetvalues(27) = "" 'CI For Point 7
    RWPSheetvalues(28) = "" 'Autoisolation Point 8
    RWPSheetvalues(29) = "" 'CML for Point 8
    RWPSheetvalues(30) = "" '% Work Plan Fix
    RWPSheetvalues(31) = "" 'CI For Point 8
    RWPSheetvalues(32) = "" 'Autoisolation Point 9
    RWPSheetvalues(33) = "" 'CML for Point 9
    RWPSheetvalues(34) = "" '% Work Plan Fix
    RWPSheetvalues(35) = "" 'CI For Point 9
    RWPSheetvalues(36) = "" 'Autoisolation Point 10
    RWPSheetvalues(37) = "" 'CML for Point 10
    RWPSheetvalues(38) = "" '% Work Plan Fix
    RWPSheetvalues(39) = "" 'CI For Point 10
    RWPSheetvalues(40) = "" 'Autoisolation Point 11
    RWPSheetvalues(41) = "" 'CML for Point 11
    RWPSheetvalues(42) = "" '% Work Plan Fix
    RWPSheetvalues(43) = "" 'CI For Point 11
    RWPSheetvalues(44) = "" 'Autoisolation Point 12
    RWPSheetvalues(45) = "" 'CML for Point 12
    RWPSheetvalues(46) = "" '% Work Plan Fix
    RWPSheetvalues(47) = "" 'CI For Point 12
    RWPSheetvalues(48) = "" 'Autoisolation Point 13
    RWPSheetvalues(49) = "" 'CML for Point 13
    RWPSheetvalues(50) = "" '% Work Plan Fix
    RWPSheetvalues(51) = "" 'CI For Point 13
    RWPSheetvalues(52) = "" 'Autoisolation Point 14
    RWPSheetvalues(53) = "" 'CML for Point 14
    RWPSheetvalues(54) = "" '% Work Plan Fix
    RWPSheetvalues(55) = "" 'CI For Point 14
    RWPSheetvalues(56) = "" 'Autoisolation Point 15
    RWPSheetvalues(57) = "" 'CML for Point 15
    RWPSheetvalues(58) = "" '% Work Plan Fix
    RWPSheetvalues(59) = "" 'CI For Point 15
    RWPSheetvalues(60) = "" 'Autoisolation Point 16
    RWPSheetvalues(61) = "" 'CML for Point 16
    RWPSheetvalues(62) = "" '% Work Plan Fix
    RWPSheetvalues(63) = "" 'CI For Point 16
    RWPSheetvalues(64) = "" 'Autoisolation Point 17
    RWPSheetvalues(65) = "" 'CML for Point 17
    RWPSheetvalues(66) = "" '% Work Plan Fix
    RWPSheetvalues(67) = "" 'CI For Point 17
    RWPSheetvalues(68) = "" 'Autoisolation Point 18
    RWPSheetvalues(69) = "" 'CML for Point 18
    RWPSheetvalues(70) = "" '% Work Plan Fix
    RWPSheetvalues(71) = "" 'CI For Point 18
    RWPSheetvalues(72) = "" 'Autoisolation Point 19
    RWPSheetvalues(73) = "" 'CML for Point 19
    RWPSheetvalues(74) = "" '% Work Plan Fix
    RWPSheetvalues(75) = "" 'CI For Point 19
    RWPSheetvalues(76) = "" 'Autoisolation Point 20
    RWPSheetvalues(77) = "" 'CML for Point 20
    RWPSheetvalues(78) = "" '% Work Plan Fix
    RWPSheetvalues(79) = "" 'CI For Point 20
    RWPSheetvalues(80) = "" 'Autoisolation Point 21
    RWPSheetvalues(81) = "" 'CML for Point 21
    RWPSheetvalues(82) = "" '% Work Plan Fix
    RWPSheetvalues(83) = "" 'CI For Point 21
    RWPSheetvalues(84) = "" 'Autoisolation Point 22
    RWPSheetvalues(85) = "" 'CML for Point 22
    RWPSheetvalues(86) = "" '% Work Plan Fix
    RWPSheetvalues(87) = "" 'CI For Point 22
    RWPSheetvalues(88) = "" 'Autoisolation Point 23
    RWPSheetvalues(89) = "" 'CML for Point 23
    RWPSheetvalues(90) = "" '% Work Plan Fix
    RWPSheetvalues(91) = "" 'CI For Point 23
    RWPSheetvalues(92) = "" 'Autoisolation Point 24
    RWPSheetvalues(93) = "" 'CML for Point 24
    RWPSheetvalues(94) = "" '% Work Plan Fix
    RWPSheetvalues(95) = "" 'CI For Point 25
    RWPSheetvalues(96) = "" 'Plan Title
    RWPSheetvalues(97) = "" 'File Location
    RWPSheetvalues(98) = "" 'Years of Data
    RWPSheetvalues(99) = "" 'Annual Improved CML
    Dim cellstring As String
    Dim rowstring As String
    Dim rownumber As Integer
    Dim i As Integer
    Dim ii As Integer
    rowstring = CStr(rownumber)
    Dim Mycheck As String
    Dim x As String
    Set wkb = xls.Workbooks.Open(Location, ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Benefit of Plan")
    ii = 0
    For rownumber = 7 To 30
        rowstring = CStr(rownumber)
            For i = 0 To 3
            cellstring = orgSheetCol(i) & rowstring
            RWPSheetvalues(ii) = wks.Range(cellstring).Value
            Mycheck = VarType(RWPSheetvalues(ii))
            ii = ii + 1
            Dim x As String
            Next i
        Next rownumber
    RWPSheetvalues(96) = wks.Range("C3").Value
    RWPSheetvalues(97) = File
    RWPSheetvalues(98) = wks.Range("B33").Value
    RWPSheetvalues(99) = wks.Range("B37").Value
    tablecheck = DCount("PlanTitle", "AIP&BOP", "PlanTitle = '" & RWPSheetvalues(71) & "'") 'check AIP & BOP table to see if plan is already there
    If tablecheck = 0 Then
        rs2.AddNew
        rs2!PlanTitle.Value = RWPSheetvalues(96)
        rs2!FileLocation.Value = RWPSheetvalues(97)
        rs2!YearsofData.Value = CInt(RWPSheetvalues(98))
        rs2!AnnualImprovedCML.Value = CLng(RWPSheetvalues(99))
            For i = 0 To 95
                If RWPSheetvalues(i) <> "" Then
                    x = "AIP" & i + 1 'It Errors on this line
                    rs2!x.Value = RWPSheetvalues(0)
                End If
            Next i
    End If
    wkb.Close False 'Close workbook.  False is so that it doesn't save
    'rs.MoveNext
    'Wend
    rs.Close

End Sub
</code>```

答:
```<code>rs2!x.Value = RWPSheetvalues(0)
</code>```

tries to assign a value to the literal column x, hence the error.

You need to use the variable like this, if x contains the column name:

```<code>rs2(x).Value = RWPSheetvalues(0)
</code>```

Body:
I am trying to iterate through inserting values into fields in a table.  I have tried using the code below (code like it, I generalized below), but it give me a Runtime error# 3265: "Item not found in this collection."  Any ideas how to accomplish this?

Private Sub ImportRWPData_Click()
    Dim db As Database
    Dim rs As Recordset
    Dim rs2 As DAO.Recordset
    Dim File As Field
    Dim Location As String
    Set db = CurrentDb()
    Set rs = db.OpenRecordset("rwpT")
    Set rs2 = db.OpenRecordset("AIP&BOP")
    Set File = rs.Fields("File")
    Dim xls As Excel.Application
    Dim wkb As Excel.Workbook
    Dim wks As Excel.Worksheet
    Set xls = New Excel.Application

   'Declare variables for column values in RWP spreadsheets
    Dim orgSheetCol(7) As String
    orgSheetCol(0) = "$A$" 'Auto Isolation Point
    orgSheetCol(1) = "$D$" 'Customer Minutes Lost
    orgSheetCol(2) = "$H$" '% work plan fix
    orgSheetCol(3) = "$E$" 'Customers in Incident Sustained
    orgSheetCol(4) = "$C3$" 'Plan Title
    orgSheetCol(5) = "$B33$" 'Years of Data
    orgSheetCol(6) = "$B37$" 'Annual Improved CML
    'Declare variables for cell values attained from RWP spreadsheets
    Dim RWPSheetvalues(100) As String
    RWPSheetvalues(0) = "" 'Autoisolation Point 1
    RWPSheetvalues(1) = "" 'CML for Point 1
    RWPSheetvalues(2) = "" '% Work Plan Fix
    RWPSheetvalues(3) = "" 'CI For Point 1
    RWPSheetvalues(4) = "" 'Autoisolation Point 2
    RWPSheetvalues(5) = "" 'CML for Point 2
    RWPSheetvalues(6) = "" '% Work Plan Fix
    RWPSheetvalues(7) = "" 'CI For Point 2
    RWPSheetvalues(8) = "" 'Autoisolation Point 3
    RWPSheetvalues(9) = "" 'CML for Point 3
    RWPSheetvalues(10) = "" '% Work Plan Fix
    RWPSheetvalues(11) = "" 'CI For Point 3
    RWPSheetvalues(12) = "" 'Autoisolation Point 4
    RWPSheetvalues(13) = "" 'CML for Point 4
    RWPSheetvalues(14) = "" '% Work Plan Fix
    RWPSheetvalues(15) = "" 'CI For Point 4
    RWPSheetvalues(16) = "" 'Autoisolation Point 5
    RWPSheetvalues(17) = "" 'CML for Point 5
    RWPSheetvalues(18) = "" '% Work Plan Fix
    RWPSheetvalues(19) = "" 'CI For Point 5
    RWPSheetvalues(20) = "" 'Autoisolation Point 6
    RWPSheetvalues(21) = "" 'CML for Point 6
    RWPSheetvalues(22) = "" '% Work Plan Fix
    RWPSheetvalues(23) = "" 'CI For Point 6
    RWPSheetvalues(24) = "" 'Autoisolation Point 7
    RWPSheetvalues(25) = "" 'CML for Point 7
    RWPSheetvalues(26) = "" '% Work Plan Fix
    RWPSheetvalues(27) = "" 'CI For Point 7
    RWPSheetvalues(28) = "" 'Autoisolation Point 8
    RWPSheetvalues(29) = "" 'CML for Point 8
    RWPSheetvalues(30) = "" '% Work Plan Fix
    RWPSheetvalues(31) = "" 'CI For Point 8
    RWPSheetvalues(32) = "" 'Autoisolation Point 9
    RWPSheetvalues(33) = "" 'CML for Point 9
    RWPSheetvalues(34) = "" '% Work Plan Fix
    RWPSheetvalues(35) = "" 'CI For Point 9
    RWPSheetvalues(36) = "" 'Autoisolation Point 10
    RWPSheetvalues(37) = "" 'CML for Point 10
    RWPSheetvalues(38) = "" '% Work Plan Fix
    RWPSheetvalues(39) = "" 'CI For Point 10
    RWPSheetvalues(40) = "" 'Autoisolation Point 11
    RWPSheetvalues(41) = "" 'CML for Point 11
    RWPSheetvalues(42) = "" '% Work Plan Fix
    RWPSheetvalues(43) = "" 'CI For Point 11
    RWPSheetvalues(44) = "" 'Autoisolation Point 12
    RWPSheetvalues(45) = "" 'CML for Point 12
    RWPSheetvalues(46) = "" '% Work Plan Fix
    RWPSheetvalues(47) = "" 'CI For Point 12
    RWPSheetvalues(48) = "" 'Autoisolation Point 13
    RWPSheetvalues(49) = "" 'CML for Point 13
    RWPSheetvalues(50) = "" '% Work Plan Fix
    RWPSheetvalues(51) = "" 'CI For Point 13
    RWPSheetvalues(52) = "" 'Autoisolation Point 14
    RWPSheetvalues(53) = "" 'CML for Point 14
    RWPSheetvalues(54) = "" '% Work Plan Fix
    RWPSheetvalues(55) = "" 'CI For Point 14
    RWPSheetvalues(56) = "" 'Autoisolation Point 15
    RWPSheetvalues(57) = "" 'CML for Point 15
    RWPSheetvalues(58) = "" '% Work Plan Fix
    RWPSheetvalues(59) = "" 'CI For Point 15
    RWPSheetvalues(60) = "" 'Autoisolation Point 16
    RWPSheetvalues(61) = "" 'CML for Point 16
    RWPSheetvalues(62) = "" '% Work Plan Fix
    RWPSheetvalues(63) = "" 'CI For Point 16
    RWPSheetvalues(64) = "" 'Autoisolation Point 17
    RWPSheetvalues(65) = "" 'CML for Point 17
    RWPSheetvalues(66) = "" '% Work Plan Fix
    RWPSheetvalues(67) = "" 'CI For Point 17
    RWPSheetvalues(68) = "" 'Autoisolation Point 18
    RWPSheetvalues(69) = "" 'CML for Point 18
    RWPSheetvalues(70) = "" '% Work Plan Fix
    RWPSheetvalues(71) = "" 'CI For Point 18
    RWPSheetvalues(72) = "" 'Autoisolation Point 19
    RWPSheetvalues(73) = "" 'CML for Point 19
    RWPSheetvalues(74) = "" '% Work Plan Fix
    RWPSheetvalues(75) = "" 'CI For Point 19
    RWPSheetvalues(76) = "" 'Autoisolation Point 20
    RWPSheetvalues(77) = "" 'CML for Point 20
    RWPSheetvalues(78) = "" '% Work Plan Fix
    RWPSheetvalues(79) = "" 'CI For Point 20
    RWPSheetvalues(80) = "" 'Autoisolation Point 21
    RWPSheetvalues(81) = "" 'CML for Point 21
    RWPSheetvalues(82) = "" '% Work Plan Fix
    RWPSheetvalues(83) = "" 'CI For Point 21
    RWPSheetvalues(84) = "" 'Autoisolation Point 22
    RWPSheetvalues(85) = "" 'CML for Point 22
    RWPSheetvalues(86) = "" '% Work Plan Fix
    RWPSheetvalues(87) = "" 'CI For Point 22
    RWPSheetvalues(88) = "" 'Autoisolation Point 23
    RWPSheetvalues(89) = "" 'CML for Point 23
    RWPSheetvalues(90) = "" '% Work Plan Fix
    RWPSheetvalues(91) = "" 'CI For Point 23
    RWPSheetvalues(92) = "" 'Autoisolation Point 24
    RWPSheetvalues(93) = "" 'CML for Point 24
    RWPSheetvalues(94) = "" '% Work Plan Fix
    RWPSheetvalues(95) = "" 'CI For Point 25
    RWPSheetvalues(96) = "" 'Plan Title
    RWPSheetvalues(97) = "" 'File Location
    RWPSheetvalues(98) = "" 'Years of Data
    RWPSheetvalues(99) = "" 'Annual Improved CML
    Dim cellstring As String
    Dim rowstring As String
    Dim rownumber As Integer
    Dim i As Integer
    Dim ii As Integer
    rowstring = CStr(rownumber)
    Dim Mycheck As String
    Dim x As String
    Set wkb = xls.Workbooks.Open(Location, ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Benefit of Plan")
    ii = 0
    For rownumber = 7 To 30
        rowstring = CStr(rownumber)
            For i = 0 To 3
            cellstring = orgSheetCol(i) & rowstring
            RWPSheetvalues(ii) = wks.Range(cellstring).Value
            Mycheck = VarType(RWPSheetvalues(ii))
            ii = ii + 1
            Dim x As String
            Next i
        Next rownumber
    RWPSheetvalues(96) = wks.Range("C3").Value
    RWPSheetvalues(97) = File
    RWPSheetvalues(98) = wks.Range("B33").Value
    RWPSheetvalues(99) = wks.Range("B37").Value
    tablecheck = DCount("PlanTitle", "AIP&BOP", "PlanTitle = '" & RWPSheetvalues(71) & "'") 'check AIP & BOP table to see if plan is already there
    If tablecheck = 0 Then
        rs2.AddNew
        rs2!PlanTitle.Value = RWPSheetvalues(96)
        rs2!FileLocation.Value = RWPSheetvalues(97)
        rs2!YearsofData.Value = CInt(RWPSheetvalues(98))
        rs2!AnnualImprovedCML.Value = CLng(RWPSheetvalues(99))
            For i = 0 To 95
                If RWPSheetvalues(i) <> "" Then
                    x = "AIP" & i + 1 'It Errors on this line
                    rs2!x.Value = RWPSheetvalues(0)
                End If
            Next i
    End If
    wkb.Close False 'Close workbook.  False is so that it doesn't save
    'rs.MoveNext
    'Wend
    rs.Close

End Sub

Body:
rs2!x.Value = RWPSheetvalues(0)

tries to assign a value to the literal column x, hence the error.

You need to use the variable like this, if x contains the column name:

rs2(x).Value = RWPSheetvalues(0)


问:
How to a put a textarea next to an image and have it fill up rest of the space?
I'm trying to make nice comment box. I want to show an image before the textarea in one line/row. The image size should be fixed. The textarea should fill up the rest of the space. The website has dynamic width, so fixing the textarea width doesn't work for me.

But the text area will not go next to the image, but it will go under it.

```<code><img src="http://i2.wp.com/c0589922.cdn.cloudfiles.rackspacecloud.com/avatars/male200.png" style="float:left;"/>
<textarea style="float: left; height: 200px; margin-left: 210px; width:100%"></textarea>
</code>```

See this fiddle.

Any ideas on how to achieve this? Check out the comment box at cnn.com to see what I'm talking about.

答:
Best way I found to do it without using the position: absolute is the following:

img {
    width: 100px;
    height: 100px;
    float: left;
}
.wrap {
  display: block;
  padding-left: 100px;
}
textarea {
    display: block;
    height: 100px;
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://i2.wp.com/c0589922.cdn.cloudfiles.rackspacecloud.com/avatars/male200.png"/>
<div class="wrap">
  <textarea></textarea>
</div></code>```

Body:
I'm trying to make nice comment box. I want to show an image before the textarea in one line/row. The image size should be fixed. The textarea should fill up the rest of the space. The website has dynamic width, so fixing the textarea width doesn't work for me.

But the text area will not go next to the image, but it will go under it.

<textarea style="float: left; height: 200px; margin-left: 210px; width:100%"></textarea>

See this fiddle.

Any ideas on how to achieve this? Check out the comment box at cnn.com to see what I'm talking about.

Body:
Best way I found to do it without using the position: absolute is the following:

img {
    width: 100px;
    height: 100px;
    float: left;
}
.wrap {
  display: block;
  padding-left: 100px;
}
textarea {
    display: block;
    height: 100px;
    width: 100%;
}

<img src="http://i2.wp.com/c0589922.cdn.cloudfiles.rackspacecloud.com/avatars/male200.png"/>
<div class="wrap">
  <textarea></textarea>
</div>


问:
scrapy pipeline process_item not working (yet another not working)
item not working question . but i have tried my very best on doing research, still i have to raise a questions. i have simplified the code as below.

to make it short, i want to get the details of some products from a web site, i have to use splash to make myself able to read some css. I have registered an item and two db classes, my plan was to store products in product table and their image paths in another .

However, at the end the images were downloaded but the item pipeline has not been triggered.

in my pipeline, i can only obtain two prints, -->

pipeline inited:

end init

Though i can get the picture but i cannot get my message

print( "pipeline" + image_url)

most importantly

```<code>pipeline.py
=============
from sqlalchemy.orm import sessionmaker
from scrapy.exceptions import DropItem
from itembot.database.models import Products, db_connect, create_products_table
from scrapy.pipelines.images import ImagesPipeline

class ImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        for image_url in item["image_urls"]:
             print("pipeline" + image_url)
        yield scrapy.Request(image_url)

    def item_completed(self, results, item, info):
        image_paths = [x["path"] for ok, x in results if ok]
        print("imagepath" + image_paths)
        if not image_paths:
            raise DropItem("Item contains no images")
        item["image_paths"] = image_paths
        return item

class ItembotPipeline(object):

    def __init__(self):

        print("pipeline inited: " )
        engine = db_connect()
        create_products_table(engine)
        self.Session = sessionmaker(bind=engine)
        print("end init")

    def process_item(self, item, spider):
        print("pipeline Entered : ",item )

        print("pipeline Entered : item is products ",item )
        products = Products(**item)
        try:
            session = self.Session()
            print("pipeline adding : ",item )
            session.add(products)
            session.commit()
            print("pipeline commited : ",item )
            session.refresh(products)
            item[id] = products[id]
            yield item[id]
        except:
            session.rollback()
            raise
        finally:
        session.close()
        if(products[id] is not None):
        print("pipeline 2if: ",item )
        productsphotos = ProductsPhotos(**item)
        try:
        session = self.Session()
        session.add(productsphotos)
        session.commit()
        session.refresh(productsphotos)
        except:
        session.rollback()
        raise
        finally:
        session.close()
        return item
</code>```

and most most importantly, the spider

```<code>    import scrapy
    from scrapy.loader import ItemLoader
    from scrapy import Request
    from w3lib.html import remove_tags
    import re
    from ..database.models import Products
    from itembot.items import ItembotItem
    from scrapy_splash import SplashRequest

    class FreeitemSpider(scrapy.Spider):
                name = "freeitem"

        start_urls = [
        "https://google.com.hk" ,
        ]
        def parse(self, response):
        yield SplashRequest(url=response.url, callback=self.parse_product, args={"wait": 0.5})

        def parse_product(self, response):
        products = response.css(" div.classified-body.listitem.classified-summary")

        c = 0
        item = []
        for product in products:
            item = ItembotItem()
            imageurl = {}
            fullurls=[]
            item["title"]= product.css("h4.R a::text").extract_first()

            pc = product.css("div#gallery"+str(c) + " ul a::attr(href)").extract()
            for link in pc:
                 fullurls.append(response.urljoin(link))
            item["image_urls"]= fullurls
            url = product.css("a.button-tiny-short.R::attr(href)").extract_first()
            item["webURL"]= response.urljoin(url)
            c = c+1

            yield [item]
</code>```

here is my item.py

```<code>import scrapy
class ItembotItem(scrapy.Item):
    id = scrapy.Field(default"null")
    title = scrapy.Field(default="null")
    details = scrapy.Field(default="null")
    webURL = scrapy.Field(default="null")
    images = scrapy.Field(default="null")
    image_urls = scrapy.Field(default="null")

class ProductsPhotos(DeclarativeBase):
__tablename__ = "products_photos"
    id = Column(Integer, primary_key=True)
    product_ID = Column(ForeignKey(Products.id),nullable=False)
    photo_path = Column(String(200))

    parent = relationship(Products, load_on_pending=True)
</code>```

settings.py

```<code>ITEM_PIPELINES = {
"itembot.pipelines.ItembotPipeline": 300,
"scrapy.pipelines.images.ImagesPipeline": 1,
}
IMAGES_STORE = "./photo"
</code>```

model.py

```<code>class Products(DeclarativeBase):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
title = Column(String(300))

webURL = Column(String(200))
def __str__(self):
return self.title

class ProductsPhotos(DeclarativeBase):
__tablename__ = "products_photos"
id = Column(Integer, primary_key=True)
product_ID = Column(ForeignKey(Products.id),nullable=False)
photo_path = Column(String(200))

parent = relationship(Products, load_on_pending=True)
</code>```

答:
I see one big mistake which can explain your problem.

First

```<code>class ImagesPipeline(ImagesPipeline)
</code>```

Don't use the same name for own class as for parent class

Better do

```<code>class MyImagesPipeline(ImagesPipeline)
</code>```

And now your main mistake

```<code>ITEM_PIPELINES = {
   ...
   "scrapy.pipelines.images.ImagesPipeline": 1,
}
</code>```

You use standard ImagesPipeline from scrapy.pipelines.images,

not your ImagesPipeline (MyImagesPipeline) from itembot.pipelines

So it downloads images but it doesn't run print("pipeline" + image_url)

It should be

```<code>ITEM_PIPELINES = {
    ...
    "itembot.pipelines.ImagesPipeline": 1,
}
</code>```

or if you use name MyImagesPipeline

```<code>ITEM_PIPELINES = {
    ...
    "itembot.pipelines.MyImagesPipeline": 1,
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
item not working question . but i have tried my very best on doing research, still i have to raise a questions. i have simplified the code as below.

to make it short, i want to get the details of some products from a web site, i have to use splash to make myself able to read some css. I have registered an item and two db classes, my plan was to store products in product table and their image paths in another .

However, at the end the images were downloaded but the item pipeline has not been triggered.

in my pipeline, i can only obtain two prints, -->

pipeline inited:

end init

Though i can get the picture but i cannot get my message

print( "pipeline" + image_url)

most importantly

pipeline.py
=============
from sqlalchemy.orm import sessionmaker
from scrapy.exceptions import DropItem
from itembot.database.models import Products, db_connect, create_products_table
from scrapy.pipelines.images import ImagesPipeline

class ImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        for image_url in item["image_urls"]:
             print("pipeline" + image_url)
        yield scrapy.Request(image_url)

    def item_completed(self, results, item, info):
        image_paths = [x["path"] for ok, x in results if ok]
        print("imagepath" + image_paths)
        if not image_paths:
            raise DropItem("Item contains no images")
        item["image_paths"] = image_paths
        return item

class ItembotPipeline(object):

    def __init__(self):

        print("pipeline inited: " )
        engine = db_connect()
        create_products_table(engine)
        self.Session = sessionmaker(bind=engine)
        print("end init")

    def process_item(self, item, spider):
        print("pipeline Entered : ",item )

        print("pipeline Entered : item is products ",item )
        products = Products(**item)
        try:
            session = self.Session()
            print("pipeline adding : ",item )
            session.add(products)
            session.commit()
            print("pipeline commited : ",item )
            session.refresh(products)
            item[id] = products[id]
            yield item[id]
        except:
            session.rollback()
            raise
        finally:
        session.close()
        if(products[id] is not None):
        print("pipeline 2if: ",item )
        productsphotos = ProductsPhotos(**item)
        try:
        session = self.Session()
        session.add(productsphotos)
        session.commit()
        session.refresh(productsphotos)
        except:
        session.rollback()
        raise
        finally:
        session.close()
        return item

and most most importantly, the spider

    import scrapy
    from scrapy.loader import ItemLoader
    from scrapy import Request
    from w3lib.html import remove_tags
    import re
    from ..database.models import Products
    from itembot.items import ItembotItem
    from scrapy_splash import SplashRequest

    class FreeitemSpider(scrapy.Spider):
                name = "freeitem"

        start_urls = [
        "https://google.com.hk" ,
        ]
        def parse(self, response):
        yield SplashRequest(url=response.url, callback=self.parse_product, args={"wait": 0.5})

        def parse_product(self, response):
        products = response.css(" div.classified-body.listitem.classified-summary")

        c = 0
        item = []
        for product in products:
            item = ItembotItem()
            imageurl = {}
            fullurls=[]
            item["title"]= product.css("h4.R a::text").extract_first()

            pc = product.css("div#gallery"+str(c) + " ul a::attr(href)").extract()
            for link in pc:
                 fullurls.append(response.urljoin(link))
            item["image_urls"]= fullurls
            url = product.css("a.button-tiny-short.R::attr(href)").extract_first()
            item["webURL"]= response.urljoin(url)
            c = c+1

            yield [item]

here is my item.py

import scrapy
class ItembotItem(scrapy.Item):
    id = scrapy.Field(default"null")
    title = scrapy.Field(default="null")
    details = scrapy.Field(default="null")
    webURL = scrapy.Field(default="null")
    images = scrapy.Field(default="null")
    image_urls = scrapy.Field(default="null")

class ProductsPhotos(DeclarativeBase):
__tablename__ = "products_photos"
    id = Column(Integer, primary_key=True)
    product_ID = Column(ForeignKey(Products.id),nullable=False)
    photo_path = Column(String(200))

    parent = relationship(Products, load_on_pending=True)

settings.py

ITEM_PIPELINES = {
"itembot.pipelines.ItembotPipeline": 300,
"scrapy.pipelines.images.ImagesPipeline": 1,
}
IMAGES_STORE = "./photo"

model.py

class Products(DeclarativeBase):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
title = Column(String(300))

webURL = Column(String(200))
def __str__(self):
return self.title

class ProductsPhotos(DeclarativeBase):
__tablename__ = "products_photos"
id = Column(Integer, primary_key=True)
product_ID = Column(ForeignKey(Products.id),nullable=False)
photo_path = Column(String(200))

parent = relationship(Products, load_on_pending=True)

Body:
I see one big mistake which can explain your problem.

First

class ImagesPipeline(ImagesPipeline)

Don't use the same name for own class as for parent class

Better do

class MyImagesPipeline(ImagesPipeline)

And now your main mistake

ITEM_PIPELINES = {
   ...
   "scrapy.pipelines.images.ImagesPipeline": 1,
}

You use standard ImagesPipeline from scrapy.pipelines.images,

not your ImagesPipeline (MyImagesPipeline) from itembot.pipelines

So it downloads images but it doesn't run print("pipeline" + image_url)

It should be

ITEM_PIPELINES = {
    ...
    "itembot.pipelines.ImagesPipeline": 1,
}

or if you use name MyImagesPipeline

ITEM_PIPELINES = {
    ...
    "itembot.pipelines.MyImagesPipeline": 1,
}


问:
Extract and load DLL from JAR
My Java application uses a DLL library. How can I get it work from the JAR file?

The DLL is in the project's sources folder. I have to include it in my JAR, extract it at runtime (in the same directory of the jar) and load it.

答:
You need to put dll in your library path (recommended ) before you try to load it. so that you will have to extract it from jar and copy it into lib path .

```<code>private void loadLib(String path, String name) {
  name = System.mapLibraryName(name); // extends name with .dll, .so or .dylib
  InputStream inputStream = null;
  OutputStream outputStream = null;
  try {
    inputStream = getClass().getResourceAsStream("/" + path + name);
    File fileOut = new File("your lib path");
    outputStream = new FileOutputStream(fileOut);
    IOUtils.copy(inputStream, outputStream);

    System.load(fileOut.toString());//loading goes here
  } catch (Exception e) {
    //handle
  } finally {
    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        //log
      }
    }
    if (outputStream != null) {
      try {
        outputStream.close();
      } catch (IOException e) {
        //log
      }
    }
  }
</code>```

}

Note:  ACWrapper is the class holding the static method

Title: Extract and load DLL from JAR

Body:
You need to put dll in your library path (recommended ) before you try to load it. so that you will have to extract it from jar and copy it into lib path .

private void loadLib(String path, String name) {
  name = System.mapLibraryName(name); // extends name with .dll, .so or .dylib
  InputStream inputStream = null;
  OutputStream outputStream = null;
  try {
    inputStream = getClass().getResourceAsStream("/" + path + name);
    File fileOut = new File("your lib path");
    outputStream = new FileOutputStream(fileOut);
    IOUtils.copy(inputStream, outputStream);

    System.load(fileOut.toString());//loading goes here
  } catch (Exception e) {
    //handle
  } finally {
    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        //log
      }
    }
    if (outputStream != null) {
      try {
        outputStream.close();
      } catch (IOException e) {
        //log
      }
    }
  }

}

Note:  ACWrapper is the class holding the static method


问:
Created a stored procedure in SQL Server Management Studio
I am still quite new to this but am ready to take the next step. I am trying to execute multiple queries at once, if at all possible. From reading some other questions, it seems as if creating a stored procedure is the best route.

The task at hand is creating 36 reports. In this case, hoping to create all 36 reports at one time and not have the results be one continuous entity. Each uses a query very similar to the code shown below. The query shown below is simply the first report to be created out of 36. The only difference in the 36 is the values in the WHERE statement. I am hoping for an operation or method that keeps me from copying and pasting 36 chunks of code into SQL and then copying and pasting those results into an excel spreadsheet.

So my question is 1. Can this be done? 2. Is a stored procedure the best method for this task?

```<code>SELECT
    '000000' AS area,
    [SizeClass],
    COUNT(*) AS [Number of Worksites],
    SUM(Employment) AS [Employment In Size Class]
FROM
    dbo.sizeclassreport
WHERE
    code LIKE '11%' OR code LIKE '21%'
GROUP BY
    [SizeClass]
ORDER BY
    [SizeClass]
</code>```

答:
It gets tricky if the 36 reports you are talking about pass a different number of arguments and also if they have wildcards AND also if the WHERE clause involves different columns. I would probably write a sproc with the max. number of parameters a report could pass like this for a max of three:

```<code>CREATE PROCEDURE dbo.sp_Test
    @code1 varchar(80),
    @code2 varchar(80),
    @code3 varchar(80)
AS
BEGIN
    IF(@code1 is null or @code1 = '')
    BEGIN
        RAISERROR('bad arguments!',16,1);
        RETURN;
    END
    select
        [cols]
    from
        dbo.tbl
    where
        ([Code] like @code1) OR
        (@code2 is NOT null AND [Code] like @code2) OR
        (@code3 is NOT null AND [Code] like @code3)
END
</code>```

Where at least code1 is expected at all times and the rest are optional. if the where clause involves different columns depending on the report, then I suggest you do multiple sprocs with a similar approach as above to accomodate the different searches.

Body:
I am still quite new to this but am ready to take the next step. I am trying to execute multiple queries at once, if at all possible. From reading some other questions, it seems as if creating a stored procedure is the best route.

The task at hand is creating 36 reports. In this case, hoping to create all 36 reports at one time and not have the results be one continuous entity. Each uses a query very similar to the code shown below. The query shown below is simply the first report to be created out of 36. The only difference in the 36 is the values in the WHERE statement. I am hoping for an operation or method that keeps me from copying and pasting 36 chunks of code into SQL and then copying and pasting those results into an excel spreadsheet.

So my question is 1. Can this be done? 2. Is a stored procedure the best method for this task?

SELECT
    '000000' AS area,
    [SizeClass],
    COUNT(*) AS [Number of Worksites],
    SUM(Employment) AS [Employment In Size Class]
FROM
    dbo.sizeclassreport
WHERE
    code LIKE '11%' OR code LIKE '21%'
GROUP BY
    [SizeClass]
ORDER BY
    [SizeClass]

Body:
It gets tricky if the 36 reports you are talking about pass a different number of arguments and also if they have wildcards AND also if the WHERE clause involves different columns. I would probably write a sproc with the max. number of parameters a report could pass like this for a max of three:

CREATE PROCEDURE dbo.sp_Test
    @code1 varchar(80),
    @code2 varchar(80),
    @code3 varchar(80)
AS
BEGIN
    IF(@code1 is null or @code1 = '')
    BEGIN
        RAISERROR('bad arguments!',16,1);
        RETURN;
    END
    select
        [cols]
    from
        dbo.tbl
    where
        ([Code] like @code1) OR
        (@code2 is NOT null AND [Code] like @code2) OR
        (@code3 is NOT null AND [Code] like @code3)
END

Where at least code1 is expected at all times and the rest are optional. if the where clause involves different columns depending on the report, then I suggest you do multiple sprocs with a similar approach as above to accomodate the different searches.


问:
How to refer to a helm chart in the same repository
I want to maintain a few Helm charts in the same repository that refer to each other in their respective requirements.yaml files.  How should these charts refer to each other's relative paths?

For local development I can use the file:// protocol as in

```<code>name: chart-name
repository: file://../chart-name
</code>```

However when I move to a hosted repository I will need to change this.  I would prefer that this directory of charts does not need to have its final location baked into its repository.yaml files.  Is this possible?

答:
When you move to a hosted repository, won't you have had to publish each chart?
If so, as long as you don't have cyclic dependencies, publish each chart in dependent order to your hosted repo and then update requirements.yaml.

i.e. if you have 3 charts A,B and C.

A has no dependency on B nor C

B depends on A

C depends on B

Publish A to the hosted repo, update B's requirements to point to the hosted repo name of A, then publish B and repeat the update process for C.

I'm doing something similar but I don't use a hosted repo. I already have a large Ansible setup so I wrote a role which installs charts directly from directories. There's a single git repo with all (currently 7) my charts and this minus running a helm server is a similar process. The obvious downside being the manual update of requirements, but I'm not sure there's any other choice on that.

EDIT

A bit hacky but could work:

To avoid editing dependencies one way is to also run your chart repo locally.
If your repo is available at charts.domain.com, add a dependency to this as per usual

```<code>dependencies:
  - name: my-chart
    repository: http://charts.domain.com
    version: 0.0.1
</code>```

then, when you develop locally, add an entry to your hosts file which points charts.domain.com to your localhost charts.

Sample workflow might be something like:

```<code>mkdir my-charts
mv my-char-a-0.0.1.tgz my-charts/
helm repo index my-charts/ --url http://charts.domain.com
</code>```

Now serve the index/repo generated from localhost. This way your dependency is always to charts.domain.com

Depending on which remote host you're using you could just rsync this local index to your remote when you're happy to release and that way you reduce the chance of your local and remotes diverging.

Again, caveat being you need to enable disable this host entry depending on if your developing or wanting to use the live repo.
You can always script the editing of host file entry.

Body:
I want to maintain a few Helm charts in the same repository that refer to each other in their respective requirements.yaml files.  How should these charts refer to each other's relative paths?

For local development I can use the file:// protocol as in

name: chart-name
repository: file://../chart-name

However when I move to a hosted repository I will need to change this.  I would prefer that this directory of charts does not need to have its final location baked into its repository.yaml files.  Is this possible?

Body:
When you move to a hosted repository, won't you have had to publish each chart?
If so, as long as you don't have cyclic dependencies, publish each chart in dependent order to your hosted repo and then update requirements.yaml.

i.e. if you have 3 charts A,B and C.

A has no dependency on B nor C

B depends on A

C depends on B

Publish A to the hosted repo, update B's requirements to point to the hosted repo name of A, then publish B and repeat the update process for C.

I'm doing something similar but I don't use a hosted repo. I already have a large Ansible setup so I wrote a role which installs charts directly from directories. There's a single git repo with all (currently 7) my charts and this minus running a helm server is a similar process. The obvious downside being the manual update of requirements, but I'm not sure there's any other choice on that.

EDIT

A bit hacky but could work:

To avoid editing dependencies one way is to also run your chart repo locally.
If your repo is available at charts.domain.com, add a dependency to this as per usual

dependencies:
  - name: my-chart
    repository: http://charts.domain.com
    version: 0.0.1

then, when you develop locally, add an entry to your hosts file which points charts.domain.com to your localhost charts.

Sample workflow might be something like:

mkdir my-charts
mv my-char-a-0.0.1.tgz my-charts/
helm repo index my-charts/ --url http://charts.domain.com

Now serve the index/repo generated from localhost. This way your dependency is always to charts.domain.com

Depending on which remote host you're using you could just rsync this local index to your remote when you're happy to release and that way you reduce the chance of your local and remotes diverging.

Again, caveat being you need to enable disable this host entry depending on if your developing or wanting to use the live repo.
You can always script the editing of host file entry.


问:
What are the benefits of running multiple Spark tasks in the same JVM?
Different sources (e.g. 1 and  2) claim that Spark can benefit from running multiple tasks in the same JVM. But they don't explain why.

What are these benefits?

答:
The biggest possible advantage is shared memory, in particular handling broadcasted objects. Because these objects are considered read-only there can be shared between multiple threads.

In scenario when you use a single task / executor you need a copy for each JVM so with N tasks there is N copies. With large objects this can be a serious overhead.

Same logic can be applied to other shared objects.


问:
OADate separated from time
An old C++ Application has split Date and Time apart.  The application shows a record as having a Date/Time like so:

```<code>10/21/2015       15:17:22
</code>```

But the data is stored like so:

```<code>13078(+29220)    3857
</code>```

I know our OADate has an offset of 29220.  So 13078 + 29220 = 42298, which is an OADate of 10/21/2015.  But I don't know how 3857 is supposed to equal 15:17:22

The actual fields are:

```<code>int _dateValue;
struct time _timeValue;
</code>```

Another example:

```<code>10/02/2015       08:40:50
13059 (+29220)   2088
</code>```

I believe the time is originally taken from the c struct time function gettime  That struct has functions to pull the hour, minute, and seconds.  But I only have the base value, and I'm working with C# and SQL to convert that base value into a time.

答:
3857 is 0xF11.  By coincidence 0xF == 15 and 0x11 == 17.

2088 is 0x828.  By coincidence 0x8 == 8 and 0x28 == 40.

It looks like the time has the high byte representing the hours, the low byte the minutes, and the seconds are tossed in the bit bucket.

Title: OADate separated from time

Body:
An old C++ Application has split Date and Time apart.  The application shows a record as having a Date/Time like so:

10/21/2015       15:17:22

But the data is stored like so:

13078(+29220)    3857

I know our OADate has an offset of 29220.  So 13078 + 29220 = 42298, which is an OADate of 10/21/2015.  But I don't know how 3857 is supposed to equal 15:17:22

The actual fields are:

int _dateValue;
struct time _timeValue;

Another example:

10/02/2015       08:40:50
13059 (+29220)   2088

I believe the time is originally taken from the c struct time function gettime  That struct has functions to pull the hour, minute, and seconds.  But I only have the base value, and I'm working with C# and SQL to convert that base value into a time.


问:
The which() function in R is not working for some reason
I am getting an 'integer(0)' result for the following query in one instance of my code, but it works fine otherwise:

data.dat:

xx, linear, squared, gaussian, rando, fruit, color, type, xxx, yyy

1, 1,  1,  1,   1.1, apple, blue, gold, 1, 1

2, 3,  4,  1,   2.5, apple, red, gold, 2, 1

3, 2,  9,  2,   4.4, orange, blue, silver, 1, 1

4, 4,  16,  3,  5.9, orange, blue, gold, 1, 1

5, 5,  25,  5,  5.5, peach, blue, gold, 1, 1

6, 6,  32,  12, 6.9, peach, blue, gold, 1, 2

7, 7,  48,  24, 7.2, apple, blue, silver, 1, 1

8, 9,  66,  30, 7.4, apple, blue, gold, 1, 2

9, 8,  84,  31, 7.6, pear, red, gold, 1, 1

10,10, 102, 30, 1.5, orange, red, gold, 1, 1

```<code>data2 <- read.csv(file="data.dat",head=TRUE,sep=",");
which(data2$color=="red" , arr.ind=TRUE)
</code>```

This isn't working either:

```<code>which(as.character(data2$color)=="red" , arr.ind=TRUE)
</code>```

I feel like I'm losing my mind, I've used this function hundreds of times with no issue...

答:
You have an extra whitespace in your entries. Try:</p>

```<code>which(trimws(data2$color) == "red")
</code>```

Body:
I am getting an 'integer(0)' result for the following query in one instance of my code, but it works fine otherwise:

data.dat:

xx, linear, squared, gaussian, rando, fruit, color, type, xxx, yyy

1, 1,  1,  1,   1.1, apple, blue, gold, 1, 1

2, 3,  4,  1,   2.5, apple, red, gold, 2, 1

3, 2,  9,  2,   4.4, orange, blue, silver, 1, 1

4, 4,  16,  3,  5.9, orange, blue, gold, 1, 1

5, 5,  25,  5,  5.5, peach, blue, gold, 1, 1

6, 6,  32,  12, 6.9, peach, blue, gold, 1, 2

7, 7,  48,  24, 7.2, apple, blue, silver, 1, 1

8, 9,  66,  30, 7.4, apple, blue, gold, 1, 2

9, 8,  84,  31, 7.6, pear, red, gold, 1, 1

10,10, 102, 30, 1.5, orange, red, gold, 1, 1

data2 <- read.csv(file="data.dat",head=TRUE,sep=",");
which(data2$color=="red" , arr.ind=TRUE)

This isn't working either:

which(as.character(data2$color)=="red" , arr.ind=TRUE)

I feel like I'm losing my mind, I've used this function hundreds of times with no issue...

Body:
You have an extra whitespace in your entries. Try:

which(trimws(data2$color) == "red")


问:
Composer Installer Error : Signature mismatch
i have a error : Signature mismatch, could not verify the phar file integrity when install composer on windows OS.

When inspecting the code, I come across the $signature variable that does not have a relationship in the verifyAndSave() function call. It's normal ?

But, if I comment test with the verifyAndSave() function, the installation takes place correctly...

答:
If you have this error during install : Signature mismatch, could not verify the phar file integrity

Comment temporarily : zend_extension=opcache in your php.ini, run Composer install and after, uncomment.

Work with PHP 7.2.0.


问:
How to check if asp.net mvc 3 is installed?
I'm trying to write a powershell script that would install asp.net mvc 3 if it is not already installed. How do i check if a specific version of asp.net mvc 3 is installed?</p>

答:
I got curious, and made a Win32_AddRemovePrograms class http://poshcode.org/2470 ... that works, but honestly, you don't need that to check on a specific product, you can just look for that product's ID in the registry.

```<code>test-path "hklm:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{DCDEC776-BADD-48B9-8F9A-DFF513C3D7FA}"
</code>```

Where {DCDEC776-BADD-48B9-8F9A-DFF513C3D7FA} is the product ID for Asp.net MVC 3.  You could double check to make sure by checking the display name for it:

```<code>(Get-ItemProperty "hklm:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{DCDEC776-BADD-48B9-8F9A-DFF513C3D7FA}" DisplayName).DisplayName -eq "Microsoft ASP.NET MVC 3"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I got curious, and made a Win32_AddRemovePrograms class http://poshcode.org/2470 ... that works, but honestly, you don't need that to check on a specific product, you can just look for that product's ID in the registry.

test-path "hklm:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{DCDEC776-BADD-48B9-8F9A-DFF513C3D7FA}"

Where {DCDEC776-BADD-48B9-8F9A-DFF513C3D7FA} is the product ID for Asp.net MVC 3.  You could double check to make sure by checking the display name for it:

(Get-ItemProperty "hklm:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{DCDEC776-BADD-48B9-8F9A-DFF513C3D7FA}" DisplayName).DisplayName -eq "Microsoft ASP.NET MVC 3"


问:
pandas dataframe float point issues
I have a column with float values such as 600.0750, 600.2274, 600.3798, 600.5322.I rounded the values to 3 decimal places and then applied the diff() function to that column which gave me values 0.1524,0.1524 and 0.1524.To remove the duplicates from the output, I applied drop_duplicates. I was expecting to see only 0.1524 but in actual I got 0.1524,0.1524,0.1524.

So I store the output values in another dataframe df_diff and I do df_diff.iloc[2] which gives me  0.15239999999994325 and for df_diff.iloc[3] I get 0.15240000000005693.

I go back and do the same for original df and I get 600.07500000000005. So even when I am rounding, the values are not getting rounded. What can I do to fix this?

Thanks

答:
You say that you rounded to three decimal places, but your numbers have four. The following assumes that four is the correct number.

There are several options. First, you can try not rounding until right before you try to drop duplicates. If that doesn't work, if you aren't too particular about the exact level of precision you're rounding to, you can round to a power of 2, such as 2**14. A second option is to use the https://docs.python.org/2/library/fractions.html module. A third option is to multiply the numbers by 10000 and then round them to integers. If you want the original numbers back, then you can divide them by 10000 again.

Title: pandas dataframe float point issues


问:
Payara - Hazelcast cluster node picks the wrong network interface
When starting Payara cluster, one of the nodes binds to the wrong IP address (internal IP address of the docker which is installed locally on the node).

What is the proper way of letting know the Payara Cluster instance node which address it should bind to?

Node 1 log:

```<code>[2017-12-04T11:35:06.512+0800] [Payara 4.1] [INFO] [] [com.hazelcast.internal.cluster.impl.MulticastJoiner] [tid: _ThreadID=16 _ThreadName=RunLevelControllerThread-1512358500010] [timeMillis: 1512358506512] [levelValue: 800] [[
[172.17.0.1]:5900 [dev] [3.8.5]
Members [1] {
    Member [172.17.0.1]:5900 - 9be6669e-b853-44c0-9656-8488d3e1031b this
}
]]
</code>```

Node 2 log:

```<code>[2017-12-04T11:35:06.771+0800] [Payara 4.1] [INFO] [] [com.hazelcast.internal.cluster.impl.MulticastJoiner] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1512358500129] [timeMillis: 1512358506771 [levelValue: 800] [[
[10.4.0.86]:5900 [dev] [3.8.5]
Members [1] {
    Member [10.4.0.86]:5900 - e3f9dd48-58b9-45f9-88fc-6b0feaedd78f this
}
]]
</code>```

I have tested the cluster itself and it works properly on machines with the only one interface (without docker installed).

I have found issues that are related to my case, but was not able to adapt them in Payara Cluster setup:

Hazelcast cluster over AWS using Docker

Configuring a two node
hazelcast cluster - avoiding multicast

Meaning, suggestion to use the local property: -Dhazelcast.local.localAddress=[yourCorrectIpGoesHere] - works, but in case of cluster environment with centralized management of the nodes config - I do not see how to set the different JVM properties for each of the nodes.

Submitting custom hazelcast-config.xml via the "Override configuration file" could be an option, but it means that full configuration should be done via this file, what makes it not super handy to manage, but currently looks like this is the only option that potentially can help here.

Thanks!

答:
Payara server doesn't expose this configuration option directly. Using the system property hazelcast.local.localAddress is the preferred option. However, you shouldn't set it as a JVM option like you did with

```<code>-Dhazelcast.local.localAddress=...
</code>```

Instead, add the system property using the server page in the Admin Console. On the Properties tab go to System properties tab and add a new property with the variable name hazelcast.local.localAddress and override value set to the IP address of the interface you want Hazelcast to bind to.

This way, the configuration is applied during runtime without any server restart needed and should also be propagated to other instances in the cluster if you also set the property for cluster instances. For those, instead of going to the server page you would go to the configuration of each instance and set the system property there.

Body:
When starting Payara cluster, one of the nodes binds to the wrong IP address (internal IP address of the docker which is installed locally on the node).

What is the proper way of letting know the Payara Cluster instance node which address it should bind to?

Node 1 log:

[2017-12-04T11:35:06.512+0800] [Payara 4.1] [INFO] [] [com.hazelcast.internal.cluster.impl.MulticastJoiner] [tid: _ThreadID=16 _ThreadName=RunLevelControllerThread-1512358500010] [timeMillis: 1512358506512] [levelValue: 800] [[
[172.17.0.1]:5900 [dev] [3.8.5]
Members [1] {
    Member [172.17.0.1]:5900 - 9be6669e-b853-44c0-9656-8488d3e1031b this
}
]]

Node 2 log:

[2017-12-04T11:35:06.771+0800] [Payara 4.1] [INFO] [] [com.hazelcast.internal.cluster.impl.MulticastJoiner] [tid: _ThreadID=17 _ThreadName=RunLevelControllerThread-1512358500129] [timeMillis: 1512358506771 [levelValue: 800] [[
[10.4.0.86]:5900 [dev] [3.8.5]
Members [1] {
    Member [10.4.0.86]:5900 - e3f9dd48-58b9-45f9-88fc-6b0feaedd78f this
}
]]

I have tested the cluster itself and it works properly on machines with the only one interface (without docker installed).

I have found issues that are related to my case, but was not able to adapt them in Payara Cluster setup:

Hazelcast cluster over AWS using Docker

Configuring a two node
hazelcast cluster - avoiding multicast

Meaning, suggestion to use the local property: -Dhazelcast.local.localAddress=[yourCorrectIpGoesHere] - works, but in case of cluster environment with centralized management of the nodes config - I do not see how to set the different JVM properties for each of the nodes.

Submitting custom hazelcast-config.xml via the "Override configuration file" could be an option, but it means that full configuration should be done via this file, what makes it not super handy to manage, but currently looks like this is the only option that potentially can help here.

Thanks!

Body:
Payara server doesn't expose this configuration option directly. Using the system property hazelcast.local.localAddress is the preferred option. However, you shouldn't set it as a JVM option like you did with

-Dhazelcast.local.localAddress=...

Instead, add the system property using the server page in the Admin Console. On the Properties tab go to System properties tab and add a new property with the variable name hazelcast.local.localAddress and override value set to the IP address of the interface you want Hazelcast to bind to.

This way, the configuration is applied during runtime without any server restart needed and should also be propagated to other instances in the cluster if you also set the property for cluster instances. For those, instead of going to the server page you would go to the configuration of each instance and set the system property there.


问:
QGraphicsItem Border Styles
How can I draw a rectangle shape and oval shape like this image.In this code which creates rectangle shape and oval shape with a single line border.But I need to change there border style like this given image.

```<code>Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);

    QBrush redBrush(Qt::red);
    QBrush blueBrush(Qt::blue);
    QPen blackPen(Qt::black);
    blackPen.setWidth(6);

    //rect = scene->addRect(25,25,Qt::RelativeSize);
    elipse = scene->addEllipse(20,20,100,100,blackPen,redBrush);
    elipse->setFlag(QGraphicsItem::ItemIsMovable, true);
    rect = scene->addRect(-20,-10,200,100,blackPen,blueBrush);
    rect->setFlag(QGraphicsItem::ItemIsMovable, true);
    rect->setFlag(QGraphicsItem::ItemIsSelectable,true);
}
</code>```

答:
These properties do not have the QGraphicsItem that Qt provides, what we must do is create our custom QGraphicsItem. An option is to inherit from classes that are standard:

dgraphicsitem.h

```<code>#ifndef DGRAPHICSITEM_H
#define DGRAPHICSITEM_H

#include <QGraphicsRectItem>
#include <QPainter>

class DGraphicsEllipseItem : public QGraphicsEllipseItem
{
public:
    DGraphicsEllipseItem(const QRectF &rect, qreal radius, QGraphicsItem *parent = nullptr):
        QGraphicsEllipseItem(rect, parent){
        mRadius = radius;
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        QGraphicsEllipseItem::paint(painter, option, widget);
        painter->setBrush(brush());
        QRectF r = rect();
        r.setSize(r.size()-mRadius*QSizeF(1, 1));
        r.translate(mRadius*QPointF(1, 1)/2);
        painter->drawEllipse(r);
    }
private:
    qreal mRadius;
};

class DGraphicsRectItem : public QGraphicsRectItem
{
public:
    DGraphicsRectItem(const QRectF &rect, qreal radius, QGraphicsItem *parent = nullptr):
        QGraphicsRectItem(rect, parent){
        mRadius = radius;
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        QGraphicsRectItem::paint(painter, option, widget);
        painter->setBrush(brush());
        QRectF r = rect();
        r.setSize(r.size()-mRadius*QSizeF(1, 1));
        r.translate(mRadius*QPointF(1, 1)/2);
        painter->drawRect(r);
    }
private:
    qreal mRadius;
};
#endif // DGRAPHICSITEM_H
</code>```

then it is added to the scene:

```<code>scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);

QBrush brush(Qt::white);
QPen pen(Qt::green);
pen.setWidth(1);

DGraphicsEllipseItem* ellipse = new DGraphicsEllipseItem(QRectF(20,20, 200,100), 10);
scene->addItem(ellipse);
ellipse->setPen(pen);
ellipse->setBrush(brush);
ellipse->setFlag(QGraphicsItem::ItemIsMovable, true);

DGraphicsRectItem* rect = new DGraphicsRectItem(QRectF(-20,-10,200,100), 10);
scene->addItem(rect);
rect->setPen(pen);
rect->setBrush(brush);
rect->setFlag(QGraphicsItem::ItemIsMovable, true);
</code>```

Output:

The complete example can be found in the following link.

Title: QGraphicsItem Border Styles

Body:
How can I draw a rectangle shape and oval shape like this image.In this code which creates rectangle shape and oval shape with a single line border.But I need to change there border style like this given image.

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);

    QBrush redBrush(Qt::red);
    QBrush blueBrush(Qt::blue);
    QPen blackPen(Qt::black);
    blackPen.setWidth(6);

    //rect = scene->addRect(25,25,Qt::RelativeSize);
    elipse = scene->addEllipse(20,20,100,100,blackPen,redBrush);
    elipse->setFlag(QGraphicsItem::ItemIsMovable, true);
    rect = scene->addRect(-20,-10,200,100,blackPen,blueBrush);
    rect->setFlag(QGraphicsItem::ItemIsMovable, true);
    rect->setFlag(QGraphicsItem::ItemIsSelectable,true);
}

Body:
These properties do not have the QGraphicsItem that Qt provides, what we must do is create our custom QGraphicsItem. An option is to inherit from classes that are standard:

dgraphicsitem.h

#ifndef DGRAPHICSITEM_H
#define DGRAPHICSITEM_H

#include <QGraphicsRectItem>
#include <QPainter>

class DGraphicsEllipseItem : public QGraphicsEllipseItem
{
public:
    DGraphicsEllipseItem(const QRectF &rect, qreal radius, QGraphicsItem *parent = nullptr):
        QGraphicsEllipseItem(rect, parent){
        mRadius = radius;
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        QGraphicsEllipseItem::paint(painter, option, widget);
        painter->setBrush(brush());
        QRectF r = rect();
        r.setSize(r.size()-mRadius*QSizeF(1, 1));
        r.translate(mRadius*QPointF(1, 1)/2);
        painter->drawEllipse(r);
    }
private:
    qreal mRadius;
};

class DGraphicsRectItem : public QGraphicsRectItem
{
public:
    DGraphicsRectItem(const QRectF &rect, qreal radius, QGraphicsItem *parent = nullptr):
        QGraphicsRectItem(rect, parent){
        mRadius = radius;
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        QGraphicsRectItem::paint(painter, option, widget);
        painter->setBrush(brush());
        QRectF r = rect();
        r.setSize(r.size()-mRadius*QSizeF(1, 1));
        r.translate(mRadius*QPointF(1, 1)/2);
        painter->drawRect(r);
    }
private:
    qreal mRadius;
};
#endif // DGRAPHICSITEM_H

then it is added to the scene:

scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);

QBrush brush(Qt::white);
QPen pen(Qt::green);
pen.setWidth(1);

DGraphicsEllipseItem* ellipse = new DGraphicsEllipseItem(QRectF(20,20, 200,100), 10);
scene->addItem(ellipse);
ellipse->setPen(pen);
ellipse->setBrush(brush);
ellipse->setFlag(QGraphicsItem::ItemIsMovable, true);

DGraphicsRectItem* rect = new DGraphicsRectItem(QRectF(-20,-10,200,100), 10);
scene->addItem(rect);
rect->setPen(pen);
rect->setBrush(brush);
rect->setFlag(QGraphicsItem::ItemIsMovable, true);

Output:

The complete example can be found in the following link.


问:
Submit an HTML form with empty checkboxes
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.

However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.

How can I get around this? Thanks.

答:
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:

```<code>if (empty($_POST['myCheckbox']))
     ....
else
     ....
</code>```

In PHP empty() and isset() don't generate notices.

OwnerDisplayName: Tray

LastEditorDisplayName: fmsf

Body:
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:

if (empty($_POST['myCheckbox']))
     ....
else
     ....

In PHP empty() and isset() don't generate notices.

OwnerDisplayName: RoBorg


问:
Need barcode & keyboard to work separately
Is there a way to read from a USB barcode reader in one interface & at the same time use the keyboard & mouse to write data in a diffrent interface application?
My application is running as web application.
Also can it work under unix?</p>

答: Under Linux it's easy; configure Xorg such that the reader is not a core input device, then use the event subsystem to read the input events directly from the reader.</p>


问:
How to make HTTP POST request from front-end to Spring?
I'm trying to set up a webapp with ReactJS as the front-end and a Java back-end connected via Spring, but I am new to Spring.

I have two different Requests set up right now in a RestController:

```<code>@RequestMapping(value = "/index")
public String index() {
        return "index string!";
}

@RequestMapping(method=RequestMethod.POST, value="/login")
public void login(@RequestParam("user") User user) {
        System.out.println(user);
}
</code>```

I can successfully query /index from the front-end like this:

```<code>fetch("http://localhost:3002/index").then(function(response) {
    console.log(response.text());
    return response;
});
</code>```

This prints a Promise that contains the string "index string!"
(I'm not exactly sure how to use this string yet either, but that's not my main problem)

I want to send data using a POST request (should it be PUT?) for a user to log in. My plan is to get a User Object from the request and validate that against my database somewhere else in the Java code. Here is a User object:

```<code>public class User {
  private String username;
  private String password;

  public User(String uName, String pass) {
    username = uName;
    password = pass;
  }
}
</code>```

and here is the POST request in the front-end:

```<code>fetch('http://localhost:3002/login', {
        method: 'POST',
        body: {
          username: username,
          password: password
        }
    });
</code>```

where username and password are strings parsed from HTML.

My understanding is that Spring should create a User Object from the body of the request and let me use that, but instead I'm getting a 400 error without much more detail.

How can I make this 400 error go away and successfully pass data from my front-end to my back-end?

EDIT: here is the top few lines of the returned error

```<code>VM10542:1 POST http://localhost:3002/login 400 ()
(anonymous) @   VM10542:1
func    @   LoginPage.js:26
</code>```

LoginPage.js:26 is the fetch call.

答:
First of all, yes POST is the correct method for this type of call.

In your case you have two options:

Send data as a body

So that the endpoint implementation will look like this:

```<code>@RequestMapping(method=RequestMethod.POST, value="/login")
public void login(@RequestBody User user) {
    System.out.println(user);
}
</code>```

Then send it as a JSON

```<code>fetch('http://localhost:3002/login', {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    username: "foo",
    password: "bar"
  })
});
</code>```

Or send it in params

So that the endpoint implementation will look like this:

```<code>@RequestMapping(method=RequestMethod.POST, value="/login")
public void login(@RequestParam("username") String username,
                  @RequestParam("password") String password) {
    System.out.println(username + " " + password);
}
</code>```

Then send it in params (not the best implementation):

```<code>fetch('http://localhost:3002/login?username=' + username
                                 + '&password=' + password, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  }
});
</code>```

Of course you should bear in mind that plain sending a password is not a good idea, but I believe it is for learning purposes. In other case you may take a look at HTTPS.

You may also take a look at other login handling techniques like for starters JWT or maybe you can introduce OAUTH. Good luck!

EDIT:

I haven't noticed that your model class is wrong.
I believe that you need to make it look like this:

```<code>class User {
    private String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}
</code>```

So the Spring was telling you that the constructor is wrong, because he couldn't find the proper mapping for the username and password fields.

Body:
I'm trying to set up a webapp with ReactJS as the front-end and a Java back-end connected via Spring, but I am new to Spring.

I have two different Requests set up right now in a RestController:

@RequestMapping(value = "/index")
public String index() {
        return "index string!";
}

@RequestMapping(method=RequestMethod.POST, value="/login")
public void login(@RequestParam("user") User user) {
        System.out.println(user);
}

I can successfully query /index from the front-end like this:

fetch("http://localhost:3002/index").then(function(response) {
    console.log(response.text());
    return response;
});

This prints a Promise that contains the string "index string!"
(I'm not exactly sure how to use this string yet either, but that's not my main problem)

I want to send data using a POST request (should it be PUT?) for a user to log in. My plan is to get a User Object from the request and validate that against my database somewhere else in the Java code. Here is a User object:

public class User {
  private String username;
  private String password;

  public User(String uName, String pass) {
    username = uName;
    password = pass;
  }
}

and here is the POST request in the front-end:

fetch('http://localhost:3002/login', {
        method: 'POST',
        body: {
          username: username,
          password: password
        }
    });

where username and password are strings parsed from HTML.

My understanding is that Spring should create a User Object from the body of the request and let me use that, but instead I'm getting a 400 error without much more detail.

How can I make this 400 error go away and successfully pass data from my front-end to my back-end?

EDIT: here is the top few lines of the returned error

VM10542:1 POST http://localhost:3002/login 400 ()
(anonymous) @   VM10542:1
func    @   LoginPage.js:26

LoginPage.js:26 is the fetch call.

Body:
First of all, yes POST is the correct method for this type of call.

In your case you have two options:

Send data as a body

So that the endpoint implementation will look like this:

@RequestMapping(method=RequestMethod.POST, value="/login")
public void login(@RequestBody User user) {
    System.out.println(user);
}

Then send it as a JSON

fetch('http://localhost:3002/login', {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    username: "foo",
    password: "bar"
  })
});

Or send it in params

So that the endpoint implementation will look like this:

@RequestMapping(method=RequestMethod.POST, value="/login")
public void login(@RequestParam("username") String username,
                  @RequestParam("password") String password) {
    System.out.println(username + " " + password);
}

Then send it in params (not the best implementation):

fetch('http://localhost:3002/login?username=' + username
                                 + '&password=' + password, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  }
});

Of course you should bear in mind that plain sending a password is not a good idea, but I believe it is for learning purposes. In other case you may take a look at HTTPS.

You may also take a look at other login handling techniques like for starters JWT or maybe you can introduce OAUTH. Good luck!

EDIT:

I haven't noticed that your model class is wrong.
I believe that you need to make it look like this:

class User {
    private String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}

So the Spring was telling you that the constructor is wrong, because he couldn't find the proper mapping for the username and password fields.


问:
Automatic minimum width for column '#0' in tkinter.TreeView
The tkinter.TreeView has a first default column (identifier #0). For example this is for holding the '+' sing of the tree.

When I add other columns this first column is resized and much to wide.

This is the code producing this treeview.

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter import ttk

root = Tk()

tree = ttk.Treeview(root, columns=('one'))
idx = tree.insert(parent='', index=END, values=('AAA'))
tree.insert(parent=idx, index=END, values=('child'))

tree.column('#0', stretch=False)  # NO effect!

tree.pack()
root.mainloop()
</code>```

I would like to have the first column (#0) in a minimum fixed width depending on the + sign in there. The point is that the width for that column differs from system to system because of different desktop environments and user settings. So it would break the plattform independence of Python3 and Tkinter when I would set a fixed size in pixel here.

答:
On windows that expand / collapse button seems to be dynamically drawn based on the size, and according to this minwidth option defaults to 20. I'd write a method to calculate minwidth such that it accounts for the depth and image and text width + 20.

That being said, using this answer a method can be written for fixing the column width at the minwidth Tk defaults to, by breaking the tagbind at that exact location:

```<code>#the minimum width default that Tk assigns
minwidth = tree.column('#0', option='minwidth')

tree.column('#0', width=minwidth)

#disabling resizing for '#0' column particularly
def handle_click(event):
    if tree.identify_region(event.x, event.y) == "separator":
        if tree.identify_column(event.x) == '#0':
            return "break"

#to have drag drop to have no effect
tree.bind('<Button-1>', handle_click)
#further disabling the double edged arrow display
tree.bind('<Motion>', handle_click)
</code>```

And a complete example:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter import ttk

root = Tk()

tree = ttk.Treeview(root, columns=('one'))
idx = tree.insert(parent='', index=END, values=('AAA'))
tree.insert(parent=idx, index=END, values=('child'))

tree.column('#0', stretch=False)  # NO effect!

#the minimum width default that Tk assigns
minwidth = tree.column('#0', option='minwidth')

tree.column('#0', width=minwidth)

#disabling resizing for '#0' column particularly
def handle_click(event):
    if tree.identify_region(event.x, event.y) == "separator":
        if tree.identify_column(event.x) == '#0':
            return "break"

#to have drag drop to have no effect
tree.bind('<Button-1>', handle_click)
#further disabling the double edged arrow display
tree.bind('<Motion>', handle_click)

tree.pack()
root.mainloop()
</code>```

Body:
The tkinter.TreeView has a first default column (identifier #0). For example this is for holding the '+' sing of the tree.

When I add other columns this first column is resized and much to wide.

This is the code producing this treeview.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter import ttk

root = Tk()

tree = ttk.Treeview(root, columns=('one'))
idx = tree.insert(parent='', index=END, values=('AAA'))
tree.insert(parent=idx, index=END, values=('child'))

tree.column('#0', stretch=False)  # NO effect!

tree.pack()
root.mainloop()

I would like to have the first column (#0) in a minimum fixed width depending on the + sign in there. The point is that the width for that column differs from system to system because of different desktop environments and user settings. So it would break the plattform independence of Python3 and Tkinter when I would set a fixed size in pixel here.

Body:
On windows that expand / collapse button seems to be dynamically drawn based on the size, and according to this minwidth option defaults to 20. I'd write a method to calculate minwidth such that it accounts for the depth and image and text width + 20.

That being said, using this answer a method can be written for fixing the column width at the minwidth Tk defaults to, by breaking the tagbind at that exact location:

#the minimum width default that Tk assigns
minwidth = tree.column('#0', option='minwidth')

tree.column('#0', width=minwidth)

#disabling resizing for '#0' column particularly
def handle_click(event):
    if tree.identify_region(event.x, event.y) == "separator":
        if tree.identify_column(event.x) == '#0':
            return "break"

#to have drag drop to have no effect
tree.bind('<Button-1>', handle_click)
#further disabling the double edged arrow display
tree.bind('<Motion>', handle_click)

And a complete example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter import ttk

root = Tk()

tree = ttk.Treeview(root, columns=('one'))
idx = tree.insert(parent='', index=END, values=('AAA'))
tree.insert(parent=idx, index=END, values=('child'))

tree.column('#0', stretch=False)  # NO effect!

#the minimum width default that Tk assigns
minwidth = tree.column('#0', option='minwidth')

tree.column('#0', width=minwidth)

#disabling resizing for '#0' column particularly
def handle_click(event):
    if tree.identify_region(event.x, event.y) == "separator":
        if tree.identify_column(event.x) == '#0':
            return "break"

#to have drag drop to have no effect
tree.bind('<Button-1>', handle_click)
#further disabling the double edged arrow display
tree.bind('<Motion>', handle_click)

tree.pack()
root.mainloop()


问:
Min and Max of code not finding correct numbers
I have a spreadsheet of information containing information on YouTube videos. I am trying to create a program that will find the average length of the videos and the shortest and longest video. I think I found the average length, but I'm unable to get the shortest and longest video.

I used a for loop to get the information from the sheet, and then I split up the information into sections. I don't think I did that wrong, since I got the right number for the average. I'm assuming it has something to do with my max and min, but I don't know what else to do.

How can I get my max and min values to find the right numbers?

```<code>def main():
  my_file = open('animalVideos.csv', 'r')

  list_of_lines = my_file.read().splitlines()

  sum = 0
  counter = 0

  for i in range(1, len(list_of_lines)):
    one_line = list_of_lines[i]
    line_items = one_line.split(',')
    sum += float(line_items[2])
    counter += 1
    longest = max(line_items[2])
    shortest = min(line_items[2])

  average = sum / counter
  print(average, shortest, longest)

main()
</code>```

答:
```<code>def main():
  with open('animalVideos.csv', 'r') as my_file:
      lengths = [float(line.split(',')[2]) for line in my_file.read().splitlines()[1:]]
  print(sum(lengths)/len(lengths), min(lengths), max(lengths))

main()
</code>```

Your code is replacing the value of shortest and longest every time you go through the for loop.  It's much easier to collect all the lengths in a single list, and then use that list to determine the shortest and longest video

If you're going to be doing anything more complicated than this with csv files, you should use the csv module, it makes things much easier

Body:
I have a spreadsheet of information containing information on YouTube videos. I am trying to create a program that will find the average length of the videos and the shortest and longest video. I think I found the average length, but I'm unable to get the shortest and longest video.

I used a for loop to get the information from the sheet, and then I split up the information into sections. I don't think I did that wrong, since I got the right number for the average. I'm assuming it has something to do with my max and min, but I don't know what else to do.

How can I get my max and min values to find the right numbers?

def main():
  my_file = open('animalVideos.csv', 'r')

  list_of_lines = my_file.read().splitlines()

  sum = 0
  counter = 0

  for i in range(1, len(list_of_lines)):
    one_line = list_of_lines[i]
    line_items = one_line.split(',')
    sum += float(line_items[2])
    counter += 1
    longest = max(line_items[2])
    shortest = min(line_items[2])

  average = sum / counter
  print(average, shortest, longest)

main()

Body:
def main():
  with open('animalVideos.csv', 'r') as my_file:
      lengths = [float(line.split(',')[2]) for line in my_file.read().splitlines()[1:]]
  print(sum(lengths)/len(lengths), min(lengths), max(lengths))

main()

Your code is replacing the value of shortest and longest every time you go through the for loop.  It's much easier to collect all the lengths in a single list, and then use that list to determine the shortest and longest video

If you're going to be doing anything more complicated than this with csv files, you should use the csv module, it makes things much easier