问:
What's a fast way to space-out bits within a word?
I have a 32-bit value in the lower part of a 64-bit register; the top part is 0's. Letting X denote a bit with information and with bits listed from LSB to MSB, here's what it looks like:

```<code>X X X  ...  X 0 0 0 0 ... 0
</code>```

Now, I want to "space out" the bits with information, so that I have

```<code>X 0 X 0 X 0 ... X 0
</code>```

(or if you'd rather put the 0's first, then

```<code>0 X 0 X 0 X 0 ... X
</code>```

is fine too.)

What's a fast way to do that?

A multi-CPU-architecture-relevant answer would be nice, but something specific to Intel x86_64 and/or nVIDIA Pascal SM's would be the most relevant.

答:
This is known as Morton number, which is a specific case of parallel expand which is in turn the reverse of compress right in the following questions

What's the fastest way to pack 32 0/1 values into the bits of a single 32-bit variable?

Shift masked bits to the lsb

One general solution might be

uint64_t bit_expand(uint64_t x)
{
    // Input:  00000000ABCDEFGH, each character is a nibble
    x = ((x & 0xFFFF0000) << 32) | ((x & 0x0000FFFF) << 16);
    // Result: ABCD0000EFGH0000
    x = (x & 0xFF000000FF000000) | ((x & 0x00FF000000FF0000) >> 8);
    // Result: AB00CD00EF00GH00
    x = (x & 0xF000F000F000F000) | ((x & 0x0F000F000F000F00) >> 4);
    // Result: A0B0C0D0E0F0G0H0. Each byte: abcd0000
    x = (x & 0xC0C0C0C0C0C0C0C0) | ((x & 0x3030303030303030) >> 2);
    // Result:                   Each byte: ab00cd00
    x = (x & 0x8888888888888888) | ((x & 0x4444444444444444) >> 1);
    // Result:                   Each byte: a0b0c0d0
    return x;
}
```
<p>However the constant generation might be inefficient on RISC architectures because the 64-bit immediate can't be stored in a single instruction like on x86. Even on x86 the output assembly is quite long. Here is another possible implementation as described on Bit Twiddling Hacks</p>
<pre class="lang-c prettyprint-override"><code>static const unsigned int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF};
static const unsigned int S[] = {1, 2, 4, 8};

unsigned int x; // Interleave lower 16 bits of x and y, so the bits of x
unsigned int y; // are in the even positions and bits from y in the odd;
unsigned int z; // z gets the resulting 32-bit Morton Number.
                // x and y must initially be less than 65536.

x = (x | (x << S[3])) & B[3];
x = (x | (x << S[2])) & B[2];
x = (x | (x << S[1])) & B[1];
x = (x | (x << S[0])) & B[0];

y = (y | (y << S[3])) & B[3];
y = (y | (y << S[2])) & B[2];
y = (y | (y << S[1])) & B[1];
y = (y | (y << S[0])) & B[0];

z = x | (y << 1);
</code>```

A lookup table can also be used

#define EXPAND4(a) ((((a) & 0x8) << 4) | (((a) & 0x4) << 2) \
                  | (((a) & 0x2) << 1) | (((a) & 0x1)))

const uint8_t LUT[16] = {
    EXPAND4( 0), EXPAND4( 1), EXPAND4( 2), EXPAND4( 3),
    EXPAND4( 4), EXPAND4( 5), EXPAND4( 6), EXPAND4( 7),
    EXPAND4( 8), EXPAND4( 9), EXPAND4(10), EXPAND4(11),
    EXPAND4(12), EXPAND4(13), EXPAND4(14), EXPAND4(15)
};

output = ((uint64_t)LUT[(x >> 28) & 0xF] << 56) | ((uint64_t)LUT[(x >> 24) & 0xF] << 48)
       | ((uint64_t)LUT[(x >> 20) & 0xF] << 40) | ((uint64_t)LUT[(x >> 16) & 0xF] << 32)
       | ((uint64_t)LUT[(x >> 12) & 0xF] << 24) | ((uint64_t)LUT[(x >>  8) & 0xF] << 16)
       | ((uint64_t)LUT[(x >>  4) & 0xF] <<  8) | ((uint64_t)LUT[(x >>  0) & 0xF] <<  0);
```
<p>The size of the lookup table may be increased if necessary</p>
<hr />
<p>On x86 with BMI2 there's hardware support with PDEP instruction which can be accessed via the following intrinsic</p>
<pre class="lang-c prettyprint-override"><code>output = _pdep_u64(x, 0xaaaaaaaaaaaaaaaaULL);
</code>```

Another solution on architectures without bit deposit/expand instruction but with fast multipliers

uint64_t spaceOut8bits(uint8_t b)
{
    uint64_t MAGIC = 0x8040201008040201;
    uint64_t MASK  = 0x8080808080808080;
    uint64_t expand8bits = htobe64(((MAGIC*b) & MASK) >> 7);
    uint64_t spacedOutBits = expand8bits*0x41041 & 0xAA000000AA000000;
    return (spacedOutBits | (spacedOutBits << 24)) & 0xFFFF000000000000;
}

uint64_t spaceOut64bits(uint64_t x)
{
    return (spaceOut8bits(x >> 24) >>  0)
         | (spaceOut8bits(x >> 16) >> 16)
         | (spaceOut8bits(x >>  8) >> 32)
         | (spaceOut8bits(x >>  0) >> 48);
}
```
<p>The way it works is like this</p>
<ul>
<li>The first step expands the input bits from <code>abcdefgh</code> to <em><strong>a0000000 b0000000 c0000000 d0000000 e0000000 f0000000 g0000000 h0000000</strong></em> and store in <code>expand8bits</code></li>
<li>Then we move those spaced out bits close together by multiplying and masking in the next step. After that <code>spacedOutBits</code> will contain <em><strong>a0b0c0d0 00000000 00000000 00000000 e0f0g0h0 00000000 00000000 00000000</strong></em>. We'll merge the two bytes in the result together</li>
</ul>
<p>The magic number for bringing the bits closer is calculated like this</p>
<pre class="lang-c prettyprint-override"><code>  a0000000b0000000c0000000d0000000e0000000f0000000g0000000h0000000
×                                              1000001000001000001
  ────────────────────────────────────────────────────────────────
  a0000000b0000000c0000000d0000000e0000000f0000000g0000000h0000000
  00b0000000c0000000d0000000e0000000f0000000g0000000h0000000
+ 0000c0000000d0000000e0000000f0000000g0000000h0000000
  000000d0000000e0000000f0000000g0000000h0000000
  ────────────────────────────────────────────────────────────────
  a0b0c0d0b0c0d0e0c0d0e0f0d0e0f0g0e0f0g0h0f0g0h000g0h00000h0000000
& 1010101000000000000000000000000010101010000000000000000000000000
  ────────────────────────────────────────────────────────────────
  a0b0c0d0000000000000000000000000e0f0g0h0000000000000000000000000
</code>```

The output assembly can be seen here. You can change the compiler to see how it's done on various architectures

There's also an alternative way on the Bit Twiddling Hacks page

z = ((x * 0x0101010101010101ULL & 0x8040201008040201ULL) *
     0x0102040810204081ULL >> 49) & 0x5555 |
    ((y * 0x0101010101010101ULL & 0x8040201008040201ULL) *
     0x0102040810204081ULL >> 48) & 0xAAAA;
