问:
Associativity of floating-point multiplication in a special case
It's well known that IEEE floating-point multiplication is not associative. However, consider the special case where a, b, and c are 32-bit signed integers (in C):

```<code>double da = (double) a;
double db = (double) b;
double dc = (double) c;
</code>```

Now, does da*(db*dc) == (da*db)*dc always return 1? Here, doubles are 64-bit double-precision IEEE floating point numbers. Round-to-even is being used.

I tried several examples by hand, such as a = pow(2, 30) + 1, b = pow(2, 30)+1, c = pow(2, 30) + pow(2, 6), numbers large enough to ensure there would be some rounding involved, because the exact mathematical answer has no representation.

Unfortunately, I couldn't find a counterexample. This expression looks like it may return 0. Could it possibly always return 1? Why?

答:
For questions like this, my first impulse is to try a brute-force search with random numbers. In this case, generating random 32-bit integers with uniform distribution demonstrates that da*(db*dc) != (da*db)*dc for about one third of the cases.

In comments, Pascal Cuoq made a convincing argument that the largest operand must be > 226 in magnitude for inequality to occur. This means we can further restrict a search to operands < 227 in magnitude:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>

// Fixes via: Greg Rose, KISS: A Bit Too Simple. http://eprint.iacr.org/2011/007
static uint32_t z=362436069,w=521288629,jsr=362436069,jcong=123456789;
#define znew (z=36969*(z&0xffff)+(z>>16))
#define wnew (w=18000*(w&0xffff)+(w>>16))
#define MWC  ((znew<<16)+wnew)
#define SHR3 (jsr^=(jsr<<13),jsr^=(jsr>>17),jsr^=(jsr<<5)) /* 2^32-1 */
#define CONG (jcong=69069*jcong+13579)                     /* 2^32 */
#define KISS ((MWC^CONG)+SHR3)

int main (void)
{
    long long count = 0LL, fail = 0LL;
    double minmax = 1.0 / 0.0;
    do {
        int32_t a = KISS & (((uint32_t)1 << 27) - 1);
        int32_t b = KISS & (((uint32_t)1 << 27) - 1);
        int32_t c = KISS & (((uint32_t)1 << 27) - 1);
        volatile double da = (double) a;
        volatile double db = (double) b;
        volatile double dc = (double) c;
        volatile double dab = da * db;
        volatile double dbc = db * dc;
        volatile double p1 = dab * dc;
        volatile double p2 = da * dbc;

        count++;
        if (p1 != p2) {
            double max = fmax (fabs(c), fmax (fabs(da), fabs(db)));
            fail++;
            if (max < minmax) {
                minmax = max;
                printf ("a=%08x  b=%08x  c=%08x  p1=% 22.13a  p2=% 22.13a  minmax=%08x  count=%13lld  fail=%13lld\n",
                        a, b, c, p1, p2, (int32_t)minmax, count, fail);
            }
        }
    } while (1);
    return EXIT_SUCCESS;
}
```
<p>The output of the above code strongly suggests that inequality can occur if the magnitude of either the product <code>da*db</code> or the product <code>db*dc</code> exceeds 2<sup>53</sup>, and that the largest factor therefore must exceed √2<sup>53</sup> in magnitude, that is, it must be greater than <code>0x05A82799</code>.</p>
<pre class="lang-none prettyprint-override"><code>a=0658c99a  b=066c9dd5  c=0679e799  p1= 0x1.080f1700c8935p+80  p2= 0x1.080f1700c8934p+80  minmax=0679e799  count=           48  fail=            1
a=05b06599  b=062ad373  c=0303ee05  p1= 0x1.a72fc3446c46ep+78  p2= 0x1.a72fc3446c46dp+78  minmax=062ad373  count=          248  fail=            6
a=05b3b91a  b=05c6607f  c=061761fd  p1= 0x1.9129296aa189ap+79  p2= 0x1.9129296aa189bp+79  minmax=061761fd  count=          552  fail=           14
a=05ffbe73  b=055f71db  c=0413771e  p1= 0x1.06c12351727fbp+79  p2= 0x1.06c12351727fcp+79  minmax=05ffbe73  count=         1029  fail=           33
a=05ae5163  b=05e25901  c=017bd0b4  p1= 0x1.8cc25e308318ap+77  p2= 0x1.8cc25e3083189p+77  minmax=05e25901  count=         1160  fail=           41
a=0349eff2  b=05a40dd7  c=05b2b3c7  p1= 0x1.a6d583d48b807p+78  p2= 0x1.a6d583d48b806p+78  minmax=05b2b3c7  count=         3187  fail=          129
a=05ae99c5  b=05a4e5a1  c=03d88fe6  p1= 0x1.ed5c24a47c416p+78  p2= 0x1.ed5c24a47c417p+78  minmax=05ae99c5  count=        43479  fail=         1722
a=05626e68  b=05ad8275  c=05acdbe3  p1= 0x1.5b017380396c4p+79  p2= 0x1.5b017380396c5p+79  minmax=05ad8275  count=        49985  fail=         1952
a=01f7f82a  b=05a9f16b  c=05ad0265  p1= 0x1.fa48865afc8abp+77  p2= 0x1.fa48865afc8acp+77  minmax=05ad0265  count=       362414  fail=        14190
a=016047d9  b=05a5d671  c=05ab6f59  p1= 0x1.608381a720becp+77  p2= 0x1.608381a720bebp+77  minmax=05ab6f59  count=      1701498  fail=        66487
a=059ecf08  b=05a83be9  c=05aa9cf9  p1= 0x1.685523897b927p+79  p2= 0x1.685523897b926p+79  minmax=05aa9cf9  count=      3412539  fail=       132973
a=05a9203d  b=05a8b04b  c=050c6609  p1= 0x1.436f803e2c24bp+79  p2= 0x1.436f803e2c24ap+79  minmax=05a9203d  count=      4074531  fail=       158854
a=00e22912  b=05a8f039  c=05a846ad  p1= 0x1.c49a83e32465fp+76  p2= 0x1.c49a83e32465ep+76  minmax=05a8f039  count=     17021780  fail=       665646
a=03bc399a  b=05a8bdf9  c=05a7ca6d  p1= 0x1.de2fac272a096p+78  p2= 0x1.de2fac272a095p+78  minmax=05a8bdf9  count=     17716380  fail=       692903
a=054d26c1  b=05a84b09  c=05a8a8c7  p1= 0x1.53704223556b3p+79  p2= 0x1.53704223556b4p+79  minmax=05a8a8c7  count=     45074477  fail=      1762937
a=03afcaa4  b=05a88a8d  c=05a7f119  p1= 0x1.d7f3ccaacca2dp+78  p2= 0x1.d7f3ccaacca2cp+78  minmax=05a88a8d  count=    118913730  fail=      4649640
a=024efebb  b=05a7e34d  c=05a881b5  p1= 0x1.2783cfcc9de75p+78  p2= 0x1.2783cfcc9de74p+78  minmax=05a881b5  count=    254043151  fail=      9930225
a=05a7d8e7  b=05a87f8b  c=050f538e  p1= 0x1.43d6f3ad2f956p+79  p2= 0x1.43d6f3ad2f957p+79  minmax=05a87f8b  count=    401539580  fail=     15695528
a=007790b6  b=05a859c9  c=05a852bb  p1= 0x1.de61a9e2da63ap+75  p2= 0x1.de61a9e2da63bp+75  minmax=05a859c9  count=    455973582  fail=     17824719
a=01505b17  b=05a8270d  c=05a830d1  p1= 0x1.505d1a5677dfbp+77  p2= 0x1.505d1a5677dfap+77  minmax=05a830d1  count=   1109123125  fail=     43353113
a=0161a988  b=05a82bed  c=05a82917  p1= 0x1.61aaf393e420bp+77  p2= 0x1.61aaf393e420cp+77  minmax=05a82bed  count=   6209738039  fail=    242736587
a=05a82a7d  b=05a8267b  c=01c962b9  p1= 0x1.c96347ff18b85p+77  p2= 0x1.c96347ff18b84p+77  minmax=05a82a7d  count=  43616243136  fail=   1704950604
a=05a8293b  b=05a828a3  c=01a44ac0  p1= 0x1.a44b86270a7d5p+77  p2= 0x1.a44b86270a7d6p+77  minmax=05a8293b  count=  51943039028  fail=   2030420245
a=05a82769  b=05a8292d  c=048dbc75  p1= 0x1.236f64a4577fap+79  p2= 0x1.236f64a4577fbp+79  minmax=05a8292d  count= 476560049469  fail=  18628158958
a=05a82871  b=05a828fd  c=01c044b1  p1= 0x1.c04561ac59666p+77  p2= 0x1.c04561ac59667p+77  minmax=05a828fd  count= 846496019034  fail=  33088575026
a=003f4e0f  b=05a828d7  c=05a828f7  p1= 0x1.fa71612c258eap+74  p2= 0x1.fa71612c258e9p+74  minmax=05a828f7  count= 864908706983  fail=  33808303937
a=043c7359  b=05a827db  c=05a828d9  p1= 0x1.0f1d1e47c37e2p+79  p2= 0x1.0f1d1e47c37e3p+79  minmax=05a828d9  count=1147388053277  fail=  44850164685
a=05a82895  b=05a82887  c=02e5fc6a  p1= 0x1.72feb235ca1e7p+78  p2= 0x1.72feb235ca1e6p+78  minmax=05a82895  count=1383932059721  fail=  54096517230
a=005b76e8  b=05a8284f  c=05a82793  p1= 0x1.6ddbcc2614301p+75  p2= 0x1.6ddbcc2614300p+75  minmax=05a8284f  count=2212385094246  fail=  86479620757
a=034f873b  b=05a827f1  c=05a82755  p1= 0x1.a7c3a2fcb346bp+78  p2= 0x1.a7c3a2fcb346ap+78  minmax=05a827f1  count=2360223870382  fail=  92258517174
a=02b2ee37  b=05a827e7  c=05a82789  p1= 0x1.597729fe1b0f2p+78  p2= 0x1.597729fe1b0f3p+78  minmax=05a827e7  count=4588948516457  fail= 179376767823
a=0023898a  b=05a827db  c=05a82779  p1= 0x1.1c4c566dfffcbp+74  p2= 0x1.1c4c566dfffccp+74  minmax=05a827db  count=6159639135691  fail= 240773437792
a=05a827a1  b=05a827bd  c=0066ef2d  p1= 0x1.9bbcc027b0c20p+75  p2= 0x1.9bbcc027b0c21p+75  minmax=05a827bd  count=7528083873615  fail= 294264463804
</code>```