```

More solutions can be found in Portable efficient alternative to PDEP without using BMI2?

Related: How to do bit striping on pixel data?

As you can see, without the availability of a bit deposit instruction it'll be quite complex in terms of operations. If you do a not of bit striping like this then it'll be better to do in parallel using SIMD

Body:
I have a 32-bit value in the lower part of a 64-bit register; the top part is 0's. Letting X denote a bit with information and with bits listed from LSB to MSB, here's what it looks like:

X X X  ...  X 0 0 0 0 ... 0

Now, I want to "space out" the bits with information, so that I have

X 0 X 0 X 0 ... X 0

(or if you'd rather put the 0's first, then

0 X 0 X 0 X 0 ... X

is fine too.)

What's a fast way to do that?

A multi-CPU-architecture-relevant answer would be nice, but something specific to Intel x86_64 and/or nVIDIA Pascal SM's would be the most relevant.

Body:
This is known as Morton number, which is a specific case of parallel expand which is in turn the reverse of compress right in the following questions

What's the fastest way to pack 32 0/1 values into the bits of a single 32-bit variable?

Shift masked bits to the lsb

One general solution might be

uint64_t bit_expand(uint64_t x)
{
    // Input:  00000000ABCDEFGH, each character is a nibble
    x = ((x & 0xFFFF0000) << 32) | ((x & 0x0000FFFF) << 16);
    // Result: ABCD0000EFGH0000
    x = (x & 0xFF000000FF000000) | ((x & 0x00FF000000FF0000) >> 8);
    // Result: AB00CD00EF00GH00
    x = (x & 0xF000F000F000F000) | ((x & 0x0F000F000F000F00) >> 4);
    // Result: A0B0C0D0E0F0G0H0. Each byte: abcd0000
    x = (x & 0xC0C0C0C0C0C0C0C0) | ((x & 0x3030303030303030) >> 2);
    // Result:                   Each byte: ab00cd00
    x = (x & 0x8888888888888888) | ((x & 0x4444444444444444) >> 1);
    // Result:                   Each byte: a0b0c0d0
    return x;
}

However the constant generation might be inefficient on RISC architectures because the 64-bit immediate can't be stored in a single instruction like on x86. Even on x86 <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGe1wAyeAyYAHI%2BAEaYxBIArKQADqgKhE4MHt6%2BekkpjgJBIeEsUTFc8XaYDmlCBEzEBBk%2Bfly2mPZ5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B9kpGcJIIAA%3D" rel="nofollow noreferrer">the output assembly is quite long. Here is another possible implementation as described on Bit Twiddling Hacks

static const unsigned int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF};
static const unsigned int S[] = {1, 2, 4, 8};

unsigned int x; // Interleave lower 16 bits of x and y, so the bits of x
unsigned int y; // are in the even positions and bits from y in the odd;
unsigned int z; // z gets the resulting 32-bit Morton Number.
                // x and y must initially be less than 65536.

x = (x | (x << S[3])) & B[3];
x = (x | (x << S[2])) & B[2];
x = (x | (x << S[1])) & B[1];
x = (x | (x << S[0])) & B[0];

y = (y | (y << S[3])) & B[3];
y = (y | (y << S[2])) & B[2];
y = (y | (y << S[1])) & B[1];
y = (y | (y << S[0])) & B[0];

z = x | (y << 1);

A lookup table can also be used

#define EXPAND4(a) ((((a) & 0x8) << 4) | (((a) & 0x4) << 2) \
                  | (((a) & 0x2) << 1) | (((a) & 0x1)))

const uint8_t LUT[16] = {
    EXPAND4( 0), EXPAND4( 1), EXPAND4( 2), EXPAND4( 3),
    EXPAND4( 4), EXPAND4( 5), EXPAND4( 6), EXPAND4( 7),
    EXPAND4( 8), EXPAND4( 9), EXPAND4(10), EXPAND4(11),
    EXPAND4(12), EXPAND4(13), EXPAND4(14), EXPAND4(15)
};

output = ((uint64_t)LUT[(x >> 28) & 0xF] << 56) | ((uint64_t)LUT[(x >> 24) & 0xF] << 48)
       | ((uint64_t)LUT[(x >> 20) & 0xF] << 40) | ((uint64_t)LUT[(x >> 16) & 0xF] << 32)
       | ((uint64_t)LUT[(x >> 12) & 0xF] << 24) | ((uint64_t)LUT[(x >>  8) & 0xF] << 16)
       | ((uint64_t)LUT[(x >>  4) & 0xF] <<  8) | ((uint64_t)LUT[(x >>  0) & 0xF] <<  0);

The size of the lookup table may be increased if necessary

On x86 with BMI2 there's hardware support with PDEP instruction which can be accessed via the following intrinsic

output = _pdep_u64(x, 0xaaaaaaaaaaaaaaaaULL);

Another solution on architectures without bit deposit/expand instruction but with fast multipliers

uint64_t spaceOut8bits(uint8_t b)
{
    uint64_t MAGIC = 0x8040201008040201;
    uint64_t MASK  = 0x8080808080808080;
    uint64_t expand8bits = htobe64(((MAGIC*b) & MASK) >> 7);
    uint64_t spacedOutBits = expand8bits*0x41041 & 0xAA000000AA000000;
    return (spacedOutBits | (spacedOutBits << 24)) & 0xFFFF000000000000;
}

uint64_t spaceOut64bits(uint64_t x)
{
    return (spaceOut8bits(x >> 24) >>  0)
         | (spaceOut8bits(x >> 16) >> 16)
         | (spaceOut8bits(x >>  8) >> 32)
         | (spaceOut8bits(x >>  0) >> 48);
}

The way it works is like this

The first step expands the input bits from abcdefgh to a0000000 b0000000 c0000000 d0000000 e0000000 f0000000 g0000000 h0000000 and store in expand8bits

Then we move those spaced out bits close together by multiplying and masking in the next step. After that spacedOutBits will contain a0b0c0d0 00000000 00000000 00000000 e0f0g0h0 00000000 00000000 00000000. We'll merge the two bytes in the result together

The magic number for bringing the bits closer is calculated like this

  a0000000b0000000c0000000d0000000e0000000f0000000g0000000h0000000
×                                              1000001000001000001
  ────────────────────────────────────────────────────────────────
  a0000000b0000000c0000000d0000000e0000000f0000000g0000000h0000000
  00b0000000c0000000d0000000e0000000f0000000g0000000h0000000
+ 0000c0000000d0000000e0000000f0000000g0000000h0000000
  000000d0000000e0000000f0000000g0000000h0000000
  ────────────────────────────────────────────────────────────────
  a0b0c0d0b0c0d0e0c0d0e0f0d0e0f0g0e0f0g0h0f0g0h000g0h00000h0000000
& 1010101000000000000000000000000010101010000000000000000000000000
  ────────────────────────────────────────────────────────────────
  a0b0c0d0000000000000000000000000e0f0g0h0000000000000000000000000

The output assembly can be seen <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGe1wAyeAyYAHI%2BAEaYxBIArKQADqgKhE4M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l4kAVzg%2Bi4MSexAUAqWw0CmzgIeiXL9Uc13nROzDl/q2PlipB9kpGcJIIAA%3D" rel="nofollow noreferrer">here. You can change the compiler to see how it's done on various architectures

There's also an alternative way on the Bit Twiddling Hacks page

z = ((x * 0x0101010101010101ULL & 0x8040201008040201ULL) *
     0x0102040810204081ULL >> 49) & 0x5555 |
    ((y * 0x0101010101010101ULL & 0x8040201008040201ULL) *
     0x0102040810204081ULL >> 48) & 0xAAAA;

More solutions can be found in Portable efficient alternative to PDEP without using BMI2?

Related: How to do bit striping on pixel data?

As you can see, without the availability of a bit deposit instruction it'll be quite complex in terms of operations. If you do a not of bit striping like this then it'll be better to do in parallel using SIMD


来源: stackexchange

问:
SAS group by first digits
I have a variable in SAS with a lot of numbers, for example 11000, 30129, 11111, 30999. I want to group this by the first two digits so "11000 and 11111" and "30129 and 30999" will be in a own table.</p>

答:
I think I did like you, but my new column only shows with ".". But  I think your answer can give me some help anyways, thank you!

data books;

infile "&path\Boken.csv" dlm=';' missover dsd firstobs=2;

 input   ISBN: $12.
   Book: $quote150.;

run;

data test_a;
format val_ISBN 15.;
set books;
val_ISBN= SUBSTRN(ISBN,1,2);
run;

proc sort data=test_a out=test_b;
by val_ISBN;
run;

proc print data=test_b (obs=10) noobs ;
run;```

ContentLicense: CC BY-SA 3.0

Title: SAS group by first digits


问:
What is the role of Artisan in Laravel framework?
In the official Laravel documentation, I found this command:

php artisan serve

Also in others commands, Artisan is used.

What is the purpose and role of Artisan?

答: Artisan is a CLI tool for Laravel, which helps a programmer to minimise the manual tasks like creating .php files. Its also helps in migration, routing, scheduling etc</p>


问:
Why some css font family does not work?
I used those css code

.logo h2 {
  font-family: Pacifico, MyriadPro-Regular, AdobeInvisFont;
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}```

But it does not work. What should I do?

答:
Please try this code. I have found Google Font for 'Pacifico'. Find for others if available. If they are not free and you have purchased those, add relative path of their location in @font-face rule.  </p>

```<code>@font-face {
    font-family: "Pacifico";
    src: url('https://fonts.googleapis.com/css?family=Pacifico');
}

.logo h2 {
  font-family: "Pacifico", "MyriadPro-Regular", "AdobeInvisFont";
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}
</code>```

Title: Why some css font family does not work?

Body:
I used those css code

.logo h2 {
  font-family: Pacifico, MyriadPro-Regular, AdobeInvisFont;
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}

But it does not work. What should I do?

Body:
Please try this code. I have found Google Font for 'Pacifico'. Find for others if available. If they are not free and you have purchased those, add relative path of their location in @font-face rule.

@font-face {
    font-family: "Pacifico";
    src: url('https://fonts.googleapis.com/css?family=Pacifico');
}

.logo h2 {
  font-family: "Pacifico", "MyriadPro-Regular", "AdobeInvisFont";
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}


问:
SABRE Passenger Details PNR without a PNR
Sometimes, for some flights, SABRE is returning the response bellow when I try to make a book: EndTransactionLLSRQ: *IM AND CANCEL UNABLE SEGMENTS

What´s the right way to treat this error? In a right response, SABRE returns the PNR:

答: When has the search been made you try to fulfill? Sounds like the status of the flights you try to book are not "HK" or "HL" but UC or so. This means you cant enter the pnr bc. the flight is not available in the predefined booking class.</p>


问:
java.net.SocketException: Invalid argument: connect
My new laptop (Alienware m17x) throws a java.net.SocketException: Invalid argument: connect when I run the following basic code:

Server.java:

```<code>public static void main (String[] args) throws Exception {

    ServerSocket serverSocket = new ServerSocket (8888);
    Socket socket = serverSocket.accept();
}
</code>```

Client.java:

```<code>public static void main (String[] args) throws Exception {
    Socket socket = new Socket ("localhost", 8888);
}
</code>```

Every time I run Client.java (after starting Server.java) I get this socket exception. Here's the full trace of the exception:

```<code>Exception in thread "main" java.net.SocketException: Invalid argument: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at Client.main(Client.java:5)
</code>```

I've tried a few things, but no luck the exception is always thrown. Here's what I have concluded:

Changing the port numbers changes nothing.

It's not a problem with the network. I have gotten the exception at school and at home.

I've reinstalled the JVM and the JDK but no luck.

This only occurs on one machine. I have run the same code on my desktop and I have not gotten any exceptions. I am using Windows 7 on both.

It is not blocked by a firewall. I have turned my firewalls off and I still have this issue.

What should I do or check for to resolve this issue?

EDIT:
route print outputs:

```<code>===========================================================================
Interface List
 15...e4 d5 3d 08 cb 83 ......Killer Wireless-N 1103 Network Adapter
 13...d0 df 9a b5 73 dc ......Bluetooth Device (Personal Area Network)
 11...d4 be d9 00 10 65 ......Atheros AR8151 PCI-E Gigabit Ethernet Controller (NDIS 6.20)
  1...........................Software Loopback Interface 1
 17...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
 16...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
 18...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 19...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.0.1    192.168.0.191     25
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      192.168.0.0    255.255.255.0         On-link     192.168.0.191    281
    192.168.0.191  255.255.255.255         On-link     192.168.0.191    281
    192.168.0.255  255.255.255.255         On-link     192.168.0.191    281
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.0.191    281
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.0.191    281
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
 17     58 ::/0                     On-link
  1    306 ::1/128                  On-link
 17     58 2001::/32                On-link
 17    306 2001:0:4137:9e76:28f3:2721:524f:e2ef/128
                                    On-link
 15    281 fe80::/64                On-link
 17    306 fe80::/64                On-link
 17    306 fe80::28f3:2721:524f:e2ef/128
                                    On-link
 15    281 fe80::68c1:bc79:fefa:88a2/128
                                    On-link
  1    306 ff00::/8                 On-link
 17    306 ff00::/8                 On-link
 15    281 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None