Body:
It's well known that IEEE floating-point multiplication is not associative. However, consider the special case where a, b, and c are 32-bit signed integers (in C):

double da = (double) a;
double db = (double) b;
double dc = (double) c;

Now, does da*(db*dc) == (da*db)*dc always return 1? Here, doubles are 64-bit double-precision IEEE floating point numbers. Round-to-even is being used.

I tried several examples by hand, such as a = pow(2, 30) + 1, b = pow(2, 30)+1, c = pow(2, 30) + pow(2, 6), numbers large enough to ensure there would be some rounding involved, because the exact mathematical answer has no representation.

Unfortunately, I couldn't find a counterexample. This expression looks like it may return 0. Could it possibly always return 1? Why?

Body:
For questions like this, my first impulse is to try a brute-force search with random numbers. In this case, generating random 32-bit integers with uniform distribution demonstrates that da*(db*dc) != (da*db)*dc for about one third of the cases.

In comments, Pascal Cuoq made a convincing argument that the largest operand must be > 226 in magnitude for inequality to occur. This means we can further restrict a search to operands < 227 in magnitude:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>

// Fixes via: Greg Rose, KISS: A Bit Too Simple. http://eprint.iacr.org/2011/007
static uint32_t z=362436069,w=521288629,jsr=362436069,jcong=123456789;
#define znew (z=36969*(z&0xffff)+(z>>16))
#define wnew (w=18000*(w&0xffff)+(w>>16))
#define MWC  ((znew<<16)+wnew)
#define SHR3 (jsr^=(jsr<<13),jsr^=(jsr>>17),jsr^=(jsr<<5)) /* 2^32-1 */
#define CONG (jcong=69069*jcong+13579)                     /* 2^32 */
#define KISS ((MWC^CONG)+SHR3)

int main (void)
{
    long long count = 0LL, fail = 0LL;
    double minmax = 1.0 / 0.0;
    do {
        int32_t a = KISS & (((uint32_t)1 << 27) - 1);
        int32_t b = KISS & (((uint32_t)1 << 27) - 1);
        int32_t c = KISS & (((uint32_t)1 << 27) - 1);
        volatile double da = (double) a;
        volatile double db = (double) b;
        volatile double dc = (double) c;
        volatile double dab = da * db;
        volatile double dbc = db * dc;
        volatile double p1 = dab * dc;
        volatile double p2 = da * dbc;

        count++;
        if (p1 != p2) {
            double max = fmax (fabs(c), fmax (fabs(da), fabs(db)));
            fail++;
            if (max < minmax) {
                minmax = max;
                printf ("a=%08x  b=%08x  c=%08x  p1=% 22.13a  p2=% 22.13a  minmax=%08x  count=%13lld  fail=%13lld\n",
                        a, b, c, p1, p2, (int32_t)minmax, count, fail);
            }
        }
    } while (1);
    return EXIT_SUCCESS;
}

The output of the above code strongly suggests that inequality can occur if the magnitude of either the product da*db or the product db*dc exceeds 253, and that the largest factor therefore must exceed √253 in magnitude, that is, it must be greater than 0x05A82799.

a=0658c99a  b=066c9dd5  c=0679e799  p1= 0x1.080f1700c8935p+80  p2= 0x1.080f1700c8934p+80  minmax=0679e799  count=           48  fail=            1
a=05b06599  b=062ad373  c=0303ee05  p1= 0x1.a72fc3446c46ep+78  p2= 0x1.a72fc3446c46dp+78  minmax=062ad373  count=          248  fail=            6
a=05b3b91a  b=05c6607f  c=061761fd  p1= 0x1.9129296aa189ap+79  p2= 0x1.9129296aa189bp+79  minmax=061761fd  count=          552  fail=           14
a=05ffbe73  b=055f71db  c=0413771e  p1= 0x1.06c12351727fbp+79  p2= 0x1.06c12351727fcp+79  minmax=05ffbe73  count=         1029  fail=           33
a=05ae5163  b=05e25901  c=017bd0b4  p1= 0x1.8cc25e308318ap+77  p2= 0x1.8cc25e3083189p+77  minmax=05e25901  count=         1160  fail=           41
a=0349eff2  b=05a40dd7  c=05b2b3c7  p1= 0x1.a6d583d48b807p+78  p2= 0x1.a6d583d48b806p+78  minmax=05b2b3c7  count=         3187  fail=          129
a=05ae99c5  b=05a4e5a1  c=03d88fe6  p1= 0x1.ed5c24a47c416p+78  p2= 0x1.ed5c24a47c417p+78  minmax=05ae99c5  count=        43479  fail=         1722
a=05626e68  b=05ad8275  c=05acdbe3  p1= 0x1.5b017380396c4p+79  p2= 0x1.5b017380396c5p+79  minmax=05ad8275  count=        49985  fail=         1952
a=01f7f82a  b=05a9f16b  c=05ad0265  p1= 0x1.fa48865afc8abp+77  p2= 0x1.fa48865afc8acp+77  minmax=05ad0265  count=       362414  fail=        14190
a=016047d9  b=05a5d671  c=05ab6f59  p1= 0x1.608381a720becp+77  p2= 0x1.608381a720bebp+77  minmax=05ab6f59  count=      1701498  fail=        66487
a=059ecf08  b=05a83be9  c=05aa9cf9  p1= 0x1.685523897b927p+79  p2= 0x1.685523897b926p+79  minmax=05aa9cf9  count=      3412539  fail=       132973
a=05a9203d  b=05a8b04b  c=050c6609  p1= 0x1.436f803e2c24bp+79  p2= 0x1.436f803e2c24ap+79  minmax=05a9203d  count=      4074531  fail=       158854
a=00e22912  b=05a8f039  c=05a846ad  p1= 0x1.c49a83e32465fp+76  p2= 0x1.c49a83e32465ep+76  minmax=05a8f039  count=     17021780  fail=       665646
a=03bc399a  b=05a8bdf9  c=05a7ca6d  p1= 0x1.de2fac272a096p+78  p2= 0x1.de2fac272a095p+78  minmax=05a8bdf9  count=     17716380  fail=       692903
a=054d26c1  b=05a84b09  c=05a8a8c7  p1= 0x1.53704223556b3p+79  p2= 0x1.53704223556b4p+79  minmax=05a8a8c7  count=     45074477  fail=      1762937
a=03afcaa4  b=05a88a8d  c=05a7f119  p1= 0x1.d7f3ccaacca2dp+78  p2= 0x1.d7f3ccaacca2cp+78  minmax=05a88a8d  count=    118913730  fail=      4649640
a=024efebb  b=05a7e34d  c=05a881b5  p1= 0x1.2783cfcc9de75p+78  p2= 0x1.2783cfcc9de74p+78  minmax=05a881b5  count=    254043151  fail=      9930225
a=05a7d8e7  b=05a87f8b  c=050f538e  p1= 0x1.43d6f3ad2f956p+79  p2= 0x1.43d6f3ad2f957p+79  minmax=05a87f8b  count=    401539580  fail=     15695528
a=007790b6  b=05a859c9  c=05a852bb  p1= 0x1.de61a9e2da63ap+75  p2= 0x1.de61a9e2da63bp+75  minmax=05a859c9  count=    455973582  fail=     17824719
a=01505b17  b=05a8270d  c=05a830d1  p1= 0x1.505d1a5677dfbp+77  p2= 0x1.505d1a5677dfap+77  minmax=05a830d1  count=   1109123125  fail=     43353113
a=0161a988  b=05a82bed  c=05a82917  p1= 0x1.61aaf393e420bp+77  p2= 0x1.61aaf393e420cp+77  minmax=05a82bed  count=   6209738039  fail=    242736587
a=05a82a7d  b=05a8267b  c=01c962b9  p1= 0x1.c96347ff18b85p+77  p2= 0x1.c96347ff18b84p+77  minmax=05a82a7d  count=  43616243136  fail=   1704950604
a=05a8293b  b=05a828a3  c=01a44ac0  p1= 0x1.a44b86270a7d5p+77  p2= 0x1.a44b86270a7d6p+77  minmax=05a8293b  count=  51943039028  fail=   2030420245
a=05a82769  b=05a8292d  c=048dbc75  p1= 0x1.236f64a4577fap+79  p2= 0x1.236f64a4577fbp+79  minmax=05a8292d  count= 476560049469  fail=  18628158958
a=05a82871  b=05a828fd  c=01c044b1  p1= 0x1.c04561ac59666p+77  p2= 0x1.c04561ac59667p+77  minmax=05a828fd  count= 846496019034  fail=  33088575026
a=003f4e0f  b=05a828d7  c=05a828f7  p1= 0x1.fa71612c258eap+74  p2= 0x1.fa71612c258e9p+74  minmax=05a828f7  count= 864908706983  fail=  33808303937
a=043c7359  b=05a827db  c=05a828d9  p1= 0x1.0f1d1e47c37e2p+79  p2= 0x1.0f1d1e47c37e3p+79  minmax=05a828d9  count=1147388053277  fail=  44850164685
a=05a82895  b=05a82887  c=02e5fc6a  p1= 0x1.72feb235ca1e7p+78  p2= 0x1.72feb235ca1e6p+78  minmax=05a82895  count=1383932059721  fail=  54096517230
a=005b76e8  b=05a8284f  c=05a82793  p1= 0x1.6ddbcc2614301p+75  p2= 0x1.6ddbcc2614300p+75  minmax=05a8284f  count=2212385094246  fail=  86479620757
a=034f873b  b=05a827f1  c=05a82755  p1= 0x1.a7c3a2fcb346bp+78  p2= 0x1.a7c3a2fcb346ap+78  minmax=05a827f1  count=2360223870382  fail=  92258517174
a=02b2ee37  b=05a827e7  c=05a82789  p1= 0x1.597729fe1b0f2p+78  p2= 0x1.597729fe1b0f3p+78  minmax=05a827e7  count=4588948516457  fail= 179376767823
a=0023898a  b=05a827db  c=05a82779  p1= 0x1.1c4c566dfffcbp+74  p2= 0x1.1c4c566dfffccp+74  minmax=05a827db  count=6159639135691  fail= 240773437792
a=05a827a1  b=05a827bd  c=0066ef2d  p1= 0x1.9bbcc027b0c20p+75  p2= 0x1.9bbcc027b0c21p+75  minmax=05a827bd  count=7528083873615  fail= 294264463804


来源: stackexchange

问:
How to force JavaMailSenderImpl to use TLS1.2?
Have a JDK7 app running on Tomcat and it does have the following env settings:

```<code>-Dhttps.protocols=TLSv1.1,TLSv1.2
</code>```

The above setting ensures that we don't use TLS 1.0 when connecting over HTTPS while making API calls etc.

We also use the org.springframework.mail.javamail.JavaMailSenderImpl class to send outgoing SMTP email, and use these props:

```<code> mail.smtp.auth=false;mail.smtp.socketFactory.port=2525;mail.smtp.socketFactory.fallback=true;mail.smtp.starttls.enable=true
</code>```

The problem is that the connection to the SMTP email server is failing when it's upgraded to TLS1.2.

javax.net.ssl.SSLHandshakeException: Remote host closed connection
  during handshake

Is there a settings or code change that will force the TLS1.2 protocol?

I did some searching and it looks like these env settings are only for applet and web clients, not for server side apps

```<code>-Ddeployment.security.SSLv2Hello=false -Ddeployment.security.SSLv3=false -Ddeployment.security.TLSv1=false
</code>```

答:
This is the fix for the next guy looking:</p>
```<code>mail.smtp.starttls.enable=true;
mail.smtp.ssl.protocols=TLSv1.2;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Have a JDK7 app running on Tomcat and it does have the following env settings:

-Dhttps.protocols=TLSv1.1,TLSv1.2

The above setting ensures that we don't use TLS 1.0 when connecting over HTTPS while making API calls etc.

We also use the org.springframework.mail.javamail.JavaMailSenderImpl class to send outgoing SMTP email, and use these props:

 mail.smtp.auth=false;mail.smtp.socketFactory.port=2525;mail.smtp.socketFactory.fallback=true;mail.smtp.starttls.enable=true

The problem is that the connection to the SMTP email server is failing when it's upgraded to TLS1.2.

javax.net.ssl.SSLHandshakeException: Remote host closed connection
  during handshake

Is there a settings or code change that will force the TLS1.2 protocol?

I did some searching and it looks like these env settings are only for applet and web clients, not for server side apps

-Ddeployment.security.SSLv2Hello=false -Ddeployment.security.SSLv3=false -Ddeployment.security.TLSv1=false

Body:
This is the fix for the next guy looking:

mail.smtp.starttls.enable=true;
mail.smtp.ssl.protocols=TLSv1.2;

ContentLicense: CC BY-SA 4.0


问:
Read 2 data string
I have faced a problem with my program and I don't understand why. I read 2 data string and the program just skips the first read and jumps on the second one. I can't place the program here because is pretty big and I don't think anyone wants to waste time reading and understanding it.For example:

```<code>struct agenda {
    char nume[20];
    char prenume[20];
} vector[50];

void adaugare (){
    printf("x=");
    gets_s(vector[0].nume);
    printf("y=");
    gets_s(vector[0].prenume);
}
</code>```

And when I build and run it, it only reads the second string.Edit:

```<code> struct agenda {
    char nume[20];
    char prenume[20];
}vector[50];

void adaugare();

void main() {
    adaugare();
    _getch();
}

void adaugare() {
    int numar;
    system("cls");
    printf("\n\tCate contacte doriti sa adaugati? ");
    scanf_s("%d", &numar);
    for (int i = 0; i < numar; i++) {
        printf("\nIntroduceti contactul %d\n", i);
        printf("\tIntroduceti numele contactului %d: ", i);
        gets_s(vector[i].nume);
        printf("\tIntroduceti prenumele contactului %d: ", i);
        gets_s(vector[i].prenume);
        }
}
</code>```

So in this case if you build and run it, it only reads the second string.

答:
First thing you should elaborate what is gets_s() ? Is it your implementation of gets() or typo ? Instead of gets_s use fgets() to avoid buffering problem as mentioned in comments by  @user3121023

```<code>// gets_s(vector[0].nume);
  fgets(vector[0].nume,sizeof(vector[0].nume),stdin);
  printf("y=");
 // gets_s(vector[0].prenume);
  fgets(vector[0].prenume,sizeof(vector[0].prenume),stdin);
</code>```

EDIT(for visual c++) :

```<code>void adaugare() {
    int numar;
    system("cls");
    printf("\n\tCate contacte doriti sa adaugati? ");
    scanf_s("%d", &numar);

    fflush(stdin);
    for (int i = 0; i < numar; i++) {
        printf("\nIntroduceti contactul %d\n", i);
        printf("\tIntroduceti numele contactului %d: \n", i);
        fflush(stdin);
        gets_s(vector[i].nume);
        printf("\tIntroduceti prenumele contactului %d: \n", i);
        fflush(stdin);
        gets_s(vector[i].prenume);
        }
</code>```

}

Because You must flush the input buffer(stdin) before using gets_s().

I hope it help's.

Title: Read 2 data string

Body:
I have faced a problem with my program and I don't understand why. I read 2 data string and the program just skips the first read and jumps on the second one. I can't place the program here because is pretty big and I don't think anyone wants to waste time reading and understanding it.For example:

struct agenda {
    char nume[20];
    char prenume[20];
} vector[50];

void adaugare (){
    printf("x=");
    gets_s(vector[0].nume);
    printf("y=");
    gets_s(vector[0].prenume);
}

And when I build and run it, it only reads the second string.Edit:

 struct agenda {
    char nume[20];
    char prenume[20];
}vector[50];

void adaugare();

void main() {
    adaugare();
    _getch();
}

void adaugare() {
    int numar;
    system("cls");
    printf("\n\tCate contacte doriti sa adaugati? ");
    scanf_s("%d", &numar);
    for (int i = 0; i < numar; i++) {
        printf("\nIntroduceti contactul %d\n", i);
        printf("\tIntroduceti numele contactului %d: ", i);
        gets_s(vector[i].nume);
        printf("\tIntroduceti prenumele contactului %d: ", i);
        gets_s(vector[i].prenume);
        }
}

So in this case if you build and run it, it only reads the second string.

Body:
First thing you should elaborate what is gets_s() ? Is it your implementation of gets() or typo ? Instead of gets_s use fgets() to avoid buffering problem as mentioned in comments by  @user3121023

// gets_s(vector[0].nume);
  fgets(vector[0].nume,sizeof(vector[0].nume),stdin);
  printf("y=");
 // gets_s(vector[0].prenume);
  fgets(vector[0].prenume,sizeof(vector[0].prenume),stdin);

EDIT(for visual c++) :

void adaugare() {
    int numar;
    system("cls");
    printf("\n\tCate contacte doriti sa adaugati? ");
    scanf_s("%d", &numar);

    fflush(stdin);
    for (int i = 0; i < numar; i++) {
        printf("\nIntroduceti contactul %d\n", i);
        printf("\tIntroduceti numele contactului %d: \n", i);
        fflush(stdin);
        gets_s(vector[i].nume);
        printf("\tIntroduceti prenumele contactului %d: \n", i);
        fflush(stdin);
        gets_s(vector[i].prenume);
        }

}

Because You must flush the input buffer(stdin) before using gets_s().

I hope it help's.


问:
.NET POP3 Library that supports Proxy
I am looking for a pop3 library that will let me use a proxy. I have tried OpenPop.NET but it doesn't support proxy. Thanks in advance.</p>

答:
I guess there aren't many proxy types able to connect a POP server other than SOCKS.

A quick search on google lead me to this. It allows you to establish a TcpClient connection through a proxy.

Here is the best POP3 client I have ever seen (and used many times), especially if you need to work with the content of retrieved mails. It uses the TcpClient class to establish connections with the POP server and the code is full of comments.
You'll just have to modify the sources (mainly Pop3MailClient) here and there to improve the client so it can use a SOCKS proxy.

ContentLicense: CC BY-SA 2.5

Title: .NET POP3 Library that supports Proxy


问:
What compression is used in txt file
Hello what type of compression is used in this txt file

https://mega.nz/#!AEgwXZ7L!6pJEhKvOUKnWzqfmewNMtxb0uOn_qK_CTmW6TB6z3B0

want to convert it but don't know how is compressed this

答: It's not compressed. If it were, it would not be compressible by a factor of eight to ten with conventional compression software (e.g. gzip).</p>

Title: What compression is used in txt file


问:
JS Add events to a List where rows are added dynamically

Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

```<code>function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}
</code>```

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

答:
Change rowElement.addEventListener("onmouseover", alert("A"), false);

To rowElement.addEventListener("mouseover", function() { alert("A"); }, false);

Body:
Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya


问:
HTML datalist keeps crashing when dynamically loaded with Vue
I'm using Vue.js to load an HTML datalist. Whenever I type in my input box that is connected to my datalist, my page freezes (using Chrome). I'm using jQuery to make an AJAX call to initially get all of my users when the page loads, then using the JavaScript filter function to make a new array that has indexOf whatever is typed in my input box, then putting that new filtered array of objects into the datalist element.

Here is my HTML:

```<code><div id="my-app">
  <input list="user-search" type="text" id="find-user" name="find-user" v-model="findUser">
    <datalist id="user-search">
      <option v-for="user in findUserList">{{ user.vendorName }}</option>
    </datalist>