</code>```

EDIT: As @PhilippeLM and @beny23 made me realize, setting the java system variable java.net.preferIPv4Stack to true solves my problem. However I want a permanent fix. I don't want to specify the system variable every time I run a java application.

Here's what I've tried with no luck once again:

Setting my machine preferences to prefer IPv4 by following these steps

Adding the line java.net.preferIPv4Stack=true to the net.properties file in %JAVA_HOME%\jre\lib.

Is there anything else I can try?

答:
Also check if your IDE is using the JRE which you expect.

I had same issue:

```<code>java.sql.SQLException: JZ006: Caught IOException: java.net.SocketException: Invalid argument: create
</code>```

When I checked my run configuration, my default JRE was pointing to 'Project Execution Environment 'JavaSE1.7' which was not I was expecting.

I changed it to option Alternate JRE and set the JAVA 8 as installed jre.
which has solved my problem.

Body:
My new laptop (Alienware m17x) throws a java.net.SocketException: Invalid argument: connect when I run the following basic code:

Server.java:

public static void main (String[] args) throws Exception {

    ServerSocket serverSocket = new ServerSocket (8888);
    Socket socket = serverSocket.accept();
}

Client.java:

public static void main (String[] args) throws Exception {
    Socket socket = new Socket ("localhost", 8888);
}

Every time I run Client.java (after starting Server.java) I get this socket exception. Here's the full trace of the exception:

Exception in thread "main" java.net.SocketException: Invalid argument: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at Client.main(Client.java:5)

I've tried a few things, but no luck the exception is always thrown. Here's what I have concluded:

Changing the port numbers changes nothing.

It's not a problem with the network. I have gotten the exception at school and at home.

I've reinstalled the JVM and the JDK but no luck.

This only occurs on one machine. I have run the same code on my desktop and I have not gotten any exceptions. I am using Windows 7 on both.

It is not blocked by a firewall. I have turned my firewalls off and I still have this issue.

What should I do or check for to resolve this issue?

EDIT:
route print outputs:

===========================================================================
Interface List
 15...e4 d5 3d 08 cb 83 ......Killer Wireless-N 1103 Network Adapter
 13...d0 df 9a b5 73 dc ......Bluetooth Device (Personal Area Network)
 11...d4 be d9 00 10 65 ......Atheros AR8151 PCI-E Gigabit Ethernet Controller (NDIS 6.20)
  1...........................Software Loopback Interface 1
 17...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
 16...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
 18...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 19...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.0.1    192.168.0.191     25
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      192.168.0.0    255.255.255.0         On-link     192.168.0.191    281
    192.168.0.191  255.255.255.255         On-link     192.168.0.191    281
    192.168.0.255  255.255.255.255         On-link     192.168.0.191    281
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.0.191    281
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.0.191    281
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
 17     58 ::/0                     On-link
  1    306 ::1/128                  On-link
 17     58 2001::/32                On-link
 17    306 2001:0:4137:9e76:28f3:2721:524f:e2ef/128
                                    On-link
 15    281 fe80::/64                On-link
 17    306 fe80::/64                On-link
 17    306 fe80::28f3:2721:524f:e2ef/128
                                    On-link
 15    281 fe80::68c1:bc79:fefa:88a2/128
                                    On-link
  1    306 ff00::/8                 On-link
 17    306 ff00::/8                 On-link
 15    281 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

EDIT: As @PhilippeLM and @beny23 made me realize, setting the java system variable java.net.preferIPv4Stack to true solves my problem. However I want a permanent fix. I don't want to specify the system variable every time I run a java application.

Here's what I've tried with no luck once again:

Setting my machine preferences to prefer IPv4 by following these steps

Adding the line java.net.preferIPv4Stack=true to the net.properties file in %JAVA_HOME%\jre\lib.

Is there anything else I can try?

Body:
Also check if your IDE is using the JRE which you expect.

I had same issue:

java.sql.SQLException: JZ006: Caught IOException: java.net.SocketException: Invalid argument: create

When I checked my run configuration, my default JRE was pointing to 'Project Execution Environment 'JavaSE1.7' which was not I was expecting.

I changed it to option Alternate JRE and set the JAVA 8 as installed jre.
which has solved my problem.


问:
How to create a s3ql file system and mount it automatically on boot?
I've been experimenting with s3ql on Ubuntu 10.04, using it to mount Amazon S3 buckets.  However, I'd really like it to mount them automatically.  Does anyone know how to do that?

Solution:

Thanks to help from Nikratio of s3ql I'm finally able to mount S3 buckets automatically when the system boots. You'll definitely want to look at the manual, but here's the basics of how to do it!

The first step is to create an authinfo file.  This file should be placed in a .s3ql directory within the home directory of the user who will be using it.  The authinfo file contains login info allowing s3ql to mount buckets without prompting.  Below is an example of what your authinfo file should look like.  The first line contains your Amazon Security Credentials.  The second contains the location and password for your bucket.  You can add multiple bucket-lines to this file if needed, but I'm only using one in this example.  At this point, the bucket password can be anything.

```<code>backend s3 machine any login ASDFGHJKL password ZXCVBNM
storage-url s3://mybucket password mypassword
</code>```

The bucket name has to be unique.  No two users can have the same bucket name, so its a good idea to log into Amazon Web Services and try different names until you find one that's available.  Once you've found one, you'll need to delete it, since s3ql will re-create it when it creates your s3ql filesystem.  If the bucket already exists, you'll receive an error.

To create the file system, use the command:

```<code>mkfs.s3ql s3://mybucket
</code>```

It will prompt you for your encryption password.  This should be the same as the bucket password in the authinfo file.

Now that your file system is created, you can mount it using the command:

```<code>mount.s3ql s3://mybucket /mnt/s3/bucket
</code>```

Of course, your bucket name and mount point will vary.

Now, if we want to mount this bucket automatically on boot, we need to add an upstart script to /etc/init.  Fortunately, s3ql comes packaged with one, s3ql.conf.

I added "--allow-other" to the mount.s3ql command to allow users other than root to access the mounted bucket.

```<code>#
# This file can be placed in /etc/init. It defines an upstart job that
# takes care of mounting and unmounting an S3QL file system.
#
description "S3QL Backup File System"
author      "Nikolaus Rath <Nikolaus@rath.org>"

start on (filesystem and net-device-up IFACE=eth0)
stop on runlevel [016]

env BUCKET="s3://mybucket"
env MOUNTPOINT="/mnt/s3/bucket"

expect stop

script
    # Redirect stdout and stderr into the system log
    DIR=$(mktemp -d)
    mkfifo "$DIR/LOG_FIFO"
    logger -t s3ql -p local0.info < "$DIR/LOG_FIFO" &
    exec > "$DIR/LOG_FIFO"
    exec 2>&1
    rm -rf "$DIR"

    # Check and mount file system
    fsck.s3ql --batch "$BUCKET"
    exec mount.s3ql --upstart --allow-other "$BUCKET" "$MOUNTPOINT"
end script

pre-stop script
    umount.s3ql "$MOUNTPOINT"
end script
</code>```

After adding this script, in theory you should be able to reboot and have your bucket automatically mounted, but this is were I ran into trouble.  Mine wasn't being mounted.

My problem was caused by the fact that upstart was running the script as root, but I'd created the file system as another user.  Once I copied the .s3ql directory from the home directory of the user I'd been logged-in as to /root, the problem was solved.

I hope this helps someone else out there.  Although I haven't been using my mounted S3 bucket for long, I'm impressed with how my initial tests have gone.

Also, this answer was written about a week after the solution was found.  I think I've covered everything, but if you find I've missed a step, let me know and I'll add it.  You'll also want to read the manual, its really worth reading if you intend to use s3ql.

答: With some help from Nikratio, I'm finally able to mount my S3 bucket automatically on boot.  I've updated my question with the solution.</p>

ContentLicense: CC BY-SA 2.5

Body:
I've been experimenting with s3ql on Ubuntu 10.04, using it to mount Amazon S3 buckets.  However, I'd really like it to mount them automatically.  Does anyone know how to do that?

Solution:

Thanks to help from Nikratio of s3ql I'm finally able to mount S3 buckets automatically when the system boots. You'll definitely want to look at the manual, but here's the basics of how to do it!

The first step is to create an authinfo file.  This file should be placed in a .s3ql directory within the home directory of the user who will be using it.  The authinfo file contains login info allowing s3ql to mount buckets without prompting.  Below is an example of what your authinfo file should look like.  The first line contains your Amazon Security Credentials.  The second contains the location and password for your bucket.  You can add multiple bucket-lines to this file if needed, but I'm only using one in this example.  At this point, the bucket password can be anything.

backend s3 machine any login ASDFGHJKL password ZXCVBNM
storage-url s3://mybucket password mypassword

The bucket name has to be unique.  No two users can have the same bucket name, so its a good idea to log into Amazon Web Services and try different names until you find one that's available.  Once you've found one, you'll need to delete it, since s3ql will re-create it when it creates your s3ql filesystem.  If the bucket already exists, you'll receive an error.

To create the file system, use the command:

mkfs.s3ql s3://mybucket

It will prompt you for your encryption password.  This should be the same as the bucket password in the authinfo file.

Now that your file system is created, you can mount it using the command:

mount.s3ql s3://mybucket /mnt/s3/bucket

Of course, your bucket name and mount point will vary.

Now, if we want to mount this bucket automatically on boot, we need to add an upstart script to /etc/init.  Fortunately, s3ql comes packaged with one, s3ql.conf.

I added "--allow-other" to the mount.s3ql command to allow users other than root to access the mounted bucket.

#
# This file can be placed in /etc/init. It defines an upstart job that
# takes care of mounting and unmounting an S3QL file system.
#
description "S3QL Backup File System"
author      "Nikolaus Rath <Nikolaus@rath.org>"

start on (filesystem and net-device-up IFACE=eth0)
stop on runlevel [016]

env BUCKET="s3://mybucket"
env MOUNTPOINT="/mnt/s3/bucket"

expect stop

script
    # Redirect stdout and stderr into the system log
    DIR=$(mktemp -d)
    mkfifo "$DIR/LOG_FIFO"
    logger -t s3ql -p local0.info < "$DIR/LOG_FIFO" &
    exec > "$DIR/LOG_FIFO"
    exec 2>&1
    rm -rf "$DIR"

    # Check and mount file system
    fsck.s3ql --batch "$BUCKET"
    exec mount.s3ql --upstart --allow-other "$BUCKET" "$MOUNTPOINT"
end script

pre-stop script
    umount.s3ql "$MOUNTPOINT"
end script

After adding this script, in theory you should be able to reboot and have your bucket automatically mounted, but this is were I ran into trouble.  Mine wasn't being mounted.

My problem was caused by the fact that upstart was running the script as root, but I'd created the file system as another user.  Once I copied the .s3ql directory from the home directory of the user I'd been logged-in as to /root, the problem was solved.

I hope this helps someone else out there.  Although I haven't been using my mounted S3 bucket for long, I'm impressed with how my initial tests have gone.

Also, this answer was written about a week after the solution was found.  I think I've covered everything, but if you find I've missed a step, let me know and I'll add it.  You'll also want to read the manual, its really worth reading if you intend to use s3ql.


问:
Prolog - predicate to sort and merge list
Hi I am trying to write a predicate that sorts first list low to high and second list high to low, then puts the heads of each list in to a new list.</p>

答:
Here the code for the mix/3 predicate:

```<code>mix([],[],[]).
mix([],[H1|T1],[H1|T2]):-
    mix([],T1,T2).
mix([H1|T1],[],[H1|T2]):-
    mix(T1,[],T2).
mix([H1|T1],[H2|T2],[H1,H2|T3]) :-
   mix(T1,T2,T3).
</code>```

This one works also with input list with different length.

Body:
Here the code for the mix/3 predicate:

mix([],[],[]).
mix([],[H1|T1],[H1|T2]):-
    mix([],T1,T2).
mix([H1|T1],[],[H1|T2]):-
    mix(T1,[],T2).
mix([H1|T1],[H2|T2],[H1,H2|T3]) :-
   mix(T1,T2,T3).

This one works also with input list with different length.


问:
cloudinary-ios - Invalid Signature - GenerateCLDCryptoModule
I am using manual Cloudinary integration and is having this error during app store upload...

ERROR ITMS-90035: "Invalid Signature. Code object is not signed at all. The file at path [BucketListApp.app/Frameworks/Cloudinary.framework/GenerateCLDCryptoModule] is not properly signed

So far, I have tried many different code signing variants, tried to shift toward pods, downgraded to xcode 8 to add support for swift 2, tried to write code in swift, tried adding a bunch of workaround codes in podFile. But unfortunately I was not able even run Cloudinary SDK using any of the methods above.

The only method worked for me was the manual integration, it works well but only road block now is when I upload to app store from XCode I get this error.

答: Cloudinary just published a Release Candidate for its iOS library - 2.0.4-rc1. CLDCryptoModule is removed in this RC so you shouldn't face this issue.


问:
Java and Javascript - Lastmodified on Linux
I  wrote a script on the Jmeter Web Driver in javascript and Java .

On a Windows system , the script is running perfectly . But on a Linux System , i have a weird problem . The lastmodifed then i obtain is not good. front_end.jtl has been modified yesterday , but the script say today at 10:00 in milliseconds timestamp .

Please help me.

```<code>    // Importing packages (and all classes in package) from Java into Javascript var pkg = JavaImporter(org.openqa.selenium)
    var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
    // We don't use wait in this very simple test, but here is way to access for more realistic testing
    var wait=new support_ui.WebDriverWait(WDS.browser, 5)

    // Start recording the time for this request

    WDS.sampleResult.sampleStart();

    // Let's get a page

    var baseUrl = "cnyw${FE}.mycore.core-cloud.net"

    WDS.browser.get("https://"+ baseUrl)

    var frontjtl = new java.io.File('/home/mycore/front_end.jtl')
    var frontlog = new java.io.File('/home/mycore/jmeter_front_end.log')

    var lastmodifjtl = frontjtl.lastModified()
    var lastmodiflog = frontlog.lastModified()

    if ( lastmodifjtl = lastmodiflog ) {
     var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
     screenshot.renameTo(new java.io.File('/home/mycore/screenshots/tools/screenshot_cnyw${FE}.png'))
   }

    // Record the time of the request
    WDS.sampleResult.sampleEnd();
</code>```

答:
I found an explanation : https://bugs.openjdk.java.net/browse/JDK-8177809

It's a confirmed bug ...

Body:
I  wrote a script on the Jmeter Web Driver in javascript and Java .

On a Windows system , the script is running perfectly . But on a Linux System , i have a weird problem . The lastmodifed then i obtain is not good. front_end.jtl has been modified yesterday , but the script say today at 10:00 in milliseconds timestamp .

Please help me.

    // Importing packages (and all classes in package) from Java into Javascript var pkg = JavaImporter(org.openqa.selenium)
    var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
    // We don't use wait in this very simple test, but here is way to access for more realistic testing
    var wait=new support_ui.WebDriverWait(WDS.browser, 5)

    // Start recording the time for this request

    WDS.sampleResult.sampleStart();

    // Let's get a page

    var baseUrl = "cnyw${FE}.mycore.core-cloud.net"

    WDS.browser.get("https://"+ baseUrl)

    var frontjtl = new java.io.File('/home/mycore/front_end.jtl')
    var frontlog = new java.io.File('/home/mycore/jmeter_front_end.log')

    var lastmodifjtl = frontjtl.lastModified()
    var lastmodiflog = frontlog.lastModified()

    if ( lastmodifjtl = lastmodiflog ) {
     var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
     screenshot.renameTo(new java.io.File('/home/mycore/screenshots/tools/screenshot_cnyw${FE}.png'))
   }

    // Record the time of the request
    WDS.sampleResult.sampleEnd();


问:
angular-virtual-keyboard not opening on focus

var myApp = angular.module('myApp',['angular-virtual-keyboard']);
myApp.controller('MyCtrl',MyCtrl);

function MyCtrl($scope) {
    document.getElementsByTagName('input')[0].focus();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<script src="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.js"></script>

<body ng-app='myApp'>
  <div ng-controller="MyCtrl">
    <input type='text' ng-model="textValue" ng-virtual-keyboard/>
  </div>
</body></code>```

If I click on input then virtual keyboard is opening. But how can I open the keyboard without click. I tried using input.focus() that didn't work.

答:
Just find a working fiddle Here  with an directive auto focus

    var myApp = angular.module('myApp',['angular-virtual-keyboard']);

myApp.controller('MyCtrl',function($scope) {
});