</div>
</code>```

Here is my Vue JavaScript:

```<code>var myApp = new Vue({
  el: '#my-app',
  data: {
    users: [],
    findUser: '',
    findUserList: '',
  },
  watch: {
    findUser: function(val) {
      this.findUserResults();
    }
  },
  methods: {
    findUserResults: function() {
      var lookFor = this.findUser.toLowerCase();
      this.findUserList = this.users.filter(function(user) {
        return (user.vendorName.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1 || user.email.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1);
      });
    },
    loadUsers: function() {
      $.ajax({
        method: 'GET',
        url: '/users',
        success: function(data) {
          myApp.users = JSON.parse(data);
        },
        error: function() {
                console.log('error...');
        }
      });
    }
  },
  mounted: function() {
    this.loadUsers();
  }
})
</code>```

The users load fine when the page loads. No problems there. I even commented out the v-for and just console.log'd the results of the filter with no problem either. The issue comes in when I implement dynamically adding the <option> values in the <datalist>. I've tried wrapping the options in the vue <template> tag and moving the v-for there with no success.

I have this working fine on another page, but instead I'm populating a table with
 and  instead of <datalist> and <option>.

What could be causing my page to crash? Is <datalist> not good enough to handle all of this? Maybe I'm missing something that a second set of eyes could help solve.

EDIT

The data that is being populated into users looks like this (it's an array of objects):

```<code>[{id:1, vendorName:'john'}, {id:2, vendorName:'Rachel', {id:3, vendorName:'Steve'}]
</code>```

ANSWER

This was actually just an example of someone overthinking (me). B.Fleming's answer about this being recursive clued me into why my approach above was incorrect. There is no need to keep reloading the datalist options every time the user types. That's exactly what <datalist> being linked to <input> does; no JavaScript needed. All I need(ed) to do was load all ~3,000 of my users into the <datalist> tag as <option>s on page load (or whenever I want the input and datalist to show up), and let the datalist and input handle the rest. I haven't tested this with the app in the example above because I'm not near that computer, but just as a proof of concept that a datalist can handle thousands of option elements, I wrote this and ran it locally with no issue (not sure why the snippet console keeps saying there is an error when it works):

window.onload = function() {
    var datalistElement = document.getElementById('datalist-test');
    var datalistString = '';
    for (var i = 0; i < 3000; i++) {
        datalistString += '<option>' + Math.random().toString(36).substring(7); + '</option>';
    }
    datalistElement.innerHTML = datalistString;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Datalist Test</title>
</head>

<body>
 <input list="datalist-test" type="text">
 <datalist id="datalist-test">
 </datalist>
</body>
</html></code>```

3,000 datalist option elements, and it's fine.

答:
You have infinitely recursive calls. You're calling myApp.findUser() on entering/deleting search text, which calls myApp.findUserResults(), which calls myApp.findUser(), etc. You'll need to fix this.

To fix this, all you have to do is load all of the users into the datalist options once. Then, let the input box and datalist handle the rest. No need to keep reloading the datalist options every time the user types.

Body:
I'm using Vue.js to load an HTML datalist. Whenever I type in my input box that is connected to my datalist, my page freezes (using Chrome). I'm using jQuery to make an AJAX call to initially get all of my users when the page loads, then using the JavaScript filter function to make a new array that has indexOf whatever is typed in my input box, then putting that new filtered array of objects into the datalist element.

Here is my HTML:

  <input list="user-search" type="text" id="find-user" name="find-user" v-model="findUser">
    <datalist id="user-search">
      <option v-for="user in findUserList">{{ user.vendorName }}</option>
    </datalist>

Here is my Vue JavaScript:

var myApp = new Vue({
  el: '#my-app',
  data: {
    users: [],
    findUser: '',
    findUserList: '',
  },
  watch: {
    findUser: function(val) {
      this.findUserResults();
    }
  },
  methods: {
    findUserResults: function() {
      var lookFor = this.findUser.toLowerCase();
      this.findUserList = this.users.filter(function(user) {
        return (user.vendorName.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1 || user.email.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1);
      });
    },
    loadUsers: function() {
      $.ajax({
        method: 'GET',
        url: '/users',
        success: function(data) {
          myApp.users = JSON.parse(data);
        },
        error: function() {
                console.log('error...');
        }
      });
    }
  },
  mounted: function() {
    this.loadUsers();
  }
})

The users load fine when the page loads. No problems there. I even commented out the v-for and just console.log'd the results of the filter with no problem either. The issue comes in when I implement dynamically adding the <option> values in the <datalist>. I've tried wrapping the options in the vue <template> tag and moving the v-for there with no success.

I have this working fine on another page, but instead I'm populating a table with
 and  instead of <datalist> and <option>.

What could be causing my page to crash? Is <datalist> not good enough to handle all of this? Maybe I'm missing something that a second set of eyes could help solve.

EDIT

The data that is being populated into users looks like this (it's an array of objects):

[{id:1, vendorName:'john'}, {id:2, vendorName:'Rachel', {id:3, vendorName:'Steve'}]

ANSWER

This was actually just an example of someone overthinking (me). B.Fleming's answer about this being recursive clued me into why my approach above was incorrect. There is no need to keep reloading the datalist options every time the user types. That's exactly what <datalist> being linked to <input> does; no JavaScript needed. All I need(ed) to do was load all ~3,000 of my users into the <datalist> tag as <option>s on page load (or whenever I want the input and datalist to show up), and let the datalist and input handle the rest. I haven't tested this with the app in the example above because I'm not near that computer, but just as a proof of concept that a datalist can handle thousands of option elements, I wrote this and ran it locally with no issue (not sure why the snippet console keeps saying there is an error when it works):

window.onload = function() {
    var datalistElement = document.getElementById('datalist-test');
    var datalistString = '';
    for (var i = 0; i < 3000; i++) {
        datalistString += '<option>' + Math.random().toString(36).substring(7); + '</option>';
    }
    datalistElement.innerHTML = datalistString;
}

<!DOCTYPE html>

 <title>Datalist Test</title>

 <input list="datalist-test" type="text">
 <datalist id="datalist-test">
 </datalist>

3,000 datalist option elements, and it's fine.


问:
How to put JSON data into a HTML div?
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

答:
You can use pre tag to display JSON.

var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
$('pre').html(JSON.stringify(data, undefined, 2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
``````</code>```

Title: How to put JSON data into a HTML div?

Body:
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

Body:
You can use pre tag to display JSON.

var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
$('pre').html(JSON.stringify(data, undefined, 2));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>


问:
Send id to controller from view in option tag
I am trying to create my first web app. I have list of products and I want to sort products by name or price. The possible option I have in <select> tag and I try to use method onchange to send paramteres to my controller and there sort my list of products. When I debug my program I saw that as paramteres is send null value. Have you got some idea how can I resolve my problem?

```<code><p>Sort by:</p>

<select onchange="location = this.value">
   <option value="@Url.Action("SortByString", new { id = "-----" })">-----</option>
   <option value="@Url.Action("SortByString", new { id = "Name" })">Name</option>
   <option value="@Url.Action("SortByString", new { id = "Price" })">Price</option>
</select>

public ActionResult SortByString(string sort){}
</code>```

And as paramter sort is send null. Thanks.

答:
You should use one of the multiple overloads of Url.Action() method according to your need. In this case, you can use the fourth overload which is specified in this article.

So you need to change your code as following to pass exactly that parameter which you specified in your action method in the controller (If you don't want to define a custom route for your URL):

```<code><p>Sort by:</p>

<select onchange="location = this.value">
   <option value="@Url.Action("SortByString", new { sort = "-----" })">-----</option>
   <option value="@Url.Action("SortByString", new { sort = "Name" })">Name</option>
   <option value="@Url.Action("SortByString", new { sort = "Price" })">Price</option>
</select>

public ActionResult SortByString(string sort){}
</code>```

Body:
I am trying to create my first web app. I have list of products and I want to sort products by name or price. The possible option I have in <select> tag and I try to use method onchange to send paramteres to my controller and there sort my list of products. When I debug my program I saw that as paramteres is send null value. Have you got some idea how can I resolve my problem?

Sort by:

<select onchange="location = this.value">
   <option value="@Url.Action("SortByString", new { id = "-----" })">-----</option>
   <option value="@Url.Action("SortByString", new { id = "Name" })">Name</option>
   <option value="@Url.Action("SortByString", new { id = "Price" })">Price</option>
</select>

public ActionResult SortByString(string sort){}

And as paramter sort is send null. Thanks.

Body:
You should use one of the multiple overloads of Url.Action() method according to your need. In this case, you can use the fourth overload which is specified in this article.

So you need to change your code as following to pass exactly that parameter which you specified in your action method in the controller (If you don't want to define a custom route for your URL):

<p>Sort by:</p>

<select onchange="location = this.value">
   <option value="@Url.Action("SortByString", new { sort = "-----" })">-----</option>
   <option value="@Url.Action("SortByString", new { sort = "Name" })">Name</option>
   <option value="@Url.Action("SortByString", new { sort = "Price" })">Price</option>
</select>

public ActionResult SortByString(string sort){}


问:
Can someone explain this behavior in javascript?
Tested in Firefox:</p>

```<code>a = [] + 0;
b = 0;

alert(a); // 0
alert(b); // 0

alert(!a); // false
alert(!b); // true
</code>```

答:
The + concatenation operator causes a toString evaluation of 0.

As such the value of a is "0", while the value of b is 0.

From ECMAScript 11.6.1 The Addition operator(+)

The addition operator either performs string concatenation or numeric addition. The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:

Let lref be the result of evaluating AdditiveExpression.

Let lval be GetValue(lref).

Let rref be the result of evaluating MultiplicativeExpression.

Let rval be GetValue(rref).

Let lprim be ToPrimitive(lval).

Let rprim be ToPrimitive(rval).

If Type(lprim) is String or Type(rprim) is String, then

a.   Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the
  Note below 11.6.3.

NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.

NOTE 2 Step 7 differs from step 3 of the comparison algorithm for the relational operators (11.8.5), by using the logical-or operation instead of the logical-and operation.

Body:
Tested in Firefox:

a = [] + 0;
b = 0;

alert(a); // 0
alert(b); // 0

alert(!a); // false
alert(!b); // true


问:
why using android:configChanges is a bad practice
I have gone through different posts and questions for handling rotation and AsyncTask. In each post it is mentioned that using android:configChanges
is a bad practice. But i didn't find the actual reason why it is discouraged and why it is a bad practice. What are the disadvantage if we use android:configChanges to handle orientation.

Note:
I know it is already answered how to handle orientation and AsyncTask. but I want to know reason behind not using android:configChanges.

答:
Using android:configChanges is good practice if you know what you are doing.

Just always test how your application how it behaves when it is restarted by system to stay comfortable for user so some state has to be saved all the time but not all.
With config changes like this:

android:configChanges="locale|keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

Your application will restart rather rarely on new devices that have a lot of memory. If it restarts it's not so unexpected for user anyway, as user had attention elsewhere and came back to app. User don't have to be in exact same state after restart if it happens by manual killing of application or application restart because of some other heavy tasks (playing game) user is doing, the user experience is important here.

If you need to refresh List just for different layouts for orientations changes or you need to hide some view elements you can call:

```<code>public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    _list.reloadData();
    _editorButton.visible(isPortrait());
}
</code>```

(I use my custom classes but you get the point)

Body:
Using android:configChanges is good practice if you know what you are doing.

Just always test how your application how it behaves when it is restarted by system to stay comfortable for user so some state has to be saved all the time but not all.
With config changes like this:

android:configChanges="locale|keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

Your application will restart rather rarely on new devices that have a lot of memory. If it restarts it's not so unexpected for user anyway, as user had attention elsewhere and came back to app. User don't have to be in exact same state after restart if it happens by manual killing of application or application restart because of some other heavy tasks (playing game) user is doing, the user experience is important here.

If you need to refresh List just for different layouts for orientations changes or you need to hide some view elements you can call:

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    _list.reloadData();
    _editorButton.visible(isPortrait());
}

(I use my custom classes but you get the point)


问:
How to include file in NodeJS SOAP request
I am using the MERN stack and one of our requirements is to hit a SOAP web service from NodeJS. Part of this SOAP call includes a file upload. I have been using node-soap package (https://github.com/vpulim/node-soap). Is there an additional NPM package that I can use for this purpose, that is specifically to include a file in a SOAP request? As a backup how does SOAP handle files? Is there some way I can hack this, like convert it to base64 or something like that first? Any help is greatly appreciated. Versions below.

```<code>node -v v6.10.2
npm -v 3.10.10
soap@0.19.0
│ ├── compress@0.99.0
│ ├─┬ concat-stream@1.6.0
</code>```

答:
Apologies for answering my own question, especially after so much time. I hadn't used SOAP in a long, long time and never with Node so I failed to realize the question really is, how do you handle files in a SOAP request. My answer was to convert it to Base64 first. Something like:</p>

```<code>const file = fs.readFileSync('picture_of_kittehs.jpg')
const fileBase64 = new Buffer(file).toString('base64')
</code>```

Body:
I am using the MERN stack and one of our requirements is to hit a SOAP web service from NodeJS. Part of this SOAP call includes a file upload. I have been using node-soap package (https://github.com/vpulim/node-soap). Is there an additional NPM package that I can use for this purpose, that is specifically to include a file in a SOAP request? As a backup how does SOAP handle files? Is there some way I can hack this, like convert it to base64 or something like that first? Any help is greatly appreciated. Versions below.

node -v v6.10.2
npm -v 3.10.10
soap@0.19.0
│ ├── compress@0.99.0
│ ├─┬ concat-stream@1.6.0

Body:
Apologies for answering my own question, especially after so much time. I hadn't used SOAP in a long, long time and never with Node so I failed to realize the question really is, how do you handle files in a SOAP request. My answer was to convert it to Base64 first. Something like:

const file = fs.readFileSync('picture_of_kittehs.jpg')
const fileBase64 = new Buffer(file).toString('base64')


问:
Firebase assistant does not act similar to google instruction
I used Firebase assistant from android studio tools to import firebase messaging into my android app. According to google instruction (firebase console > project setting), to import firebase manually, I had to generate google-sevices.json file which contains configuration details and put it in project tree. But using firebase assistant, there is no json file added to the tree however this tools found the project and says that connected to it.

Should I add google-sevices.json manually or assistant tool resolves it automatically?

答: Which tree are you looking at? The json is added automatically under the "Project Files" tree if you are using the Android Studio Firebase tools, abide the tools are a little outdated.


问:
Trouble With frmMenu.controls( control ) code but for forms
Sorry for the bad title but I do not know how to say this as English is my second language.

I have a form called "frmMenu" with a textbox called "txtName".

I have the code in a module:

```<code>Public Sub TextMenu(ByVal SomeVariable As String)
frmMenu.controls(SomeVariable).text="hi"
end sub
</code>```

I am calling the module with the parameter "txtName" to point to the textbox on the form

if I have many forms with the same textbox name, how can I point to many forms? something similar to the ".controls" code but for forms.

Thank you

答:
You need to loop through all Loaded UserForms in VBA.UserForms collection and on each control on the form.

You can have a function return the control by providing its name.

```<code>Public Function ControlByName(ByVal Name As String) As Object

    Dim f As UserForm, c As Control

    For Each f In VBA.UserForms
        For Each c In f.Controls
            If c.Name = Name Then
                Set ControlByName = f.Controls(Name)
                Exit For
            End If
        Next c
    Next
End Function
</code>```

Then to call it:

```<code>Sub T()

    Dim f As TextBox2
    Set f = ControlByName("TextBox1")

    Debug.Print f.Text

    Dim b As CommandButton
    Set b = ControlByName("CommandButton1")

    Debug.Print b.Caption
End Sub
</code>```

Body:
Sorry for the bad title but I do not know how to say this as English is my second language.

I have a form called "frmMenu" with a textbox called "txtName".

I have the code in a module:

Public Sub TextMenu(ByVal SomeVariable As String)
frmMenu.controls(SomeVariable).text="hi"
end sub

I am calling the module with the parameter "txtName" to point to the textbox on the form

if I have many forms with the same textbox name, how can I point to many forms? something similar to the ".controls" code but for forms.

Thank you

Body:
You need to loop through all Loaded UserForms in VBA.UserForms collection and on each control on the form.

You can have a function return the control by providing its name.

Public Function ControlByName(ByVal Name As String) As Object

    Dim f As UserForm, c As Control

    For Each f In VBA.UserForms
        For Each c In f.Controls
            If c.Name = Name Then
                Set ControlByName = f.Controls(Name)
                Exit For
            End If
        Next c
    Next
End Function

Then to call it:

Sub T()

    Dim f As TextBox2
    Set f = ControlByName("TextBox1")

    Debug.Print f.Text

    Dim b As CommandButton
    Set b = ControlByName("CommandButton1")

    Debug.Print b.Caption
End Sub


问:
git shallow clone to specific tag
I want to clone the Linux kernel repo, but only from version 3.0 onwards, since the kernel repo is so huge it makes my versioning tools run faster if I can do a shallow clone. The core of my question is: how can I tell git what the "n" value is for the --depth parameter? I was hoping this would work:

git clone http://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git --depth v3.0

thanks.

答:
For someone who already has a clone this command will get the number of commits between tip of current branch and the tag v5.2:

```<code>$ git rev-list HEAD ^v5.2 --count
407
</code>```

I found this project implementing rev-list using the GitHub API:
https://github.com/cjlarose/github-rev-list

The very lengthy man page on rev-list indicates there is a lot going on behind the scenes. There are many different paths to possibly count commits through with branches and merges coming and going. For this use case though that can probably be ignored(?)

Title: git shallow clone to specific tag

Body:
For someone who already has a clone this command will get the number of commits between tip of current branch and the tag v5.2:

$ git rev-list HEAD ^v5.2 --count
407

I found this project implementing rev-list using the GitHub API:
https://github.com/cjlarose/github-rev-list

The very lengthy man page on rev-list indicates there is a lot going on behind the scenes. There are many different paths to possibly count commits through with branches and merges coming and going. For this use case though that can probably be ignored(?)


问:
Are some bigquery public datasets no longer available?
When using the BigQuery GUI interface, I'm no longer able to browse the bigquery-public-data.stackoverflow dataset.  It doesn't show up in the Public Datasets dropdown, where I was previously able to view the schema.  On the other hand, I am able to query the table.

Have some public datasets been removed from the GUI?

答: The original issue was due to a bug that caused Pinned Projects to be hidden. It has since been fixed.</p>


问:
How to check if a value doesn't exist in one or more arrays inside array of arrays?
I need to write a function that returns true if a value exists in a multidimensional array and false if the value doesn't exist in atleast one array in the multidimensional array.</p>

```<code>    function isItemOmnipresent (arrayOfArrays, item) {

     var arrays = arrayOfArrays;
     var itemCheck = item;

     for(var i = 0; i < arrays.length; i++){
      for(var j = 0; j < arrays[i].length; j++){
       if(arrays[i][j] == itemCheck) {
         return true;
      } else {
         return false;
      }
    }
  }
</code>```

答:
You could use a function like this one - see this https://jsfiddle.net/jde2urL6/:

```<code>    function isValuePresent(arr, value) {
  var result = false;

  if (Array.isArray(arr)) {
    for (var i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
        result = isValuePresent(arr[i], value);
      }
      else {
        if (arr[i] === value)
          result = true;
      }
    }
  }

  return result;
}
</code>```

As the for loop iterates over each array element in the array it checks to see if that item is an (nested) array and if so the method calls back into itself (recursive) to check if any of the elements within the nested array have a matching value. If the element is not an array the value of that element is checked against the desired "to find" value - if so it sets result to true. I added a "visual" below (the flow starts at the first red horizontal line). I hope that brings a little more clarification.

Body:
I need to write a function that returns true if a value exists in a multidimensional array and false if the value doesn't exist in atleast one array in the multidimensional array.

    function isItemOmnipresent (arrayOfArrays, item) {

     var arrays = arrayOfArrays;
     var itemCheck = item;

     for(var i = 0; i < arrays.length; i++){
      for(var j = 0; j < arrays[i].length; j++){
       if(arrays[i][j] == itemCheck) {
         return true;
      } else {
         return false;
      }
    }
  }

Body:
You could use a function like this one - see this https://jsfiddle.net/jde2urL6/:

    function isValuePresent(arr, value) {
  var result = false;

  if (Array.isArray(arr)) {
    for (var i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
        result = isValuePresent(arr[i], value);
      }
      else {
        if (arr[i] === value)
          result = true;
      }
    }
  }

  return result;
}

As the for loop iterates over each array element in the array it checks to see if that item is an (nested) array and if so the method calls back into itself (recursive) to check if any of the elements within the nested array have a matching value. If the element is not an array the value of that element is checked against the desired "to find" value - if so it sets result to true. I added a "visual" below (the flow starts at the first red horizontal line). I hope that brings a little more clarification.


问:
Java: How to find the second char in a string?
So let say I have a String:

```<code>String line1 = "you can also view my (abbreviated)(resume.html) at lunch.";
</code>```

and another String :

```<code>String line2 = "you can also view my(resume.html) at lunch.";
</code>```

So I'm trying to take the substring of line2 to make the

```<code>line2 = "you can also view my resume.html at lunch."
</code>```

and similarly with line1 so

```<code>line1 = "you can also view my (abbreviated) resume.html at lunch."
</code>```

However when I try to use the code to make the string for line2 which I used for line 1 it has a problem since when I try to find the index of "(" and ")" it read them from (abbreviated) instead of the "(" and ")" from the resume.html.

So for example to change line 1 I would do

```<code>String ax = line1.substring(line1.indexOf("(") + 1, line1.indexOf(")"));
line1 = line1.substring(0,line1.indexOf("(")) + ax + line1.substring(line1.indexOf(")");
</code>```

However when i do something similar for the first line it messes up.

I need help to write a single method or way that works for both of them.

答:
Just use the ((lastIndexOf)) method instead of ((indexOf)) method, will look like this:</p>

```<code>    String ax = line1.substring(line1.lastIndexOf("(") + 1, line1.lastIndexOf(")"));
    line1 = line1.substring(0,line1.lastIndexOf("(")) + ax +line1.substring(line1.lastIndexOf(")");
</code>```

Body:
So let say I have a String:

String line1 = "you can also view my (abbreviated)(resume.html) at lunch.";

and another String :

String line2 = "you can also view my(resume.html) at lunch.";

So I'm trying to take the substring of line2 to make the

line2 = "you can also view my resume.html at lunch."

and similarly with line1 so

line1 = "you can also view my (abbreviated) resume.html at lunch."

However when I try to use the code to make the string for line2 which I used for line 1 it has a problem since when I try to find the index of "(" and ")" it read them from (abbreviated) instead of the "(" and ")" from the resume.html.

So for example to change line 1 I would do

String ax = line1.substring(line1.indexOf("(") + 1, line1.indexOf(")"));
line1 = line1.substring(0,line1.indexOf("(")) + ax + line1.substring(line1.indexOf(")");

However when i do something similar for the first line it messes up.

I need help to write a single method or way that works for both of them.

Body:
Just use the ((lastIndexOf)) method instead of ((indexOf)) method, will look like this:

    String ax = line1.substring(line1.lastIndexOf("(") + 1, line1.lastIndexOf(")"));
    line1 = line1.substring(0,line1.lastIndexOf("(")) + ax +line1.substring(line1.lastIndexOf(")");


问:
Create a cocoa button that accepts keyboard input
Hey everyone, thanks for all your help so far, I've learned a whole lot in a short amount of time.

What I've done so far is to create a small calculator program and it works nicely.  To complete this version of it, what I'd like to do is make my "keys" on the calculator interface accept input from my keyboard presses.  So, for example, if I want to add 2 and 4, instead of clicking my "2" and "4" buttons, I can just press them on my numeric keypad instead.

I know it has something to do with giving my buttons focus but I can't figure out how to make them respond to keydown events.

I'm looking around on the apple developer documentation as well, so if I find the answers before you guys can then I'll try what I find out, and if it doesn't work I'll post with my progress.

Again, thanks everyone for your help!

答: You can set the key equivalent in interface builder. Click on the button in interface builder open the inspector and open it to the first tab. Under the first section there is a Key Equiv: and a gray box you can click on. Click on it and press the key you want to press it.


问:
How to change currently active window tab color in atom editor
I'm using atom editor version 1.0 stable in ubuntu 14.04.
my question is,
How can I change the background colour of currently selected window tab...
(means current tab..)
by editing style.less file?

I tried,

.tab{ background-color:black; }
```

to change the tab color,

but,
this code only changed all tab colors except current tab color.

So my question is, how can I change the color of current tab in atom editor by editing style.less file?

答:
None of these worked for me. Here was my solution (Atom 1.22.1):</p>

```<code>.tab-bar .tab.active[data-type$="Editor"] {
 background-color: #167373;
}
</code>```

Body:
I'm using atom editor version 1.0 stable in ubuntu 14.04.
my question is,
How can I change the background colour of currently selected window tab...
(means current tab..)
by editing style.less file?

I tried,

.tab{ background-color:black; }

to change the tab color,

but,
this code only changed all tab colors except current tab color.

So my question is, how can I change the color of current tab in atom editor by editing style.less file?

Body:
None of these worked for me. Here was my solution (Atom 1.22.1):

.tab-bar .tab.active[data-type$="Editor"] {
 background-color: #167373;
}


问:
OpenStreetMap Requests with Unprecise GPS Position from QtLocation
I am using OSM (OpenStreetMap) plugin for Qt 5.9, to make route calculation in my desktop application.

I have an OSRM local server running that receives the requests from the application.

I noticed a weird flickering in route calculations, and found out that the request hitting the server side does not have the precise GPS coordinates that I passed to the QGeoRoutingManager::calculateRoute request.

The coordinates are only 3-4 decimal places, while the original request had 7 decimal places for the GPS points.

This imprecision causes a drift in position (causing often placement on the other direction of the road), and thus result in a jump in route calculation.

Is there some way to set the precision?

答:
It's a bug in QT, I had to download the source files, and rebuild it.

The bug is how the routingUrl appends the GPS lat/long in the request URL in the function QGeoRouteParserOsrmV5Private::requestUrl in file qgeorouteparseosrmv5.cpp


问:
How to use Sugar ORM?
I am developing one application and now I need to use database in my application. I wanna use Sugar ORM, but I didn't find "actual" documentation and "actual" version on Maven (I found 1.3 and 1.4 versions). Can somebody share information or links about Sugar ORM?

For example, when I create a model I take error cause class SugarRecord doesn't exist

答:
First install the sugar orm by adding the line below to your to your module level gradle dependencies and then sync your project:

```<code>compile 'com.github.satyan:sugar:1.5'
</code>```

You then have to specify SugarApp as your application class by changing the android name attribute in your application tag. Also, you need to include some meta data about your database such as your database name, version etc. Your manifest file should look something like this:

```<code><application
        android:name="com.orm.SugarApp"
        android:allowBackup="true"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data android:name="DATABASE" android:value="sugar_example.db" />
        <meta-data android:name="VERSION" android:value="1" />
        <meta-data android:name="QUERY_LOG" android:value="true" />
        <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.kwabenaberko" />
    </application>
</code>```

All your data models that you want to persist need to extend SugarRecord and also have at least an empty default constructor:

```<code>import com.orm.SugarRecord;

public class Developer extends SugarRecord{
    private String firstname;
    private String lastname;
    private String favouriteLanguage;

    public Developer(){

    }

    public Developer(String firstname, String lastname, String favouriteLanguage){
        this.firstname = firstname;
        this.lastname = lastname;
        this.favouriteLanguage = favouriteLanguage;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getFavouriteLanguage() {
        return favouriteLanguage;
    }

    public void setFavouriteLanguage(String favouriteLanguage) {
        this.favouriteLanguage = favouriteLanguage;
    }
}
</code>```

Then insert a new record like this:

```<code>Developer developer = new Developer("Kwabena", "Berko", "JavaScript");
developer.save();
</code>```

I wrote an article on https://dev.to, describing the use of Sugar ORM in much more detail:
https://dev.to/kwabenberko/sugar-orm-an-easier-way-to-work-with-sqlite-databases-in-android-cpg

Title: How to use Sugar ORM?

Body:
First install the sugar orm by adding the line below to your to your module level gradle dependencies and then sync your project:

compile 'com.github.satyan:sugar:1.5'

You then have to specify SugarApp as your application class by changing the android name attribute in your application tag. Also, you need to include some meta data about your database such as your database name, version etc. Your manifest file should look something like this:

<application
        android:name="com.orm.SugarApp"
        android:allowBackup="true"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data android:name="DATABASE" android:value="sugar_example.db" />
        <meta-data android:name="VERSION" android:value="1" />
        <meta-data android:name="QUERY_LOG" android:value="true" />
        <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.kwabenaberko" />
    </application>

All your data models that you want to persist need to extend SugarRecord and also have at least an empty default constructor:

import com.orm.SugarRecord;

public class Developer extends SugarRecord{
    private String firstname;
    private String lastname;
    private String favouriteLanguage;

    public Developer(){

    }

    public Developer(String firstname, String lastname, String favouriteLanguage){
        this.firstname = firstname;
        this.lastname = lastname;
        this.favouriteLanguage = favouriteLanguage;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getFavouriteLanguage() {
        return favouriteLanguage;
    }

    public void setFavouriteLanguage(String favouriteLanguage) {
        this.favouriteLanguage = favouriteLanguage;
    }
}

Then insert a new record like this:

Developer developer = new Developer("Kwabena", "Berko", "JavaScript");
developer.save();

I wrote an article on https://dev.to, describing the use of Sugar ORM in much more detail:
https://dev.to/kwabenberko/sugar-orm-an-easier-way-to-work-with-sqlite-databases-in-android-cpg


问:
Converting Cisco CDR DateTime and Duration in SSRS
I am creating a report in SSRS that pulls data including Call Date and Duration from a table with Cisco CDR data. Both fields store the data as a bigint datatype. I understand that the Date/Time field is Unix Epoch Time.

My challenge is that I need to display the date/time and duration correctly in the report but I am not sure how to create the appropriate expression in SSRS to accomplish this. I will also need to enable the user to run the report by entering Start and End Date parameters. I would greatly appreciate some assistance

Body:
You can use

DATEADD(s, epoch, '1970-01-01 00:00:00')


问:
Object oriented coding in a multi threaded request environment - PHP
I am writing a web application in an object oriented design. This application would be interacting with the database pretty often. A few regular operations are verifying a user's ACL permissions for the function/method requested, performing certain functions etc. In a nutshell, the database would be used a lot. So my question here is, if I do develop my application using OOP, and declare class level variables which would be used to set the input coming in, and if there is any parallel or concurrent request coming in from another user, would the input data be changed??

Would I have to do something separate to make sure that the application is multi-threaded and the input coming in be not changed until the process isn't finished??

ex:

```<code>class myProces{
var $input1;
var $input2;

    function process1($ip1, $ip2){
      $this->input1 = $ip1;
      $this->input2 = $ip2;
      $this->getDataDB();
    }

    function getDataDB(){
     //do some database activity with the class level variables;
     // I would pass the values in the class level variables;
    $query = "select column from table where col1 = $this->input1 and col2= $this->input2";

    mysql_query($query);

    return something;
    }

}
</code>```

Now if I have two users hitting my application at the same time, and make a call to the functions in this class

user1:
$obj = new myProces();
$obj->process1(1,2);

user2:
$obj = new myProces();
$obj->process1(5,6);

Now if I do have class level variables, would they have changed values when concurrent requests come in?? Would PHP doing any kind of handling for multi threading? I am not sure if Apache can act as a message queue, where requests can be queued.

Can anybody explain if OOP for web applications with heavy number of users is good or if any kind of multithreading has to be done by developers??

答: There is no need to worry about mixing things up on the PHP side, but when you come up with a need to update or insert data, having several users being able to modify the same subset of data will lead you into unwanted consequences. Such as inserting duplicate rows or modifying the same row. Thus, you need to use SQL commands such as locking tables or rows.</p>

Body:
I am writing a web application in an object oriented design. This application would be interacting with the database pretty often. A few regular operations are verifying a user's ACL permissions for the function/method requested, performing certain functions etc. In a nutshell, the database would be used a lot. So my question here is, if I do develop my application using OOP, and declare class level variables which would be used to set the input coming in, and if there is any parallel or concurrent request coming in from another user, would the input data be changed??

Would I have to do something separate to make sure that the application is multi-threaded and the input coming in be not changed until the process isn't finished??

ex:

class myProces{
var $input1;
var $input2;

    function process1($ip1, $ip2){
      $this->input1 = $ip1;
      $this->input2 = $ip2;
      $this->getDataDB();
    }

    function getDataDB(){
     //do some database activity with the class level variables;
     // I would pass the values in the class level variables;
    $query = "select column from table where col1 = $this->input1 and col2= $this->input2";

    mysql_query($query);

    return something;
    }

}

Now if I have two users hitting my application at the same time, and make a call to the functions in this class

user1:
$obj = new myProces();
$obj->process1(1,2);

user2:
$obj = new myProces();
$obj->process1(5,6);

Now if I do have class level variables, would they have changed values when concurrent requests come in?? Would PHP doing any kind of handling for multi threading? I am not sure if Apache can act as a message queue, where requests can be queued.

Can anybody explain if OOP for web applications with heavy number of users is good or if any kind of multithreading has to be done by developers??


问:
How to revert the build in Teamcity after the CI tests failed
I am using TeamCity for my CI integration and TFS as my code repo. We trigger a build to deploy the code changes on every check-in by devs. Once this build is successful, then we trigger another build configuration which runs some sanity tests which are managed by automation team and not the unit tests. Now when any test in this build fails, I want to revert the check-in made by the dev's implying there was a problem in the application with the latest code and previously successful build to be redeployed.</p>

答:
It sounds like you want to use TC Delayed Commit Feature.

Delayed Commit Overview Page

Delayed Commit Documentation


问:
How to read test data when running test-kitchen during Chef converge
I have a recipe that updates the Splunk /opt/splunkforwarder/etc/system/local/inputs.conf file with single entry for meta data that needs to be added to the events that are being forwarded to the indexers.

This meta data entry is a nine character text entry in a configuration file of another piece of software that has already been installed on the host.

I have the code to read the data from this file but when it comes to running test-kitchen I don't know how to declare where the test file that has this information is located in my .kitchen.yml file.

I've tried creating a directory at the root of my repo with this file in it thinking it would be copied over like the roles, environments, cookbook directories are so my .kitchen.yml contained an entry:

```<code>    attributes:
      splunk:
        sliceconf_path: test/slice.conf
</code>```

However I would get an error like

```<code>Errno::ENOENT
       -------------
       No such file or directory @ rb_sysopen - test/slice.conf
</code>```

I've tried many other locations but I still can't get it to find this file. It will get copied over if I put it in "files/test/slice.conf" but then it still can't find it if I declare the path either

```<code>sliceconf_path: files/test/slice.conf
</code>```

or (based on examining the directory structure of the Docker image I'm using for Test-Kitchen)

```<code>cookbooks/cookbook-dh_rainbow_forwarders/files/test/slice.conf
</code>```

I'm stumped as to how to get Chef/Test-Kitchen to find the file.

----------------EDIT-------------------

Here's the code I'm using just to clarify:

```<code>Recipe
slice_name = ''
ruby_block 'read_slice_conf' do
  block do
    slice_name = File.read("#{node['sliceconf_path']}").chomp
  end
end

# Update local input conf file with meta-data about slice.
 template '/opt/splunkforwarder/etc/system/local/inputs.conf' do
   source 'system_local_inputs.erb'
   owner 'nobody'
   group 'nobody'
  mode 0o600
  mode '0600'
   action :create
  variables(
    slice_decorators: slice_name
  )
 end

Template
[default]
host = <%= node['fqdn'] %>

_meta = slice::#{slice_name}
</code>```

Where I've set the node attribute (node['sliceconf_path']) in my .kitchen.yml

答: It sounds like you are doing something like IO.read(node['splunk']['sliceconf_path']), meaning it has to be an absolute path on the target VM, it would have no knowledge of Chef-y things like you are giving it. But That attribute doesn't exist in the community splunk cookbook so I can't tell how the code works. If you want it to automatically understand cookbook_files, you'll need to write the code for that.

Body:
I have a recipe that updates the Splunk /opt/splunkforwarder/etc/system/local/inputs.conf file with single entry for meta data that needs to be added to the events that are being forwarded to the indexers.

This meta data entry is a nine character text entry in a configuration file of another piece of software that has already been installed on the host.

I have the code to read the data from this file but when it comes to running test-kitchen I don't know how to declare where the test file that has this information is located in my .kitchen.yml file.

I've tried creating a directory at the root of my repo with this file in it thinking it would be copied over like the roles, environments, cookbook directories are so my .kitchen.yml contained an entry:

    attributes:
      splunk:
        sliceconf_path: test/slice.conf

However I would get an error like

Errno::ENOENT
       -------------
       No such file or directory @ rb_sysopen - test/slice.conf

I've tried many other locations but I still can't get it to find this file. It will get copied over if I put it in "files/test/slice.conf" but then it still can't find it if I declare the path either

sliceconf_path: files/test/slice.conf

or (based on examining the directory structure of the Docker image I'm using for Test-Kitchen)

cookbooks/cookbook-dh_rainbow_forwarders/files/test/slice.conf

I'm stumped as to how to get Chef/Test-Kitchen to find the file.

----------------EDIT-------------------

Here's the code I'm using just to clarify:

Recipe
slice_name = ''
ruby_block 'read_slice_conf' do
  block do
    slice_name = File.read("#{node['sliceconf_path']}").chomp
  end
end

# Update local input conf file with meta-data about slice.
 template '/opt/splunkforwarder/etc/system/local/inputs.conf' do
   source 'system_local_inputs.erb'
   owner 'nobody'
   group 'nobody'
  mode 0o600
  mode '0600'
   action :create
  variables(
    slice_decorators: slice_name
  )
 end

Template
[default]
host = <%= node['fqdn'] %>

_meta = slice::#{slice_name}

Where I've set the node attribute (node['sliceconf_path']) in my .kitchen.yml


问:
Angular 5 testing code in module constructor
I'm trying to test code that's in one of my module's constructor. Basically, the module (named GraphqlModule) configures a service (named Graphql) and provides it. The configuration happens in the module's constructor.

Here's the code I use to test the module.

```<code>it('should use the GraphqlConfigs and ServerConfigs', (done: DoneFn) => {

    // Adding spies to Config classes
    let serverConfigs = new ServerConfigs();
    let serverDomainSpy = spyOnProperty(serverConfigs, 'ServerDomain', 'get').and.callThrough();
    let serverPortSpy = spyOnProperty(serverConfigs, 'ServerPort', 'get').and.callThrough();

    let gqlConfigs = new GraphqlConfigs();
    let protocolSpy = spyOnProperty(gqlConfigs, 'EndpointProtocol', 'get').and.callThrough();
    let endpointNameSpy = spyOnProperty(gqlConfigs, 'EndpointName', 'get').and.callThrough();

    TestBed.configureTestingModule({
        imports: [ GraphqlModule ],
        providers: [
            {provide: ServerConfigs, useValue: serverConfigs}, // Replacing real config classes with the ones spied on.
            {provide: GraphqlConfigs, useValue: gqlConfigs}
        ]

    }).compileComponents().then(() => {

        // This line seems to make Angular instantiate GraphqlModule
        const graphql = TestBed.get(Graphql) as Graphql;

        expect(serverDomainSpy.calls.count()).toBe(1, 'ServerConfigs.ServerDomain was not used.');
        expect(serverPortSpy.calls.count()).toBe(1,  'ServerConfigs.ServerPort was not used.');

        expect(protocolSpy.calls.count()).toBe(1, 'GraphqlConfigs.EndpointProtocol was not used.');
        expect(endpointNameSpy.calls.count()).toBe(1,  'GraphqlConfigs.EndpointName was not used.');

        done();
    });
});
</code>```

As is, the test passes and works, but if I dont use the following (useless) line const graphql = TestBed.get(Graphql) as Graphql; the GraphqlModule gets instantiated after the test has been executed, which makes the test fail.

Since it's GraphqlModule that provides the Graphql service, I understand that there's some lazy loading algorithm in Angular that's triggered when I do TestBed.get(Graphql). That's fine... my question is, is there a way to make my module load in a more explicit way?

Here's the GraphqlModule class definition:

```<code>imports...

@NgModule({
    imports: [
        CommonModule,
        HttpClientModule,
        ApolloModule,
        HttpLinkModule
    ],
    declarations: [],

    providers: [
        Graphql, // Is an alias for Apollo
        GraphqlConfigs
    ]
})
export class GraphqlModule {

    constructor(
        @Optional() @SkipSelf() parentModule: GraphqlModule,
        graphql: Graphql,
        httpLink: HttpLink,
        serverConfigs: ServerConfigs,
        graphqlConfigs: GraphqlConfigs
    ) {

        // Making sure this is not imported twice.
        // https://angular.io/guide/ngmodule#prevent-reimport-of-the-coremodule
        if (parentModule) {
            throw new Error(
                'GraphqlModule is already loaded. Import it in the '+CoreModule.name+' only.');
        }

        // Gql setup:

        const gqlHttpLink = httpLink.create({
            uri: GraphqlModule.buildEndpointUrl(serverConfigs, graphqlConfigs)
        });

        graphql.create({
            link: gqlHttpLink,
            cache: new InMemoryCache(),
        });
    }

    private static buildEndpointUrl(serverConfigs: ServerConfigs, graphqlConfigs: GraphqlConfigs): string {

        return graphqlConfigs.EndpointProtocol +                            // eg. http://
            serverConfigs.ServerDomain+":"+serverConfigs.ServerPort+'/' +   // eg. example.com:80/
            graphqlConfigs.EndpointName;                                    // eg. graphql
    }
}
</code>```

答:
Graphql is already instantiated in GraphqlModule constructor for root injector, and GraphqlModule is eagerly instantiated when it's specified in TestBed imports. There's no lazy loading involved.

As it's explained in this answer, TestBed injector is instantiated on first inject callback call, or TestBed.get, or TestBed.createComponent call. The injector doesn't exist until the first injection, so don't any module or provider instances. Since almost all TestBed tests perform at least one of these calls in it or beforeEach, this issue usually never appears.

Since graphql instance isn't needed in this test, in order for the test to pass it can be just:

```<code>TestBed.get(Injector);
</code>```

Or:

```<code>TestBed.get(TestBed);
</code>```

Also, .compileComponents().then(() => { ... }) and done() are unnecessary, the test doesn't involve components and is synchronous.

The fact that the injector needs to be instantiated manually suggests that TestBed isn't required for this test, although it's beneficial because this way GraphqlModule constructor DI annotation can be tested, including the one for parentModule.

Body:
I'm trying to test code that's in one of my module's constructor. Basically, the module (named GraphqlModule) configures a service (named Graphql) and provides it. The configuration happens in the module's constructor.

Here's the code I use to test the module.

it('should use the GraphqlConfigs and ServerConfigs', (done: DoneFn) => {

    // Adding spies to Config classes
    let serverConfigs = new ServerConfigs();
    let serverDomainSpy = spyOnProperty(serverConfigs, 'ServerDomain', 'get').and.callThrough();
    let serverPortSpy = spyOnProperty(serverConfigs, 'ServerPort', 'get').and.callThrough();

    let gqlConfigs = new GraphqlConfigs();
    let protocolSpy = spyOnProperty(gqlConfigs, 'EndpointProtocol', 'get').and.callThrough();
    let endpointNameSpy = spyOnProperty(gqlConfigs, 'EndpointName', 'get').and.callThrough();

    TestBed.configureTestingModule({
        imports: [ GraphqlModule ],
        providers: [
            {provide: ServerConfigs, useValue: serverConfigs}, // Replacing real config classes with the ones spied on.
            {provide: GraphqlConfigs, useValue: gqlConfigs}
        ]

    }).compileComponents().then(() => {

        // This line seems to make Angular instantiate GraphqlModule
        const graphql = TestBed.get(Graphql) as Graphql;

        expect(serverDomainSpy.calls.count()).toBe(1, 'ServerConfigs.ServerDomain was not used.');
        expect(serverPortSpy.calls.count()).toBe(1,  'ServerConfigs.ServerPort was not used.');

        expect(protocolSpy.calls.count()).toBe(1, 'GraphqlConfigs.EndpointProtocol was not used.');
        expect(endpointNameSpy.calls.count()).toBe(1,  'GraphqlConfigs.EndpointName was not used.');

        done();
    });
});

As is, the test passes and works, but if I dont use the following (useless) line const graphql = TestBed.get(Graphql) as Graphql; the GraphqlModule gets instantiated after the test has been executed, which makes the test fail.

Since it's GraphqlModule that provides the Graphql service, I understand that there's some lazy loading algorithm in Angular that's triggered when I do TestBed.get(Graphql). That's fine... my question is, is there a way to make my module load in a more explicit way?

Here's the GraphqlModule class definition:

imports...

@NgModule({
    imports: [
        CommonModule,
        HttpClientModule,
        ApolloModule,
        HttpLinkModule
    ],
    declarations: [],

    providers: [
        Graphql, // Is an alias for Apollo
        GraphqlConfigs
    ]
})
export class GraphqlModule {

    constructor(
        @Optional() @SkipSelf() parentModule: GraphqlModule,
        graphql: Graphql,
        httpLink: HttpLink,
        serverConfigs: ServerConfigs,
        graphqlConfigs: GraphqlConfigs
    ) {

        // Making sure this is not imported twice.
        // https://angular.io/guide/ngmodule#prevent-reimport-of-the-coremodule
        if (parentModule) {
            throw new Error(
                'GraphqlModule is already loaded. Import it in the '+CoreModule.name+' only.');
        }

        // Gql setup:

        const gqlHttpLink = httpLink.create({
            uri: GraphqlModule.buildEndpointUrl(serverConfigs, graphqlConfigs)
        });

        graphql.create({
            link: gqlHttpLink,
            cache: new InMemoryCache(),
        });
    }

    private static buildEndpointUrl(serverConfigs: ServerConfigs, graphqlConfigs: GraphqlConfigs): string {

        return graphqlConfigs.EndpointProtocol +                            // eg. http://
            serverConfigs.ServerDomain+":"+serverConfigs.ServerPort+'/' +   // eg. example.com:80/
            graphqlConfigs.EndpointName;                                    // eg. graphql
    }
}

Body:
Graphql is already instantiated in GraphqlModule constructor for root injector, and GraphqlModule is eagerly instantiated when it's specified in TestBed imports. There's no lazy loading involved.

As it's explained in this answer, TestBed injector is instantiated on first inject callback call, or TestBed.get, or TestBed.createComponent call. The injector doesn't exist until the first injection, so don't any module or provider instances. Since almost all TestBed tests perform at least one of these calls in it or beforeEach, this issue usually never appears.

Since graphql instance isn't needed in this test, in order for the test to pass it can be just:

TestBed.get(Injector);

Or:

TestBed.get(TestBed);

Also, .compileComponents().then(() => { ... }) and done() are unnecessary, the test doesn't involve components and is synchronous.

The fact that the injector needs to be instantiated manually suggests that TestBed isn't required for this test, although it's beneficial because this way GraphqlModule constructor DI annotation can be tested, including the one for parentModule.


问:
Is it possible to limit the length of a string column in my seed.rb file in Rails?
UPDATE: i meant in my creates_coves.rb file in db/migrate, not seeds.rb

In my seed.rb file I have:

```<code>class CreateCoves < ActiveRecord::Migration
  def self.up
    create_table :coves do |t|
      t.string :title, :limit=>9,:null =>false

      t.timestamps
    end
  end

  def self.down
    drop_table :coves
  end
end
</code>```

After I run rake db:migrate, I'm still able to create new objects with titles longer than 9 characters, and empty characters too.  Why isn't the limit or null working?

答:
You'll need to use validations...

Rails 3 Validations

```<code># model.rb
validates :field, :presence => true, :length => {:minimum => 1, :maximum => 9}
</code>```

On another note, WHY are you using seeds.rb for this? This is a migration

Body:
UPDATE: i meant in my creates_coves.rb file in db/migrate, not seeds.rb

In my seed.rb file I have:

class CreateCoves < ActiveRecord::Migration
  def self.up
    create_table :coves do |t|
      t.string :title, :limit=>9,:null =>false

      t.timestamps
    end
  end

  def self.down
    drop_table :coves
  end
end

After I run rake db:migrate, I'm still able to create new objects with titles longer than 9 characters, and empty characters too.  Why isn't the limit or null working?

Body:
You'll need to use validations...

Rails 3 Validations

# model.rb
validates :field, :presence => true, :length => {:minimum => 1, :maximum => 9}

On another note, WHY are you using seeds.rb for this? This is a migration


问:
Evaluating Binary expressions into Hexadecimals by hand
I had to take a quiz on bit's and all questions below are what I got wrong with correct answer displayed. I'm here because I need guidance on how to get these answers.

Evaluate each stated binary expression; assume the data type of all values are unsigned char. All answers must be stated as hexadecimal values.

For this question, I got 48. My reasoning behind this was that the starting bit value was 3. 011 and we shift it over to the left 4 places and got my answer (albeit wrong).

```<code>3 << 4         // Correct Answer is 30
</code>```

Everything below here I had absolutely no clue what I was doing or how these answers were achieved.  The only thing that I can speak of is that each uppercase letter has some assigned bit value to them like A - 10, B - 11, C - 12, etc. and that the & is sort of like a mask that converts bits from 1's to 0's if both bits column's being compared aren't both 1.

```<code>0xD7 & 0x3D    // Correct Answer is 15
               // How do you read 0xD7 and 0x3D in bits?

~0xBB          // Correct Answer 44

(3 | 5) << 1   // Correct Answer is 0E
</code>```

I have an exam coming up and I can't arrange a meeting with my teacher with my given time. Any help would be greatly appreciated! :)

EDITED: 0xBB | 0x44 , my answer was right. I misread his pen marking.

答:
For the expression 0xD7 & 0x3D, first convert to binary.  Remember, each hexadecimal digit is 4 binary digits:

```<code>11010111 (0xD7)
00111101 (0x3D
</code>```

The truth table for the AND operation (&) is:

```<code>1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0
</code>```

Applying the rules:

```<code>1 1 0 1 0 1 1 1 (0xD7)
0 0 1 1 1 1 0 1 (0x3D)
===============
0 0 0 1 0 1 0 1 (0x15)
</code>```

Body:
I had to take a quiz on bit's and all questions below are what I got wrong with correct answer displayed. I'm here because I need guidance on how to get these answers.

Evaluate each stated binary expression; assume the data type of all values are unsigned char. All answers must be stated as hexadecimal values.

For this question, I got 48. My reasoning behind this was that the starting bit value was 3. 011 and we shift it over to the left 4 places and got my answer (albeit wrong).

3 << 4         // Correct Answer is 30

Everything below here I had absolutely no clue what I was doing or how these answers were achieved.  The only thing that I can speak of is that each uppercase letter has some assigned bit value to them like A - 10, B - 11, C - 12, etc. and that the & is sort of like a mask that converts bits from 1's to 0's if both bits column's being compared aren't both 1.

0xD7 & 0x3D    // Correct Answer is 15
               // How do you read 0xD7 and 0x3D in bits?

~0xBB          // Correct Answer 44

(3 | 5) << 1   // Correct Answer is 0E

I have an exam coming up and I can't arrange a meeting with my teacher with my given time. Any help would be greatly appreciated! :)

EDITED: 0xBB | 0x44 , my answer was right. I misread his pen marking.

Body:
For the expression 0xD7 & 0x3D, first convert to binary.  Remember, each hexadecimal digit is 4 binary digits:

11010111 (0xD7)
00111101 (0x3D

The truth table for the AND operation (&) is:

1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0

Applying the rules:

1 1 0 1 0 1 1 1 (0xD7)
0 0 1 1 1 1 0 1 (0x3D)
===============
0 0 0 1 0 1 0 1 (0x15)