myApp.directive('autoFocus', function($timeout) {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 0);
        }
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
    <script src="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.js"></script>

    <body ng-app='myApp'>
      <div ng-controller="MyCtrl">
        <input type='text' ng-model="textValue" auto-focus ng-virtual-keyboard/>
      </div>
    </body></code>```

Body:
var myApp = angular.module('myApp',['angular-virtual-keyboard']);
myApp.controller('MyCtrl',MyCtrl);

function MyCtrl($scope) {
    document.getElementsByTagName('input')[0].focus();
}

<link href="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.css" rel="stylesheet"/>

    <input type='text' ng-model="textValue" ng-virtual-keyboard/>

If I click on input then virtual keyboard is opening. But how can I open the keyboard without click. I tried using input.focus() that didn't work.

Body:
Just find a working fiddle Here  with an directive auto focus

    var myApp = angular.module('myApp',['angular-virtual-keyboard']);

myApp.controller('MyCtrl',function($scope) {
});

myApp.directive('autoFocus', function($timeout) {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 0);
        }
    };
});

<link href="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
    <script src="https://rawgit.com/the-darc/angular-virtual-keyboard/master/release/angular-virtual-keyboard.js"></script>

    <body ng-app='myApp'>
      <div ng-controller="MyCtrl">
        <input type='text' ng-model="textValue" auto-focus ng-virtual-keyboard/>
      </div>
    </body>


问:
Combination of for-loop and index slicing is not returning expected results
Apologies in advance, I loathe to ask such a newb question (this is the first language I'm learning) but there's clearly a gap in my understanding, and I can't find a link to any content which solves the issue I'm experiencing.

The below code defines 3 dictionaries, and an empty list. I then run a for loop to populate the list with 30 "Slow Aliens".

I then run another loop on the first 10 entries in the list in order to update that particular instance to a "Fast Alien" dictionary. However, I seem to be replacing every dictionary in the list.

Any help pointing me to some articles which discuss/solve/educate me further would be appreciatively received.

```<code>slow_alien = {
    "Name": "Slow Alien",
    "Colour": "Green",
    "Points": 10,
    "X Position": 15,
    "Y Position": 20,
    "Current Speed": "Slow",
    "Height": 1.8,
}
medium_alien = {
    "Name": "Medium Alien",
    "Colour": "Yellow",
    "Points": 15,
    "X Position": 30,
    "Y Position": 20,
    "Current Speed": "Medium",
    "Height": 2.2,
}
fast_alien = {
    "Name": "Fast Alien",
    "Colour": "Red",
    "Points": 20,
    "X Position": 45,
    "Y Position": 20,
    "Current Speed": "Fast",
    "Height": 2.6,
}
aliens = []

for alien in range(30):
    aliens.append(slow_alien)

for alien in aliens[:10]:
    if alien == slow_alien:
        alien.update(fast_alien)

for alien in aliens:
    for key, value in alien.items():
        print(str(key) + ": " + str(value))
    print("")
print("The aliens list contains " + str(len(aliens)) + " dictionaries")
</code>```

Thanks,

Carl.

答:
Creating a new copy of the dictionary is the correct answer, as has already been pointed out. I want to make more explicit what actually goes wrong with your code.

```<code>for alien in range(30):
    aliens.append(slow_alien)
</code>```

slow_alien refers to the same dict, so you get 30 references of that (same) object.

```<code>for alien in aliens[:10]:
    if alien == slow_alien:
        alien.update(fast_alien)
</code>```

The update() call is what messes everything up. The first alien in the loop is a reference to the slow_alien dict. So what you really do is slow_alien.update() and you effectively change the object itself. It will successfully enter the conditional block for the remaining iterations because each alien and slow_alien refer to the same object, namely fast_alien. You can see this if you print slow_alien == fast_alien at the end of your code.

If each item is a different copy, then you update that copy itself without touching the original slow_alien. It can also be written more compactly with a list comprehension.

```<code>aliens = [slow_alien.copy() for _ in range(30)]
</code>```

Body:
Apologies in advance, I loathe to ask such a newb question (this is the first language I'm learning) but there's clearly a gap in my understanding, and I can't find a link to any content which solves the issue I'm experiencing.

The below code defines 3 dictionaries, and an empty list. I then run a for loop to populate the list with 30 "Slow Aliens".

I then run another loop on the first 10 entries in the list in order to update that particular instance to a "Fast Alien" dictionary. However, I seem to be replacing every dictionary in the list.

Any help pointing me to some articles which discuss/solve/educate me further would be appreciatively received.

slow_alien = {
    "Name": "Slow Alien",
    "Colour": "Green",
    "Points": 10,
    "X Position": 15,
    "Y Position": 20,
    "Current Speed": "Slow",
    "Height": 1.8,
}
medium_alien = {
    "Name": "Medium Alien",
    "Colour": "Yellow",
    "Points": 15,
    "X Position": 30,
    "Y Position": 20,
    "Current Speed": "Medium",
    "Height": 2.2,
}
fast_alien = {
    "Name": "Fast Alien",
    "Colour": "Red",
    "Points": 20,
    "X Position": 45,
    "Y Position": 20,
    "Current Speed": "Fast",
    "Height": 2.6,
}
aliens = []

for alien in range(30):
    aliens.append(slow_alien)

for alien in aliens[:10]:
    if alien == slow_alien:
        alien.update(fast_alien)

for alien in aliens:
    for key, value in alien.items():
        print(str(key) + ": " + str(value))
    print("")
print("The aliens list contains " + str(len(aliens)) + " dictionaries")

Thanks,

Carl.

Body:
Creating a new copy of the dictionary is the correct answer, as has already been pointed out. I want to make more explicit what actually goes wrong with your code.

for alien in range(30):
    aliens.append(slow_alien)

slow_alien refers to the same dict, so you get 30 references of that (same) object.

for alien in aliens[:10]:
    if alien == slow_alien:
        alien.update(fast_alien)

The update() call is what messes everything up. The first alien in the loop is a reference to the slow_alien dict. So what you really do is slow_alien.update() and you effectively change the object itself. It will successfully enter the conditional block for the remaining iterations because each alien and slow_alien refer to the same object, namely fast_alien. You can see this if you print slow_alien == fast_alien at the end of your code.

If each item is a different copy, then you update that copy itself without touching the original slow_alien. It can also be written more compactly with a list comprehension.

aliens = [slow_alien.copy() for _ in range(30)]


问:
Time complexity of two nested loops depending on n and k
I have a string of n chars and a k length of unique substrings

I'm trying to understand the time complexity of this code:

```<code>for (int i = 0; i <= inputStr.length() - k; i++) {
    String substr = inputStr.substring(i, i + k);
    Set<Character> setChars =  new HashSet<Character>();
    for (int j = 0; j < k; j++) {
        setChars.add(substr.charAt(j));
    }
    if (setChars.size() == num) {
        set.add(substr);
    }
}
</code>```

If I correctly understood the time complexity might be expressed by the formula:

f((n-k+1)*k)

I believe that the worse case I can have is when k = n/2, so:

f((n-k+1)k) = nn/2 - n/2*n/2 + n/2 = 1/2*n*n - 1/4*n*n + 1/2*n =>
  O(n)

答:
You are correct until the implication.

f((n-k+1)k) = nn/2 - n/2*n/2 + n/2 = 1/2*n*n - 1/4*n*n + 1/2*n

= 1/4n*n + 1/2*n => O(n*n)

Body:
I have a string of n chars and a k length of unique substrings

I'm trying to understand the time complexity of this code:

for (int i = 0; i <= inputStr.length() - k; i++) {
    String substr = inputStr.substring(i, i + k);
    Set<Character> setChars =  new HashSet<Character>();
    for (int j = 0; j < k; j++) {
        setChars.add(substr.charAt(j));
    }
    if (setChars.size() == num) {
        set.add(substr);
    }
}

If I correctly understood the time complexity might be expressed by the formula:

f((n-k+1)*k)

I believe that the worse case I can have is when k = n/2, so:

f((n-k+1)k) = nn/2 - n/2*n/2 + n/2 = 1/2*n*n - 1/4*n*n + 1/2*n =>
  O(n)


问:
Can I test my iPad app on someone else's iPad?
I'm developing an iPad app, and want to test it on a friend's iPad.  Before I buy the $99 developer account, I just want to make sure that this will work.

Does my friend's device have to use my apple ID in order to install the provisioning profile?  Is there anything that would change about his iPad (besides the ability to install my app, of course)?

Thanks!

答:
With the $99 developer package, you can install your app on up to 100 test devices, and they don't need to use your Apple ID.

All that changes on the iPad is that there's an additional section within settings that lists the provisioning profile(s) present on the device. However, you might want to get your friend to do a backup (via iTunes) before you borrow it, if only in case it falls off the edge of a table or something. :-)


问:
Bot Framework - imBack or postBack message without buttons? Is it possible?
I am trying to display a card (or list of links ) to my Skype, Slack or Messenger users with some postBack actions.

Herocard works fine, they display the buttons with the text like in this example:

```<code>    IMessageActivity replyMessage = context.MakeMessage();
    replyMessage.Attachments.Add(
    new HeroCard
    {
        Subtitle = "Settings",
        Buttons = new List<CardAction> {
            new CardAction(ActionTypes.ImBack, $"Spell-check {spellcheckst}", value: $"Set Spell-check setting {spellcheckst}", text: $"Spell-check {spellcheckst}", displayText: $"Spell-check {spellcheckst}"),
            new CardAction(ActionTypes.ImBack, $"Small-talk {smalltalkst}", value: $"Set Small-talk setting {smalltalkst}", text: $"Small-talk {smalltalkst}", displayText: $"Small-talk {smalltalkst}")

        }
    }.ToAttachment()
    );
    await context.PostAsync(replyMessage);
</code>```

But buttons take a lot of screen real estate and many times their captions are truncated.

Is there a way to trigger a postBack or imBack card action without displaying buttons. Here is an example scenario, when the User asks for Help, the Bot displays list of commands:

Add a webpage Try Me

delete a webpage Try Me

Display help Try Me

etc.

The "Try Me" links would postBack to the bot exactly as the buttons above do.

Is this possible to do?

Thanks

答:
Indeed, large button name will create a problem and it's look like alien to cards. In place of that you can do that using Carousel Cards. Put below code in your dialog and check. I am doing it and its working.

```<code> public Task StartAsync(IDialogContext context)
        {
            context.Wait(MessageReceivedAsync);

            return Task.CompletedTask;
        }
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
        {
            var reply = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Attachments = GetCardsAttachments();

            await context.PostAsync(reply);

            context.Wait(this.MessageReceivedAsync);
        }

        private static IList<Attachment> GetCardsAttachments()
        {
            return new List<Attachment>()
            {
                GetHeroCard(
                    "Add a webpage",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "Add a webpage", value: "Add a webpage")),
                GetHeroCard(
                    "delete a webpage",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "delete a webpage", value: "delete a webpage")),
                GetHeroCard(
                    "Display help",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "Display help", value: "Display help")),
                GetHeroCard(
                    "etc",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "etc", value: "etc")),

            };
        }

        private static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction)
        {
            var heroCard = new HeroCard
            {
                Title = title,
                Subtitle = subtitle,
                Text = text,
                Images = new List<CardImage>() { cardImage },
                Buttons = new List<CardAction>() { cardAction },
            };

            return heroCard.ToAttachment();
        }
</code>```

I hope this will help you out to solve your concern.

Below is the scren shot for your reference.

Body:
I am trying to display a card (or list of links ) to my Skype, Slack or Messenger users with some postBack actions.

Herocard works fine, they display the buttons with the text like in this example:

    IMessageActivity replyMessage = context.MakeMessage();
    replyMessage.Attachments.Add(
    new HeroCard
    {
        Subtitle = "Settings",
        Buttons = new List<CardAction> {
            new CardAction(ActionTypes.ImBack, $"Spell-check {spellcheckst}", value: $"Set Spell-check setting {spellcheckst}", text: $"Spell-check {spellcheckst}", displayText: $"Spell-check {spellcheckst}"),
            new CardAction(ActionTypes.ImBack, $"Small-talk {smalltalkst}", value: $"Set Small-talk setting {smalltalkst}", text: $"Small-talk {smalltalkst}", displayText: $"Small-talk {smalltalkst}")

        }
    }.ToAttachment()
    );
    await context.PostAsync(replyMessage);

But buttons take a lot of screen real estate and many times their captions are truncated.

Is there a way to trigger a postBack or imBack card action without displaying buttons. Here is an example scenario, when the User asks for Help, the Bot displays list of commands:

Add a webpage Try Me

delete a webpage Try Me

Display help Try Me

etc.

The "Try Me" links would postBack to the bot exactly as the buttons above do.

Is this possible to do?

Thanks

Body:
Indeed, large button name will create a problem and it's look like alien to cards. In place of that you can do that using Carousel Cards. Put below code in your dialog and check. I am doing it and its working.

 public Task StartAsync(IDialogContext context)
        {
            context.Wait(MessageReceivedAsync);

            return Task.CompletedTask;
        }
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
        {
            var reply = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Attachments = GetCardsAttachments();

            await context.PostAsync(reply);

            context.Wait(this.MessageReceivedAsync);
        }

        private static IList<Attachment> GetCardsAttachments()
        {
            return new List<Attachment>()
            {
                GetHeroCard(
                    "Add a webpage",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "Add a webpage", value: "Add a webpage")),
                GetHeroCard(
                    "delete a webpage",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "delete a webpage", value: "delete a webpage")),
                GetHeroCard(
                    "Display help",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "Display help", value: "Display help")),
                GetHeroCard(
                    "etc",
                    "",
                    "",
                    new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                    new CardAction(ActionTypes.ImBack, "etc", value: "etc")),

            };
        }

        private static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction)
        {
            var heroCard = new HeroCard
            {
                Title = title,
                Subtitle = subtitle,
                Text = text,
                Images = new List<CardImage>() { cardImage },
                Buttons = new List<CardAction>() { cardAction },
            };

            return heroCard.ToAttachment();
        }

I hope this will help you out to solve your concern.

Below is the scren shot for your reference.


问:
What's wrong with Macro definition in the C code?
```<code>#define TRUE 1
#define FALSE 0

void function(int var)
{
    if(var == TRUE) {
        dosomething();
    }
}
</code>```

During an interview, I was showed the code. However, I think it's right. And I also try this on my computer.

答:
Nothing is wrong with the macro definition. However, the if condition needs an explanation.

Note the difference between:

```<code>if (var == TRUE)
</code>```

1 makes the condition true and every other value makes it false.

and

```<code>if (var)
</code>```

Every value except 0 makes the condition true. Only 0 makes it false.

Body:
#define TRUE 1
#define FALSE 0

void function(int var)
{
    if(var == TRUE) {
        dosomething();
    }
}

During an interview, I was showed the code. However, I think it's right. And I also try this on my computer.

Body:
Nothing is wrong with the macro definition. However, the if condition needs an explanation.

Note the difference between:

if (var == TRUE)

1 makes the condition true and every other value makes it false.

and

if (var)

Every value except 0 makes the condition true. Only 0 makes it false.


问:
gradle: find to which project does a file belong
Let's consider this sample multi gradle project structure

```<code>build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java
</code>```

And let's say from git changelog I have changed files:

```<code>project-a/project-a-b/src/test.java
project-c/src/test2.java
</code>```

I need to find out to which project they belong

```<code>project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c
</code>```

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

答:
The following should do what you want:</p>

```<code>def file = file('your/path')
def project
while (file.parentFile != null) {
    file = file.parentFile
    project = rootProject.allprojects.findAll { it.projectDir == file }
    if (project) {
        break;
    }
}
</code>```

Body:
Let's consider this sample multi gradle project structure

build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java

And let's say from git changelog I have changed files:

project-a/project-a-b/src/test.java
project-c/src/test2.java

I need to find out to which project they belong

project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

Body:
The following should do what you want:

def file = file('your/path')
def project
while (file.parentFile != null) {
    file = file.parentFile
    project = rootProject.allprojects.findAll { it.projectDir == file }
    if (project) {
        break;
    }
}


问:
npm - EPERM: operation not permitted on Windows
I ran

```<code>npm config set prefix /usr/local
</code>```

After running that command,
When trying to run any npm commands on Windows OS I keep getting the below.

```<code>Error: EPERM: operation not permitted, mkdir 'C:\Program Files (x86)\Git\local'
at Error (native)
</code>```

Have deleted all files from

```<code>C:\Users\<your username>\.config\configstore\
</code>```

It did not work.

Any suggestion ?

答: Just run cmd as admin. delete old node_modules folder and run npm install again.</p>

Body:
I ran

npm config set prefix /usr/local

After running that command,
When trying to run any npm commands on Windows OS I keep getting the below.

Error: EPERM: operation not permitted, mkdir 'C:\Program Files (x86)\Git\local'
at Error (native)

Have deleted all files from

C:\Users\<your username>\.config\configstore\

It did not work.

Any suggestion ?


问:
Intent for a Skype call using email information in the datas
I would like to open a Skype Intent (better with a direct call if possible) using the email of the user.

I find this but it seem it work only with the Skype username :

```<code>Intent skype = new Intent("android.intent.action.VIEW");
skype.setData(Uri.parse("skype:" + "user_name"));
startActivity(skype);
</code>```

It is possible to setData with the email of the Skype account? If not, it is possible to get the username thanks to the email ?

答: It seem it's not possible using email address in the Intent, only using username.</p>

Body:
I would like to open a Skype Intent (better with a direct call if possible) using the email of the user.

I find this but it seem it work only with the Skype username :

Intent skype = new Intent("android.intent.action.VIEW");
skype.setData(Uri.parse("skype:" + "user_name"));
startActivity(skype);

It is possible to setData with the email of the Skype account? If not, it is possible to get the username thanks to the email ?


问:
Get Merged Cell Area with EPPLus
I'm using EPPlus to read excel files.

I have a single cell that is part of merged cells. How do I get the merged range that this cell is part of?

For example:

Assume Range ("A1:C1") has been merged.

Given Range "B1" it's Merge property will be true but there isn't a way to get the merged range given a single cell.

How do you get the merged range?

I was hoping for a .MergedRange which would return Range("A1:C1")

答:
There is no such property out of the box but the worksheet has a MergedCells property with an array of all the merged cell addresses in the worksheet and a GetMergeCellId() method which will give you the index for a given cell address.

We can therefore combine these into a little extension method you can use to get the address. Something like this:

```<code>public static string GetMergedRangeAddress(this ExcelRange @this)
{
    if (@this.Merge)
    {
        var idx = @this.Worksheet.GetMergeCellId(@this.Start.Row, @this.Start.Column);
        return @this.Worksheet.MergedCells[idx-1]; //the array is 0-indexed but the mergeId is 1-indexed...
    }
    else
    {
        return @this.Address;
    }
}
</code>```

which you can use as follows:

```<code>using (var excel = new ExcelPackage(new FileInfo("inputFile.xlsx")))
{
    var ws = excel.Workbook.Worksheets["sheet1"];
    var b3address = ws.Cells["B3"].GetMergedRangeAddress();

}
</code>```

(Note that in the event that you use this method on a multi-celled range it will return the merged cell address for the first cell in the range only)

ContentLicense: CC BY-SA 4.0

Title: Get Merged Cell Area with EPPLus

Body:
There is no such property out of the box but the worksheet has a MergedCells property with an array of all the merged cell addresses in the worksheet and a GetMergeCellId() method which will give you the index for a given cell address.

We can therefore combine these into a little extension method you can use to get the address. Something like this:

public static string GetMergedRangeAddress(this ExcelRange @this)
{
    if (@this.Merge)
    {
        var idx = @this.Worksheet.GetMergeCellId(@this.Start.Row, @this.Start.Column);
        return @this.Worksheet.MergedCells[idx-1]; //the array is 0-indexed but the mergeId is 1-indexed...
    }
    else
    {
        return @this.Address;
    }
}

which you can use as follows:

using (var excel = new ExcelPackage(new FileInfo("inputFile.xlsx")))
{
    var ws = excel.Workbook.Worksheets["sheet1"];
    var b3address = ws.Cells["B3"].GetMergedRangeAddress();

}

(Note that in the event that you use this method on a multi-celled range it will return the merged cell address for the first cell in the range only)


问:
Apache Tomcat Load Balancing Cluster
I am having 3 servers installed with Ubuntu and I want to configure Tomcat Load Balancing.

```<code>Server A = 10.0.0.1,
Server B = 10.0.0.2,
Server C = 10.0.0.3
</code>```

I have pointed Domain to Server A which is having Apache and Mod_JK installed. while Server B and C is having Apache Tomcat 8. below is the Details of my workers.properties file

```<code>workers.apache_log=/var/log/apache2 worker.list=tomcatlb,status
worker.stat1.type=status

worker.tomcat1.type=ajp13 worker.tomcat1.host=10.0.0.2 #put your app
host here worker.tomcat1.port=8009 worker.tomcat2.type=ajp13
worker.tomcat2.host=10.0.0.3 worker.tomcat2.port=8009

worker.tomcat1.lbfactor=1  worker.tomcat2.lbfactor=1

worker.tomcatlb.type=lb
worker.tomcatlb.balance_workers=tomcat1,tomcat2

worker.list=jkstatus worker.jkstatus.type=status
</code>```

I have also used jvmRounte name as tomcat1 and tomcat2 in server.xml of both the Apache Tomcat.

i have also added below lines in server.xml

```<code>      <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">

        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="6">

        <Channel className="org.apache.catalina.tribes.group.GroupChannel">
        <Membership     className="org.apache.catalina.tribes.membership.McastService"
        address="228.0.0.4"
        port="45564" frequency="500"
        dropTime="3000"/>

        <Sender     className="org.apache.catalina.tribes.transport.ReplicationTransmitter">

        <Transport     className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>

        </Sender>

        <Receiver     className="org.apache.catalina.tribes.transport.nio.NioReceiver"
        address="auto" port="4001" autoBind="100"
        selectorTimeout="5000" maxThreads="6"/>

        <Interceptor     className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>

        <Interceptor     className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interc    eptor"/>
        <Interceptor     className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>

        </Channel>
</code>```

context.xml is like below

```<code>http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->

<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->

<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Manager className="org.apache.catalina.ha.session.BackupManager" />

</Context>
</code>```

apache configuration is having below lines

```<code> RewriteEngine on
    RewriteRule ^/$ /test [PT,L]
    JkMount /* tomcatlb
</code>```

apache is redirecting the request to Tomcat via mod_jk and its working fine but when one tomcat goes down it should redirect the request to the other tomcat instead of that I have to do relogin as its not replicating the session.

答:
I'm seeing that you're missing
stickysession=JSESSIONID|jsessionid lbmethod=byrequests nofailover=Off connectiontimeout=5 timeout=30</p>

Title: Apache Tomcat Load Balancing Cluster

Body:
I am having 3 servers installed with Ubuntu and I want to configure Tomcat Load Balancing.

Server A = 10.0.0.1,
Server B = 10.0.0.2,
Server C = 10.0.0.3

I have pointed Domain to Server A which is having Apache and Mod_JK installed. while Server B and C is having Apache Tomcat 8. below is the Details of my workers.properties file

workers.apache_log=/var/log/apache2 worker.list=tomcatlb,status
worker.stat1.type=status

worker.tomcat1.type=ajp13 worker.tomcat1.host=10.0.0.2 #put your app
host here worker.tomcat1.port=8009 worker.tomcat2.type=ajp13
worker.tomcat2.host=10.0.0.3 worker.tomcat2.port=8009

worker.tomcat1.lbfactor=1  worker.tomcat2.lbfactor=1

worker.tomcatlb.type=lb
worker.tomcatlb.balance_workers=tomcat1,tomcat2

worker.list=jkstatus worker.jkstatus.type=status

I have also used jvmRounte name as tomcat1 and tomcat2 in server.xml of both the Apache Tomcat.

i have also added below lines in server.xml

      <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">

        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="6">

        <Channel className="org.apache.catalina.tribes.group.GroupChannel">
        <Membership     className="org.apache.catalina.tribes.membership.McastService"
        address="228.0.0.4"
        port="45564" frequency="500"
        dropTime="3000"/>

        <Sender     className="org.apache.catalina.tribes.transport.ReplicationTransmitter">

        <Transport     className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>

        </Sender>

        <Receiver     className="org.apache.catalina.tribes.transport.nio.NioReceiver"
        address="auto" port="4001" autoBind="100"
        selectorTimeout="5000" maxThreads="6"/>

        <Interceptor     className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>

        <Interceptor     className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interc    eptor"/>
        <Interceptor     className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>

        </Channel>

context.xml is like below

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<Context>

<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Manager className="org.apache.catalina.ha.session.BackupManager" />

</Context>

apache configuration is having below lines

 RewriteEngine on
    RewriteRule ^/$ /test [PT,L]
    JkMount /* tomcatlb

apache is redirecting the request to Tomcat via mod_jk and its working fine but when one tomcat goes down it should redirect the request to the other tomcat instead of that I have to do relogin as its not replicating the session.


问:
global variables typescript not defined
I have a problem with typescript global variable.

I'm writing a piece of code to login with facebook in my ionic 3 app.

I have a global variable declared, but when the app runs, got me the error *.*FB is not defined** at the function FB.init({})

The code:

```<code>//all needed imports

declare const FB;

@Injectable()
export class AuthenticationProvider implements OnInit{

  //properties

  //constructor

   ngOnInit() {
     debugger
     if( FB != null && FB != 'undefined')
     {
       FB.init({
         appId: '***',
         cookie: false,access
         status: true,
         xfbml: true,
         version: 'v2.11'
       });
     }
   }

   //FB.login(){} inside an observable function
   //FB.getLoginStatus(){} inside an observable function
   //FB.api(){} inside an observable function

 }
</code>```

Can someone help me?

答: In TypeScript const is a block scoped variable. For a true global variable you need to use var. </p>

Title: global variables typescript not defined

Body:
I have a problem with typescript global variable.

I'm writing a piece of code to login with facebook in my ionic 3 app.

I have a global variable declared, but when the app runs, got me the error *.*FB is not defined** at the function FB.init({})

The code:

//all needed imports

declare const FB;

@Injectable()
export class AuthenticationProvider implements OnInit{

  //properties

  //constructor

   ngOnInit() {
     debugger
     if( FB != null && FB != 'undefined')
     {
       FB.init({
         appId: '***',
         cookie: false,access
         status: true,
         xfbml: true,
         version: 'v2.11'
       });
     }
   }

   //FB.login(){} inside an observable function
   //FB.getLoginStatus(){} inside an observable function
   //FB.api(){} inside an observable function

 }

Can someone help me?


问:
compilation error in C pointer working in 32 bits, not in 64 bits
I am trying to compile a c program in 64 bits. It is already working in 32 bits for several years and used by some clients.

Example of code working in 32 bits :

```<code>#include <stdio.h>

int main() {

    char* rcfilename ;
    char* vhome ;
    char* script = "/script/main.tcl" ;

    vhome = (char *)getenv("VHOME");
    rcfilename = (char *) malloc(strlen(vhome) + strlen(script) + 1) ;

    strcpy(rcfilename, vhome) ;
    return 0;
}
</code>```

in Compil in 64 bits  i have an error:

conversion between a pointer and an integer of different size

and a segmentation fault in execution.

I have no experience in pointer in c, so i prefer to ask for help !

答:
As mentionned in the comments, you should:

include the proper headers (stdlib.h and string.h)

check for the value return, in particular the getenv call:

```<code>if (!(vhome = (char *)getenv("VHOME"))){
    fprintf(stderr, "getenv(\"VHOME\") returned NULL\n");
    return -1;
}
</code>```

Body:
I am trying to compile a c program in 64 bits. It is already working in 32 bits for several years and used by some clients.

Example of code working in 32 bits :

#include <stdio.h>

int main() {

    char* rcfilename ;
    char* vhome ;
    char* script = "/script/main.tcl" ;

    vhome = (char *)getenv("VHOME");
    rcfilename = (char *) malloc(strlen(vhome) + strlen(script) + 1) ;

    strcpy(rcfilename, vhome) ;
    return 0;
}

in Compil in 64 bits  i have an error:

conversion between a pointer and an integer of different size

and a segmentation fault in execution.

I have no experience in pointer in c, so i prefer to ask for help !

Body:
As mentionned in the comments, you should:

include the proper headers (stdlib.h and string.h)

check for the value return, in particular the getenv call:

if (!(vhome = (char *)getenv("VHOME"))){
    fprintf(stderr, "getenv(\"VHOME\") returned NULL\n");
    return -1;
}


问:
Appname having dots at last of appname
I am having application name as "MYApplication" but it showing me as "MYApplica..." below app icon in mobile.

Now i want to show that fullname as application name, please give me any solution to fix this issue

Note : I have already set appname as "MYApplication" in info.plist (Bundle name)

Thank you.

答:
This is an iOS limitation; not anything that you can control. Even the SE app is effected by this.

Just use a shorter name if you don't want it to be cut off.

The exact cut off point will likely depend on the resolution of the screen it's being displayed on though. If you're worried about how your app name will appear when cut off, you may want to play around with an emulator or something to see how it displays on different devices.

I seem to recall it being possible to effect how many characters are shown if your iPhone is jailbroken, but that only effects your phone obviously, not the phones of people who use your app.

Title: Appname having dots at last of appname


问:
C++ inlining class methods causes undefined reference
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

```<code>#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}
</code>```

my_class.h:

```<code>class MyClass {
 public:
  void TestMethod();
};
</code>```

my_class.cpp:

```<code>#include "my_class.h"

inline void MyClass::TestMethod() {
}
</code>```

I try compiling with:

```<code>g++ main.cpp my_class.cpp
</code>```

I get the error:

```<code>main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'
</code>```

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.

答:
7.1.2/4 of the Standard:

An inline function shall be defined in
  every translation unit in which it is
  used...

You use TestMethod in main.cpp, but it's not defined there.

... If a function with external linkage is
  declared inline in one translation
  unit, it shall be declared inline in
  all translation units in which it
  appears; no diagnostic is required.

You define (and hence also declare) TestMethod inline in my_class.cpp, but not in main.cpp.

The fix in this case is to move the function definition to the header file, either like this:

```<code>class MyClass {
 public:
  void TestMethod() {}
};
</code>```

or like this:

```<code>class MyClass {
 public:
  inline void TestMethod();
};

inline void MyClass::TestMethod() {}
</code>```

Body:
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}

my_class.h:

class MyClass {
 public:
  void TestMethod();
};

my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}

I try compiling with:

g++ main.cpp my_class.cpp

I get the error:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.

Body:
7.1.2/4 of the Standard:

An inline function shall be defined in
  every translation unit in which it is
  used...

You use TestMethod in main.cpp, but it's not defined there.

... If a function with external linkage is
  declared inline in one translation
  unit, it shall be declared inline in
  all translation units in which it
  appears; no diagnostic is required.

You define (and hence also declare) TestMethod inline in my_class.cpp, but not in main.cpp.

The fix in this case is to move the function definition to the header file, either like this:

class MyClass {
 public:
  void TestMethod() {}
};

or like this:

class MyClass {
 public:
  inline void TestMethod();
};

inline void MyClass::TestMethod() {}


问:
How to create new object from List<> by Expression array
I have List and want to be able to define list of Expression which select new object defined in this Expression list.

But I dont know, how to pass Expression list to data.Select().
Someting like this: data.Select(SelectExpressionList)

```<code>public class Test
{
    public void Process()
    {
        var foo = new Foo<User>();

        foo.data.Add(new User() { id = 1, LastName = "User1", Other = "A" });
        foo.data.Add(new User() { id = 2, LastName = "User2", Other = "B" });
        foo.data.Add(new User() { id = 3, LastName = "User3", Other = "C" });

        foo.AddExpression(u => u.id);
        foo.AddExpression(u => u.LastName);

        var result = foo.CreateNewByExpression(); // I want List<> object {id, LastName}

    }

}

public class User
{
    public int id { get; set; }
    public string LastName { get; set; }

    public string Other { get; set; }

}
public class Foo<T>
{

    public List<T> data = new List<T>();

    public List<Expression> SelectExpressionsList = new List<Expression>();
    public List<object> CreateNewByExpression()
    {
        return data.Select(....); // I want List<> object defined by SelectExpressions
    }

    public void AddExpression<TKey>(Expression<Func<T, TKey>> exp)
    {
        SelectExpressionsList.Add(exp);
    }

}
</code>```

Hope, its clear, what I want to achive.
Thanks.

Edit:
It does not have to be Anonymous type. I want List that have only "selected" properties...

答:
You can use ExpandoObject. See my working example.

```<code>using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Dynamic;

public class Program
{
    public static void Main()
    {
        var foo = new Foo<User>();

        foo.data.Add(new User() { id = 1, LastName = "User1", Other = "A" });
        foo.data.Add(new User() { id = 2, LastName = "User2", Other = "B" });
        foo.data.Add(new User() { id = 3, LastName = "User3", Other = "C" });

        foo.AddExpression(u => u.id);
        foo.AddExpression(u => u.LastName);

        var result = foo.CreateNewByExpression();
        Console.WriteLine(result.First().LastName);
    }
}

public class User
{
    public int id { get; set; }

    public string LastName { get; set; }

    public string Other { get; set; }

}

public class Foo<T>
{
    public List<T> data = new List<T>();

    public List<Expression<Func<T, object>>> SelectExpressionsList = new List<Expression<Func<T, object>>>();

    public IEnumerable<dynamic> CreateNewByExpression()
    {
        foreach (var item in data)
        {
            IDictionary<string, object> result = new ExpandoObject();
            foreach (var exp in SelectExpressionsList)
            {
                string name = GetMember(exp.Body).Member.Name;
                result[name] = exp.Compile()(item);
            }

            yield return result as ExpandoObject;
        }
    }

    public void AddExpression(Expression<Func<T, object>> exp)
    {
        SelectExpressionsList.Add(exp);
    }

    public static MemberExpression GetMember(Expression expression)
    {
        MemberExpression exp = null;
        switch (expression.NodeType)
        {
            case ExpressionType.MemberAccess:
                exp = expression as MemberExpression;
                break;
            case ExpressionType.Convert:
                exp = ((UnaryExpression)expression).Operand as MemberExpression;
                break;
            default:
                break;
        }

        return exp;
    }
}
</code>```

Body:
I have List and want to be able to define list of Expression which select new object defined in this Expression list.

But I dont know, how to pass Expression list to data.Select().
Someting like this: data.Select(SelectExpressionList)

public class Test
{
    public void Process()
    {
        var foo = new Foo<User>();

        foo.data.Add(new User() { id = 1, LastName = "User1", Other = "A" });
        foo.data.Add(new User() { id = 2, LastName = "User2", Other = "B" });
        foo.data.Add(new User() { id = 3, LastName = "User3", Other = "C" });

        foo.AddExpression(u => u.id);
        foo.AddExpression(u => u.LastName);

        var result = foo.CreateNewByExpression(); // I want List<> object {id, LastName}

    }

}

public class User
{
    public int id { get; set; }
    public string LastName { get; set; }

    public string Other { get; set; }

}
public class Foo<T>
{

    public List<T> data = new List<T>();

    public List<Expression> SelectExpressionsList = new List<Expression>();
    public List<object> CreateNewByExpression()
    {
        return data.Select(....); // I want List<> object defined by SelectExpressions
    }

    public void AddExpression<TKey>(Expression<Func<T, TKey>> exp)
    {
        SelectExpressionsList.Add(exp);
    }

}

Hope, its clear, what I want to achive.
Thanks.

Edit:
It does not have to be Anonymous type. I want List that have only "selected" properties...

Body:
You can use ExpandoObject. See my working example.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Dynamic;

public class Program
{
    public static void Main()
    {
        var foo = new Foo<User>();

        foo.data.Add(new User() { id = 1, LastName = "User1", Other = "A" });
        foo.data.Add(new User() { id = 2, LastName = "User2", Other = "B" });
        foo.data.Add(new User() { id = 3, LastName = "User3", Other = "C" });

        foo.AddExpression(u => u.id);
        foo.AddExpression(u => u.LastName);

        var result = foo.CreateNewByExpression();
        Console.WriteLine(result.First().LastName);
    }
}

public class User
{
    public int id { get; set; }

    public string LastName { get; set; }

    public string Other { get; set; }

}

public class Foo<T>
{
    public List<T> data = new List<T>();

    public List<Expression<Func<T, object>>> SelectExpressionsList = new List<Expression<Func<T, object>>>();

    public IEnumerable<dynamic> CreateNewByExpression()
    {
        foreach (var item in data)
        {
            IDictionary<string, object> result = new ExpandoObject();
            foreach (var exp in SelectExpressionsList)
            {
                string name = GetMember(exp.Body).Member.Name;
                result[name] = exp.Compile()(item);
            }

            yield return result as ExpandoObject;
        }
    }

    public void AddExpression(Expression<Func<T, object>> exp)
    {
        SelectExpressionsList.Add(exp);
    }

    public static MemberExpression GetMember(Expression expression)
    {
        MemberExpression exp = null;
        switch (expression.NodeType)
        {
            case ExpressionType.MemberAccess:
                exp = expression as MemberExpression;
                break;
            case ExpressionType.Convert:
                exp = ((UnaryExpression)expression).Operand as MemberExpression;
                break;
            default:
                break;
        }

        return exp;
    }
}