问:
Creating WPA2 PSK Access Point in Android Programmatically
I want to create Access Point in android programmatically with the following configurations.
AccessPointName :SomeName
Security:WPA2 PSK
Password:SomeKey

How can i do that?
Regards

答:
I was also facing same problem by passing 4 as KeyMangement solved my problem.

```<code>WifiConfiguration myConfig = new WifiConfiguration();
        myConfig.SSID = ssid; // SSID name of netwok
        myConfig.preSharedKey = password; // password for network
        myConfig.allowedKeyManagement.set(4); // 4 is for KeyMgmt.WPA2_PSK which is not exposed by android KeyMgmt class
        myConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); // Set Auth Algorithms to open
        try {
            Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            return (Boolean) method.invoke(mWifiManager, myConfig, true);  // setting and turing on android wifiap with new configrations
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

Read more at Link

Body:
I was also facing same problem by passing 4 as KeyMangement solved my problem.

WifiConfiguration myConfig = new WifiConfiguration();
        myConfig.SSID = ssid; // SSID name of netwok
        myConfig.preSharedKey = password; // password for network
        myConfig.allowedKeyManagement.set(4); // 4 is for KeyMgmt.WPA2_PSK which is not exposed by android KeyMgmt class
        myConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); // Set Auth Algorithms to open
        try {
            Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            return (Boolean) method.invoke(mWifiManager, myConfig, true);  // setting and turing on android wifiap with new configrations
        } catch (Exception e) {
            e.printStackTrace();
        }

Read more at Link


来源: stackexchange

问:
How to decrypt the first message sent from Mifare Desfire EV1
Does anyone have a clue how to decrypt the first message sent from the card? I mean after the authentication success and then you send a command (for example 0x51 (GetRealTagUID). It returns 00+random32bits (always different). I try to decrypt it with:

```<code>        private byte[] decrypt(byte[] raw, byte[] encrypted, byte[] iv)
            throws Exception {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
</code>```

And calling it with decrypt(sessionKey, response, iv)

IV = all zeros (16 bytes)

response = that 32randombits after the 0x51 command (just removed the two zeros)

Someone told me, that the IV changes after the first sent command (0x51). How to generate the right IV for decrypting that response? I think the all zeros is wrong, because the decrypted message is always different and it should be always same with the same card.

-EDIT-

After applying your (Michael Roland) instructions, the decrypted response is still just random bits. Here is my code (I think I'm doing something wrong):

```<code>            byte[] x = encrypt(sessionKey, iv, iv);

            byte[] rx = rotateBitsLeft(x);

            if ((rx[15] & 0x01) == 0x01)
                rx[15] = (byte) (rx[15] ^ 0x87);

            if ((rx[15] & 0x01) == 0x00)
                rx[15] = (byte) (rx[15] ^ 0x01);

            byte[] crc_k1 = rx;

            byte[] rrx = rotateBitsLeft(rx);

            if ((rrx[15] & 0x01) == 0x01)
                rrx[15] = (byte) (rrx[15] ^ 0x87);

            if ((rrx[15] & 0x01) == 0x00)
                rrx[15] = (byte) (rrx[15] ^ 0x01);

            byte[] crc_k2 = rrx;

            byte[] command = { (byte) 0x51, (byte) 0x80, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                    (byte) 0x00 };

            for (int i = 0; i < 16; i++){
                command[i] = (byte) (command[i] ^ crc_k2[i]);
            }

            byte[] iv2 = encrypt(sessionKey, command, iv);

            byte[] RealUID = decrypt(sessionKey, ReadDataParsed, iv2);

            Log.e("RealUID", ByteArrayToHexString(RealUID));
</code>```

-EDIT3-

Still returning always different values. I think the problem might lie here:

```<code>byte[] iv2 = encrypt(sessionKey, command, iv);
</code>```

What IV to use when creating the new IV for decrypting the response? It is all zeros there.

答:
It's not c/c++ section but enter my position, I'm looking at a possible bug from the C developer.
I can't proof Java implementation here. But i think @Michael Roland way is not true! Maby! Maby i'm wrong!

Sry for my English,- its terrible :) but it's not my native language. I'm Russian.

Check first MSB (7 - bit) of array[0] and then shiffting this to the left. And then XOR if MSB 7 bit was == 1;
Or save first MSB bit of array[0] and after shiffting put this bit at the end of array[15] at the end (LSB bit).

Just proof it's here:
https://www.nxp.com/docs/en/application-note/AN10922.pdf

Try this way:

Zeros <- 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

SessionKey <- 00 01 02 03 E3 27 64 0C 0C 0D 0E 0F 5C 5D B9 D5

Data <- 6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00

First u have to encrypt 16 bytes (zeros) with SesionKey;

```<code>enc_aes_128_ecb(Zeros);
</code>```

And u get EncryptedData.

EncryptedData <- 3D 08 A2 49 D9 71 58 EA 75 73 18 F2 FA 6A 27 AC

Check bit 7 [MSB - LSB] of EncryptedData[0] == 1? switch i to true;

```<code> bool i = false;
  if (EncryptedData[0] & 0x80){
    i = true;
  }
</code>```

Then do Shiffting of all EncryptedData to 1 bit <<.

```<code>ShiftLeft(EncryptedData,16);
</code>```

And now, when i == true - XOR the last byte [15] with 0x87

```<code>if (i){
    ShiftedEncryptedData[15] ^= 0x87;
  }
</code>```

7A 11 44 93 B2 E2 B1 D4 EA E6 31 E5 F4 D4 4F 58

Save it as KEY_1.

Try bit 7 [MSB - LSB] of ShiftedEncryptedData[0] == 1?

```<code> i = false;
  if (ShiftedEncryptedData[0] & 0x80){
    i = true;
  }
</code>```

Then do Shiffting of all ShiftedEncryptedData to 1 bit <<.

```<code>ShiftLeft(ShiftedEncryptedData,16);
</code>```

And now, when i == true - XOR the last byte [15] with 0x87

```<code>if (i){
   ShiftedEncryptedData[15] ^= 0x87;
}
</code>```

F4 22 89 27 65 C5 63 A9 D5 CC 63 CB E9 A8 9E B0

Save it as KEY_2.

Now we take our Data (6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00)

As Michael say's - pad command with 0x80 0x00...

XOR Data with KEY_2 - if command was padded, or KEY_1 if don't.
If we have more like 16 bytes (32 for example) u have to XOR just last 16 bytes.

Then encrypt it:

```<code>enc_aes_128_ecb(Data);
</code>```

Now u have a CMAC.

CD C0 52 62 6D F6 60 CA 9B C1 09 FF EF 64 1A E3

Zeros <- 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

SessionKey <- 00 01 02 03 E3 27 64 0C 0C 0D 0E 0F 5C 5D B9 D5

Key_1 <- 7A 11 44 93 B2 E2 B1 D4 EA E6 31 E5 F4 D4 4F 58

Key_2 <- F4 22 89 27 65 C5 63 A9 D5 CC 63 CB E9 A8 9E B0

Data <- 6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00

CMAC <- CD C0 52 62 6D F6 60 CA 9B C1 09 FF EF 64 1A E3

C/C++ function:

```<code>void ShiftLeft(byte *data, byte dataLen){
  for (int n = 0; n < dataLen - 1; n++) {
   data[n] = ((data[n] << 1) | ((data[n+1] >> 7)&0x01));
  }
  data[dataLen - 1] <<= 1;
}
</code>```

Have a nice day :)

ContentLicense: CC BY-SA 3.0

Body:
Does anyone have a clue how to decrypt the first message sent from the card? I mean after the authentication success and then you send a command (for example 0x51 (GetRealTagUID). It returns 00+random32bits (always different). I try to decrypt it with:

        private byte[] decrypt(byte[] raw, byte[] encrypted, byte[] iv)
            throws Exception {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

And calling it with decrypt(sessionKey, response, iv)

IV = all zeros (16 bytes)

response = that 32randombits after the 0x51 command (just removed the two zeros)

Someone told me, that the IV changes after the first sent command (0x51). How to generate the right IV for decrypting that response? I think the all zeros is wrong, because the decrypted message is always different and it should be always same with the same card.

-EDIT-

After applying your (Michael Roland) instructions, the decrypted response is still just random bits. Here is my code (I think I'm doing something wrong):

            byte[] x = encrypt(sessionKey, iv, iv);

            byte[] rx = rotateBitsLeft(x);

            if ((rx[15] & 0x01) == 0x01)
                rx[15] = (byte) (rx[15] ^ 0x87);

            if ((rx[15] & 0x01) == 0x00)
                rx[15] = (byte) (rx[15] ^ 0x01);

            byte[] crc_k1 = rx;

            byte[] rrx = rotateBitsLeft(rx);

            if ((rrx[15] & 0x01) == 0x01)
                rrx[15] = (byte) (rrx[15] ^ 0x87);

            if ((rrx[15] & 0x01) == 0x00)
                rrx[15] = (byte) (rrx[15] ^ 0x01);

            byte[] crc_k2 = rrx;

            byte[] command = { (byte) 0x51, (byte) 0x80, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
                    (byte) 0x00 };

            for (int i = 0; i < 16; i++){
                command[i] = (byte) (command[i] ^ crc_k2[i]);
            }

            byte[] iv2 = encrypt(sessionKey, command, iv);

            byte[] RealUID = decrypt(sessionKey, ReadDataParsed, iv2);

            Log.e("RealUID", ByteArrayToHexString(RealUID));

-EDIT3-

Still returning always different values. I think the problem might lie here:

byte[] iv2 = encrypt(sessionKey, command, iv);

What IV to use when creating the new IV for decrypting the response? It is all zeros there.

Body:
It's not c/c++ section but enter my position, I'm looking at a possible bug from the C developer.
I can't proof Java implementation here. But i think @Michael Roland way is not true! Maby! Maby i'm wrong!

Sry for my English,- its terrible :) but it's not my native language. I'm Russian.

Check first MSB (7 - bit) of array[0] and then shiffting this to the left. And then XOR if MSB 7 bit was == 1;
Or save first MSB bit of array[0] and after shiffting put this bit at the end of array[15] at the end (LSB bit).

Just proof it's here:
https://www.nxp.com/docs/en/application-note/AN10922.pdf

Try this way:

Zeros <- 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

SessionKey <- 00 01 02 03 E3 27 64 0C 0C 0D 0E 0F 5C 5D B9 D5

Data <- 6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00

First u have to encrypt 16 bytes (zeros) with SesionKey;

enc_aes_128_ecb(Zeros);

And u get EncryptedData.

EncryptedData <- 3D 08 A2 49 D9 71 58 EA 75 73 18 F2 FA 6A 27 AC

Check bit 7 [MSB - LSB] of EncryptedData[0] == 1? switch i to true;

 bool i = false;
  if (EncryptedData[0] & 0x80){
    i = true;
  }

Then do Shiffting of all EncryptedData to 1 bit <<.

ShiftLeft(EncryptedData,16);

And now, when i == true - XOR the last byte [15] with 0x87

if (i){
    ShiftedEncryptedData[15] ^= 0x87;
  }

7A 11 44 93 B2 E2 B1 D4 EA E6 31 E5 F4 D4 4F 58

Save it as KEY_1.

Try bit 7 [MSB - LSB] of ShiftedEncryptedData[0] == 1?

 i = false;
  if (ShiftedEncryptedData[0] & 0x80){
    i = true;
  }

Then do Shiffting of all ShiftedEncryptedData to 1 bit <<.

ShiftLeft(ShiftedEncryptedData,16);

And now, when i == true - XOR the last byte [15] with 0x87

if (i){
   ShiftedEncryptedData[15] ^= 0x87;
}

F4 22 89 27 65 C5 63 A9 D5 CC 63 CB E9 A8 9E B0

Save it as KEY_2.

Now we take our Data (6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00)

As Michael say's - pad command with 0x80 0x00...

XOR Data with KEY_2 - if command was padded, or KEY_1 if don't.
If we have more like 16 bytes (32 for example) u have to XOR just last 16 bytes.

Then encrypt it:

enc_aes_128_ecb(Data);

Now u have a CMAC.

CD C0 52 62 6D F6 60 CA 9B C1 09 FF EF 64 1A E3

Zeros <- 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

SessionKey <- 00 01 02 03 E3 27 64 0C 0C 0D 0E 0F 5C 5D B9 D5

Key_1 <- 7A 11 44 93 B2 E2 B1 D4 EA E6 31 E5 F4 D4 4F 58

Key_2 <- F4 22 89 27 65 C5 63 A9 D5 CC 63 CB E9 A8 9E B0

Data <- 6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00

CMAC <- CD C0 52 62 6D F6 60 CA 9B C1 09 FF EF 64 1A E3

C/C++ function:

void ShiftLeft(byte *data, byte dataLen){
  for (int n = 0; n < dataLen - 1; n++) {
   data[n] = ((data[n] << 1) | ((data[n+1] >> 7)&0x01));
  }
  data[dataLen - 1] <<= 1;
}

Have a nice day :)


答:
The skinIndices and skinWeights properties are arrays of arrays (technically the inner arrays are three.js Vector4 objects). Each item in the outer array of either corresponds, one-to-one, based on the indexed position, with each vertex in the mesh.

Here's the relevant JSONLoader code that creates the values for these properties from a three.js JSON model file:

```<code>if ( json.skinWeights ) {

    for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {

        var x = json.skinWeights[ i ];
        var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
        var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
        var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;

        geometry.skinWeights.push( new Vector4( x, y, z, w ) );

    }

}

if ( json.skinIndices ) {

    for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {

        var a = json.skinIndices[ i ];
        var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
        var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
        var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;

        geometry.skinIndices.push( new Vector4( a, b, c, d ) );

    }
}
</code>```

The docs for the three.js Geometry object were updated to include info about this [some formatting and two inconsistency corrections mine]:

Just like the skinWeights property, the skinIndices' values correspond to the geometry's vertices. Each vertex can have up to 4 bones associated with it. So if you look at the first vertex, and the first skin index, this will tell you the bones associated with that vertex. For example the first vertex could have a value of ( 10.05, 30.10, 12.12 ). Then the first skin index could have the value of ( 10, 2, 0, 0 ). The first skin weight could have the value of ( 0.8, 0.2, 0, 0 ). In affect this would take the first vertex, and then the bone mesh.bones[10] and apply it 80% of the way. Then it would take the bone mesh.bones[2] and apply it 20% of the way. The next two values have a weight of 0, so they would have no affect.

In code another example could look like this:

```<code>// e.g.
geometry.skinIndices[15] = new THREE.Vector4(   0,   5,   9, 0 );
geometry.skinWeights[15] = new THREE.Vector4( 0.2, 0.5, 0.3, 0 );

// corresponds with the following vertex
geometry.vertices[15];

// these bones will be used like so:
skeleton.bones[0]; // weight of 0.2
skeleton.bones[5]; // weight of 0.5
skeleton.bones[9]; // weight of 0.3
skeleton.bones[10]; // weight of 0
</code>```

Title: What is the meaning of skin indices and skin weights?

Body:
This is undocumented, so I'm asking here. I'm trying to animate a mesh in JavaScript. I'm using Blender->Three.js exporter because it is convenient. I can't use Three.js itself because I was not able to figure out how to solve certain problems on it (rendering the normals and depth informations of a scene with animated meshes to a buffer). So, how do you read the "skinIndices" and "skinWeights" properties that get exported from Blender to Three.js? What do they mean, and what are they roles when calculating the position of the vertices on the animations?

"bones" : [
    {"parent":-1,"name":"pelvis","pos":[-3.52132e-08,0.0410043,0.880063],"rotq":[0,0,0,1]},
    {"parent":0,"name":"thigh.L","pos":[0.0878887,0.00522349,0.102822],"rotq":[0,0,0,1]},
    {"parent":1,"name":"shin.L","pos":[0.103679,0.00638392,-0.445744],"rotq":[0,0,0,1]},
    {"parent":2,"name":"foot.L","pos":[0.0655578,0.0194668,-0.418675],"rotq":[0,0,0,1]},
    {"parent":3,"name":"toe.L","pos":[0.0280578,-0.107185,-0.0704246],"rotq":[0,0,0,1]},
    {"parent":3,"name":"heel.L","pos":[3.58224e-05,0.036576,-0.0885088],"rotq":[0,0,0,1]},
    {"parent":0,"name":"thigh.R","pos":[-0.0878888,0.00522352,0.102822],"rotq":[0,0,0,1]},
    {"parent":6,"name":"shin.R","pos":[-0.103679,0.00638412,-0.445745],"rotq":[0,0,0,1]},
    {"parent":7,"name":"foot.R","pos":[-0.0655576,0.0194677,-0.418675],"rotq":[0,0,0,1]},
    {"parent":8,"name":"toe.R","pos":[-0.0280577,-0.107185,-0.0704248],"rotq":[0,0,0,1]},
    {"parent":8,"name":"heel.R","pos":[-3.57926e-05,0.036576,-0.0885083],"rotq":[0,0,0,1]},
    {"parent":0,"name":"stomach","pos":[5.37268e-09,-0.008465,0.121596],"rotq":[0,0,0,1]},
    {"parent":11,"name":"chest","pos":[1.94616e-08,0.0538289,0.269019],"rotq":[0,0,0,1]},
    {"parent":12,"name":"upper_arm.L","pos":[0.160045,-0.010388,0.159844],"rotq":[0,0,0,1]},
    {"parent":13,"name":"forearm.L","pos":[0.165089,0.0102809,-0.232678],"rotq":[0,0,0,1]},
    {"parent":14,"name":"hand.L","pos":[0.0980782,-0.0148839,-0.245313],"rotq":[0,0,0,1]},
    {"parent":15,"name":"index.L.001","pos":[0.019191,-0.040475,-0.0743723],"rotq":[0,0,0,1]},
    {"parent":16,"name":"index.L.002","pos":[-0.00562334,-0.00824448,-0.0310695],"rotq":[0,0,0,1]},
    {"parent":17,"name":"index.L.003","pos":[-0.00953785,-0.00126594,-0.0192741],"rotq":[0,0,0,1]},
    {"parent":15,"name":"middle.L.001","pos":[0.0191911,-0.0188201,-0.0769786],"rotq":[0,0,0,1]},
    {"parent":19,"name":"middle.L.002","pos":[0.00288424,-0.00695575,-0.0326532],"rotq":[0,0,0,1]},
    {"parent":20,"name":"middle.L.003","pos":[-0.0111618,-0.00550338,-0.0242877],"rotq":[0,0,0,1]},
    {"parent":15,"name":"ring.L.001","pos":[0.0186397,0.00194495,-0.0777299],"rotq":[0,0,0,1]},
    {"parent":22,"name":"ring.L.002","pos":[0.00393239,-0.00062982,-0.0309386],"rotq":[0,0,0,1]},
    {"parent":23,"name":"ring.L.003","pos":[-0.00873661,-0.00165674,-0.024165],"rotq":[0,0,0,1]},
    {"parent":15,"name":"pinky.L.001","pos":[0.0191911,0.02271,-0.0758559],"rotq":[0,0,0,1]},
    {"parent":25,"name":"pinky.L.002","pos":[-0.0057596,0.0014303,-0.0236881],"rotq":[0,0,0,1]},
    {"parent":26,"name":"pinky.L.003","pos":[-0.00877053,-0.0020119,-0.0195478],"rotq":[0,0,0,1]},
    {"parent":15,"name":"thumb.L.001","pos":[-0.0073517,-0.0318671,-0.0156776],"rotq":[0,0,0,1]},
    {"parent":28,"name":"thumb.L.002","pos":[-0.00941652,-0.0166059,-0.0179188],"rotq":[0,0,0,1]},
    {"parent":29,"name":"thumb.L.003","pos":[-0.0081799,-0.0129757,-0.0276645],"rotq":[0,0,0,1]},
    {"parent":12,"name":"upper_arm.R","pos":[-0.160044,-0.010388,0.159844],"rotq":[0,0,0,1]},
    {"parent":31,"name":"forearm.R","pos":[-0.165089,0.0102809,-0.232679],"rotq":[0,0,0,1]},
    {"parent":32,"name":"hand.R","pos":[-0.0980774,-0.0148839,-0.245313],"rotq":[0,0,0,1]},
    {"parent":33,"name":"index.R.001","pos":[-0.0185038,-0.0404748,-0.0743726],"rotq":[0,0,0,1]},
    {"parent":34,"name":"index.R.002","pos":[0.00562337,-0.00824449,-0.0310695],"rotq":[0,0,0,1]},
    {"parent":35,"name":"index.R.003","pos":[0.00953785,-0.00126596,-0.0192741],"rotq":[0,0,0,1]},
    {"parent":33,"name":"middle.R.001","pos":[-0.0185038,-0.0188199,-0.0769789],"rotq":[0,0,0,1]},
    {"parent":37,"name":"middle.R.002","pos":[-0.00288421,-0.00695577,-0.0326532],"rotq":[0,0,0,1]},
    {"parent":38,"name":"middle.R.003","pos":[0.0111619,-0.00550339,-0.0242877],"rotq":[0,0,0,1]},
    {"parent":33,"name":"ring.R.001","pos":[-0.0179525,0.00194514,-0.0777302],"rotq":[0,0,0,1]},
    {"parent":40,"name":"ring.R.002","pos":[-0.00393245,-0.000629827,-0.0309386],"rotq":[0,0,0,1]},
    {"parent":41,"name":"ring.R.003","pos":[0.00873658,-0.00165676,-0.024165],"rotq":[0,0,0,1]},
    {"parent":33,"name":"pinky.R.001","pos":[-0.0185039,0.0227101,-0.0758562],"rotq":[0,0,0,1]},
    {"parent":43,"name":"pinky.R.002","pos":[0.0057596,0.00143027,-0.0236881],"rotq":[0,0,0,1]},
    {"parent":44,"name":"pinky.R.003","pos":[0.00877053,-0.00201192,-0.0195478],"rotq":[0,0,0,1]},
    {"parent":33,"name":"thumb.R.001","pos":[0.00803882,-0.0318669,-0.0156779],"rotq":[0,0,0,1]},
    {"parent":46,"name":"thumb.R.002","pos":[0.00941664,-0.0166059,-0.0179188],"rotq":[0,0,0,1]},
    {"parent":47,"name":"thumb.R.003","pos":[0.00817987,-0.0129757,-0.0276645],"rotq":[0,0,0,1]},
    {"parent":12,"name":"neck","pos":[1.6885e-08,-0.0164749,0.225555],"rotq":[0,0,0,1]},
    {"parent":49,"name":"head","pos":[0.000806741,-0.0273245,0.0637051],"rotq":[0,0,0,1]}],

"skinIndices" : [
        11,0,11,0,1,11,11,0,0,11,0,11,1,11,1,11,0,11,11,0,11,0,11,0,1,11,11,0,11,0,0,11,1,11,1,11,0,11,0,11,0,11,12,0,0,11,0,11,
        0,11,12,0,12,0,11,0,11,0,11,0,12,0,11,0,11,0,11,0,12,0,12,11,11,0,11,0,12,13,11,0,0,11,11,0,12,13,12,13,0,11,12,13,12,0,
        12,0,13,12,13,12,12,13,12,0,12,13,13,12,12,13,12,13,13,12,13,0,12,13,12,0,12,13,13,0,12,0,13,0,0,13,13,0,13,0,0,13,0,13,
        13,0,13,0,0,13,13,12,13,12,13,12,13,0,13,0,13,0,13,12,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,13,
        (... too big)]

"skinWeights" : [
    0.454566,0.443267,0.456435,0.4405,0.568642,0.331477,0.452697,0.446034,0.600277,0.577654,0.603738,0.578153,0.557686,0.334716,
    0.579597,0.328238,0.596817,0.577156,0.481496,0.447683,0.604872,0.59171,0.466162,0.448242,0.567426,0.35812,0.49683,0.447124,
    0.618979,0.590887,0.592533,0.590764,0.578989,0.341559,0.555862,0.37468,0.477411,0.438341,0.617349,0.569542,0.454728,0.432345,
    0.401061,0.337472,0.500093,0.444338,0.633534,0.572105,0.601164,0.56698,0.388198,0.308292,0.413925,0.366652,0.449179,0.424051,
    0.618298,0.58735,0.458406,0.430254,0.473939,0,0.439952,0.417849,0.605333,0.579977,0.631263,0.594722,0.517687,0,0.430191,0.274572,
    (... too big)]

"animations" : [
    {"name":"ArmatureAction",
    "fps":24,
    "length":0.625,
    "hierarchy":
    [{"parent":-1,"keys":[
        {"time":0,"pos":[-3.52132e-08,0.0410043,0.880063],"rot":[0,0,0,1],"scl":[1,1,1]},
        {"time":0.291667,"pos":[-3.52132e-08,0.0410043,0.880063]},
        {"time":0.625,"pos":[-3.52132e-08,0.0410043,0.880063],"rot":[0,0,0,1],"scl":[1,1,1]}]
    },
    {"parent":0,"keys":[
        {"time":0,"pos":[0.0878887,0.00522349,0.102822],"rot":[0,0,0,1],"scl":[1,1,1]},
        {"time":0.291667,"pos":[0.0878887,0.00522349,0.102822],"rot":[-0.36166,-1.53668e-08,-7.05768e-10,0.93231]},
        {"time":0.625,"pos":[0.0878887,0.00522349,0.102822],"rot":[0,0,0,1],"scl":[1,1,1]}
    ]},
    {"parent":1,"keys":[
        {"time":0,"pos":[0.103679,0.00638392,-0.445744],"rot":[0,0,0,1],"scl":[1,1,1]},
        {"time":0.291667,"pos":[0.103679,0.00638392,-0.445744]},
        {"time":0.625,"pos":[0.103679,0.00638392,-0.445744],"rot":[0,0,0,1],"scl":[1,1,1]}
    ]},
    {"parent":2,"keys":[
        {"time":0,"pos":[0.0655578,0.0194668,-0.418675],"rot":[0,0,0,1],"scl":[1,1,1]},
        {"time":0.291667,"pos":[0.0655578,0.0194668,-0.418675]},
        {"time":0.625,"pos":[0.0655578,0.0194668,-0.418675],"rot":[0,0,0,1],"scl":[1,1,1]}
    ]},
    {"parent":3,"keys":[
        {"time":0,"pos":[0.0280578,-0.107185,-0.0704246],"rot":[0,0,0,1],"scl":[1,1,1]},
        {"time":0.291667,"pos":[0.0280578,-0.107185,-0.0704246]},
        {"time":0.625,"pos":[0.0280578,-0.107185,-0.0704246],"rot":[0,0,0,1],"scl":[1,1,1]}
    ]},
    {"parent":4,"keys":[
        {"time":0,"pos":[3.58149e-05,0.036576,-0.0885088],"rot":[0,0,0,1],"scl":[1,1,1]},
        {"time":0.291667,"pos":[3.58149e-05,0.036576,-0.0885088]},
        {"time":0.625,"pos":[3.58149e-05,0.036576,-0.0885088],"rot":[0,0,0,1],"scl":[1,1,1]}
    ]},

Body:
The skinIndices and skinWeights properties are arrays of arrays (technically the inner arrays are three.js Vector4 objects). Each item in the outer array of either corresponds, one-to-one, based on the indexed position, with each vertex in the mesh.

Here's the relevant JSONLoader code that creates the values for these properties from a three.js JSON model file:

if ( json.skinWeights ) {

    for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {

        var x = json.skinWeights[ i ];
        var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
        var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
        var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;

        geometry.skinWeights.push( new Vector4( x, y, z, w ) );

    }

}

if ( json.skinIndices ) {

    for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {

        var a = json.skinIndices[ i ];
        var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
        var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
        var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;

        geometry.skinIndices.push( new Vector4( a, b, c, d ) );

    }
}

The docs for the three.js Geometry object were updated to include info about this [some formatting and two inconsistency corrections mine]:

Just like the skinWeights property, the skinIndices' values correspond to the geometry's vertices. Each vertex can have up to 4 bones associated with it. So if you look at the first vertex, and the first skin index, this will tell you the bones associated with that vertex. For example the first vertex could have a value of ( 10.05, 30.10, 12.12 ). Then the first skin index could have the value of ( 10, 2, 0, 0 ). The first skin weight could have the value of ( 0.8, 0.2, 0, 0 ). In affect this would take the first vertex, and then the bone mesh.bones[10] and apply it 80% of the way. Then it would take the bone mesh.bones[2] and apply it 20% of the way. The next two values have a weight of 0, so they would have no affect.

In code another example could look like this:

// e.g.
geometry.skinIndices[15] = new THREE.Vector4(   0,   5,   9, 0 );
geometry.skinWeights[15] = new THREE.Vector4( 0.2, 0.5, 0.3, 0 );

// corresponds with the following vertex
geometry.vertices[15];

// these bones will be used like so:
skeleton.bones[0]; // weight of 0.2
skeleton.bones[5]; // weight of 0.5
skeleton.bones[9]; // weight of 0.3
skeleton.bones[10]; // weight of 0


问:
Eliminate Duplicate IDs in SQL Server View
i am creating this view from different tables . but the problem in view some of the IDS are repeated . i want to eliminate repeated ID from it .how can i do that .I know i have to use Distinct keyword but how can i use it here ?</p>

```<code> SELECT        dbo.Dispatch.Date, dbo.Dispatch.ID AS Dispatch_ID, dbo.Dispatch.Demand_ID AS Dispatch_DemandID, dbo.Dispatch.Full_Weight, dbo.Dispatch.Empty_Weight, dbo.Dispatch.Status, dbo.Dispatch.PDate,
                         dbo.Customer.Name AS CustomerName, dbo.Demand.ID AS Demand_ID, dbo.Material.Bulk_Bags, dbo.Material.Type AS MaterialType, dbo.Material.Name AS MaterialName,
                         dbo.[Order].Order_ID AS Order_Order_ID, dbo.[Order].Order_Date, dbo.Dispatch.PYear, dbo.Dispatch.PWeek, dbo.Dispatch.PMonth, dbo.[Order].Total_Quantity, dbo.[Order].RatePerTon, dbo.[Order].Discount,
                         dbo.[Order].Final_Cost, dbo.[Order].Payment_Mode, dbo.[Order].Tax, dbo.[Order].Added_Value, dbo.Dispatch.Full_Weight - dbo.Dispatch.Empty_Weight AS DeliveredQuantity, dbo.Demand.Order_ID,
                         dbo.Total_Amount_Status.Total_Amount, dbo.Total_Amount_Status.Amount_status
FROM                     dbo.Dispatch INNER JOIN
                         dbo.Demand ON dbo.Dispatch.Demand_ID = dbo.Demand.ID INNER JOIN
                         dbo.[Order] ON dbo.Demand.Order_ID = dbo.[Order].Order_ID INNER JOIN
                         dbo.Material ON dbo.[Order].Material_ID = dbo.Material.ID INNER JOIN
                         dbo.Customer ON dbo.[Order].Customer_ID = dbo.Customer.ID LEFT OUTER JOIN
                         dbo.Total_Amount_Status ON dbo.[Order].Order_ID = dbo.Total_Amount_Status.Order_ID
WHERE        (dbo.Dispatch.Status = 'EXIT') AND (dbo.Dispatch.Date = CONVERT(DATETIME, '2017-12-06 00:00:00', 102)) order by Dispatch.ID desc
</code>```

答:
Just add DISTINCT after SELECT.

You also can have rows with same IDs but different data in another columns. If you dont care about what data to show you can use:

```<code>SELECT TOP 1 WITH TIES
...
ORDER BY ROW_NUMBER() OVER (PARTITION BY dispatch_ID ORDER BY (SELECT NULL))
</code>```

One note: please, use aliases

Body:
i am creating this view from different tables . but the problem in view some of the IDS are repeated . i want to eliminate repeated ID from it .how can i do that .I know i have to use Distinct keyword but how can i use it here ?

 SELECT        dbo.Dispatch.Date, dbo.Dispatch.ID AS Dispatch_ID, dbo.Dispatch.Demand_ID AS Dispatch_DemandID, dbo.Dispatch.Full_Weight, dbo.Dispatch.Empty_Weight, dbo.Dispatch.Status, dbo.Dispatch.PDate,
                         dbo.Customer.Name AS CustomerName, dbo.Demand.ID AS Demand_ID, dbo.Material.Bulk_Bags, dbo.Material.Type AS MaterialType, dbo.Material.Name AS MaterialName,
                         dbo.[Order].Order_ID AS Order_Order_ID, dbo.[Order].Order_Date, dbo.Dispatch.PYear, dbo.Dispatch.PWeek, dbo.Dispatch.PMonth, dbo.[Order].Total_Quantity, dbo.[Order].RatePerTon, dbo.[Order].Discount,
                         dbo.[Order].Final_Cost, dbo.[Order].Payment_Mode, dbo.[Order].Tax, dbo.[Order].Added_Value, dbo.Dispatch.Full_Weight - dbo.Dispatch.Empty_Weight AS DeliveredQuantity, dbo.Demand.Order_ID,
                         dbo.Total_Amount_Status.Total_Amount, dbo.Total_Amount_Status.Amount_status
FROM                     dbo.Dispatch INNER JOIN
                         dbo.Demand ON dbo.Dispatch.Demand_ID = dbo.Demand.ID INNER JOIN
                         dbo.[Order] ON dbo.Demand.Order_ID = dbo.[Order].Order_ID INNER JOIN
                         dbo.Material ON dbo.[Order].Material_ID = dbo.Material.ID INNER JOIN
                         dbo.Customer ON dbo.[Order].Customer_ID = dbo.Customer.ID LEFT OUTER JOIN
                         dbo.Total_Amount_Status ON dbo.[Order].Order_ID = dbo.Total_Amount_Status.Order_ID
WHERE        (dbo.Dispatch.Status = 'EXIT') AND (dbo.Dispatch.Date = CONVERT(DATETIME, '2017-12-06 00:00:00', 102)) order by Dispatch.ID desc

Body:
Just add DISTINCT after SELECT.

You also can have rows with same IDs but different data in another columns. If you dont care about what data to show you can use:

SELECT TOP 1 WITH TIES
...
ORDER BY ROW_NUMBER() OVER (PARTITION BY dispatch_ID ORDER BY (SELECT NULL))

One note: please, use aliases


问:
Eclipse Runnable JAR file export failed. No resources selected
i'm trying to export a Runnable Jar in order to run my project with .bat file, however when trying to export a Runnable jar it fails with massage:

"Jar creation failed. See details for additional information."
< < Details :
No resources selected. See details for additional information.
 Could not find main method from given launch configuration.

Using Windows Server 2012, newest eclipse, jdk and jre. cleaning didn't change anything, nor copying the project to a new one.

Downgrading to 1.8 didn't help as well, I looked at some suggestions for the last couple of hours, none helped.

Of-curse I have static void main(String[] args) in my Runner.java class, and if you click "Run" (with same Run Configuration) from Eclipse it works perfect.

Couldn't find a solution as of now.

6/12 - Update: Adding screenshots of the export process as howlger asked.

I've also tried new workspace according to Akshay Bahadur's suggestion, same result.

https://s3.amazonaws.com/stackover/Screenshot_141.png

https://s3.amazonaws.com/stackover/Screenshot_142.png

https://s3.amazonaws.com/stackover/Screenshot_143.png

6/12 - 2nd Update: Adding
Run Configuration:
https://s3.amazonaws.com/stackover/Screenshot_149.png

7/12 - 3nd Update: Adding
About Eclipse:

Eclipse IDE for Java Developers
Version: Oxygen.1a Release (4.7.1a)
Build id: 20171005-1200
OS: Windows Server 2012 R2, v.6.3, x86_64 / win32

https://s3.amazonaws.com/stackover/Screenshot_155.png

and the main() function is plain Java - no Maven or Gradle:

```<code>public static void main(String[] args) {
    boolean errorNotHappened = true;
    boolean errorWithMailNotHappened = true;
    boolean performDownload = true;
    boolean performEmailSent = true;
    boolean performDataManipulation = true;

    System.out.println("***~~~*** Starting job. If you want more details - turn on debug mode");

    //Downloader d = new Downloader();
    printMsg("Date to use with files: "+getDateToUse());
    printMsg("Write mail for date: "+getYasterdayNiceDate());

    if (performDownload)
    {
        Downloader d = new Downloader();
        d.connectAnd(); //connect to pair server
        errorNotHappened = d.downloadFiles();
        d.disconnectFromServer();
    }

    if (errorNotHappened && performDataManipulation)
    {
        Manipulator m = new Manipulator();
        errorNotHappened = m.work();
        m.terminateManipulator();
    }

    if (performEmailSent)
    {
        GoogleMailer gmail = new GoogleMailer();
        gmail.startMailingService();
        if (errorNotHappened)
            errorWithMailNotHappened = gmail.sendMailWithAttach();
        else
            gmail.sendFailedMail();
        if(!errorWithMailNotHappened)
        {
            gmail.sendFailedMail();
        }
    }
    System.out.println("***~~~*** Job ended.");

}
</code>```

答:
I managed to get the job working by exporting the project to regular Jar file (not Runnable as I originally  tried) and activating from CMD with the following:

```<code>java -cp "C:\Users\Administrator\Desktop\runDebug\rundebug.jar";"C:\Users\Administrator\Desktop\runDebug\activation.jar";"C:\Users\Administrator\Desktop\runDebug\commons-net-3.1.jar";"C:\Users\Administrator\Desktop\runDebug\mail.jar" pairbb.Runner
</code>```

I've wrote this command to a BAT file, and set this BAT file as a windows scheduled task. So right now I get what I need this way, I still however couldn't export it as a Runnable Jar.

Body:
i'm trying to export a Runnable Jar in order to run my project with .bat file, however when trying to export a Runnable jar it fails with massage:

"Jar creation failed. See details for additional information."
< < Details :
No resources selected. See details for additional information.
 Could not find main method from given launch configuration.

Using Windows Server 2012, newest eclipse, jdk and jre. cleaning didn't change anything, nor copying the project to a new one.

Downgrading to 1.8 didn't help as well, I looked at some suggestions for the last couple of hours, none helped.

Of-curse I have static void main(String[] args) in my Runner.java class, and if you click "Run" (with same Run Configuration) from Eclipse it works perfect.

Couldn't find a solution as of now.

6/12 - Update: Adding screenshots of the export process as howlger asked.

I've also tried new workspace according to Akshay Bahadur's suggestion, same result.

https://s3.amazonaws.com/stackover/Screenshot_141.png

https://s3.amazonaws.com/stackover/Screenshot_142.png

https://s3.amazonaws.com/stackover/Screenshot_143.png

6/12 - 2nd Update: Adding
Run Configuration:
https://s3.amazonaws.com/stackover/Screenshot_149.png

7/12 - 3nd Update: Adding
About Eclipse:

Eclipse IDE for Java Developers
Version: Oxygen.1a Release (4.7.1a)
Build id: 20171005-1200
OS: Windows Server 2012 R2, v.6.3, x86_64 / win32

https://s3.amazonaws.com/stackover/Screenshot_155.png

and the main() function is plain Java - no Maven or Gradle:

public static void main(String[] args) {
    boolean errorNotHappened = true;
    boolean errorWithMailNotHappened = true;
    boolean performDownload = true;
    boolean performEmailSent = true;
    boolean performDataManipulation = true;

    System.out.println("***~~~*** Starting job. If you want more details - turn on debug mode");

    //Downloader d = new Downloader();
    printMsg("Date to use with files: "+getDateToUse());
    printMsg("Write mail for date: "+getYasterdayNiceDate());

    if (performDownload)
    {
        Downloader d = new Downloader();
        d.connectAnd(); //connect to pair server
        errorNotHappened = d.downloadFiles();
        d.disconnectFromServer();
    }

    if (errorNotHappened && performDataManipulation)
    {
        Manipulator m = new Manipulator();
        errorNotHappened = m.work();
        m.terminateManipulator();
    }

    if (performEmailSent)
    {
        GoogleMailer gmail = new GoogleMailer();
        gmail.startMailingService();
        if (errorNotHappened)
            errorWithMailNotHappened = gmail.sendMailWithAttach();
        else
            gmail.sendFailedMail();
        if(!errorWithMailNotHappened)
        {
            gmail.sendFailedMail();
        }
    }
    System.out.println("***~~~*** Job ended.");

}

Body:
I managed to get the job working by exporting the project to regular Jar file (not Runnable as I originally  tried) and activating from CMD with the following:

java -cp "C:\Users\Administrator\Desktop\runDebug\rundebug.jar";"C:\Users\Administrator\Desktop\runDebug\activation.jar";"C:\Users\Administrator\Desktop\runDebug\commons-net-3.1.jar";"C:\Users\Administrator\Desktop\runDebug\mail.jar" pairbb.Runner

I've wrote this command to a BAT file, and set this BAT file as a windows scheduled task. So right now I get what I need this way, I still however couldn't export it as a Runnable Jar.


问:
grunt compass give single scss file
I am using grunt compass and I want only to compile a single scss file src/scss/image_slider.scss instead of all the files under scss folder.

Below written code works fine for full scss foler.

```<code>compass: {
        dist: {
            options: {
                sassDir: 'src/scss',
                cssDir: 'src/css',
            }
        }
    },
</code>```

答:
There is an option in grunt-contrib-compass https://github.com/gruntjs/grunt-contrib-compass#specify:

```<code>specify

Type: String|Array

Lets you specify which files you want to compile.
Useful if you don't want to compile the whole folder.
Globbing supported. Ignores filenames starting with underscore.
Paths are relative to the Gruntfile.
</code>```

So you should be able to to:

```<code>compass: {
    dist: {
        options: {
            sassDir: 'src/scss',
            cssDir: 'src/css',
            specify: 'myfile.scss'
        }
    }
},
</code>```

Title: grunt compass give single scss file

Body:
I am using grunt compass and I want only to compile a single scss file src/scss/image_slider.scss instead of all the files under scss folder.

Below written code works fine for full scss foler.

compass: {
        dist: {
            options: {
                sassDir: 'src/scss',
                cssDir: 'src/css',
            }
        }
    },

Body:
There is an option in grunt-contrib-compass https://github.com/gruntjs/grunt-contrib-compass#specify:

specify

Type: String|Array

Lets you specify which files you want to compile.
Useful if you don't want to compile the whole folder.
Globbing supported. Ignores filenames starting with underscore.
Paths are relative to the Gruntfile.

So you should be able to to:

compass: {
    dist: {
        options: {
            sassDir: 'src/scss',
            cssDir: 'src/css',
            specify: 'myfile.scss'
        }
    }
},


问:
Java how to respond to HttpExchange
I am new to Java. I used write server in Golang. I need to send response to the HttpExchange. Here is my code:

```<code>public static void main(String[] args) throws IOException
{
  Server = HttpServer.create(new InetSocketAddress(8000),0);
  Server.createContext("/login", new SimpleHandler());
  Server.setExecutor(null);
  Server.start();
}
class SimpleHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange request) throws IOException
    {
     //Here I need to do like request.Response.Write(200,"DONE");
    }
}
</code>```

答:
Use the sendResponseHeaders(int rCode, long responseLength) method. See the documentation and the example:

```<code>@Override
public void handle(HttpExchange request) throws IOException {
     request.sendResponseHeaders(200, "DONE");
}
</code>```

Title: Java how to respond to HttpExchange

Body:
I am new to Java. I used write server in Golang. I need to send response to the HttpExchange. Here is my code:

public static void main(String[] args) throws IOException
{
  Server = HttpServer.create(new InetSocketAddress(8000),0);
  Server.createContext("/login", new SimpleHandler());
  Server.setExecutor(null);
  Server.start();
}
class SimpleHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange request) throws IOException
    {
     //Here I need to do like request.Response.Write(200,"DONE");
    }
}

Body:
Use the sendResponseHeaders(int rCode, long responseLength) method. See the documentation and the example:

@Override
public void handle(HttpExchange request) throws IOException {
     request.sendResponseHeaders(200, "DONE");
}


问:
Why does docker say that -d and --rm are conflicting options for running a container?
A minor issue but I want to run docker containers in dev with docker run --rm so that I don't have to remove them after I stop them, especially since I'm changing the command line parameters with virtually every run.

However my containers pump out lots of logging onto stdout if I don't use docker run -d.

Then I can't use --rm anymore, because docker complains:

```<code>[adam@gondor ~]$ docker run --rm -d -p 10040:443 --name rproxy adam-rproxy
Conflicting options: --rm and -d
</code>```

Admittedly I could just run stop and rm together on the command line:

docker stop rproxy; docker rm rproxy

but I know I'll forget, get annoyed and start worrying I'm moving out on the autistic spectrum!

docker run options

答:
I cannot reproduce this.

The following detaches fine and can be stopped just fine (resulting in removal, as required) in Docker version 17.09.0-ce, build afdb6d4:

docker run --rm -d --name yes alpine:3.7 yes
```

I also tried adding some ports to closer match your example, but that was no problem either.

Body:
A minor issue but I want to run docker containers in dev with docker run --rm so that I don't have to remove them after I stop them, especially since I'm changing the command line parameters with virtually every run.

However my containers pump out lots of logging onto stdout if I don't use docker run -d.

Then I can't use --rm anymore, because docker complains:

[adam@gondor ~]$ docker run --rm -d -p 10040:443 --name rproxy adam-rproxy
Conflicting options: --rm and -d

Admittedly I could just run stop and rm together on the command line:

docker stop rproxy; docker rm rproxy

but I know I'll forget, get annoyed and start worrying I'm moving out on the autistic spectrum!

docker run options

Body:
I cannot reproduce this.

The following detaches fine and can be stopped just fine (resulting in removal, as required) in Docker version 17.09.0-ce, build afdb6d4:

docker run --rm -d --name yes alpine:3.7 yes

I also tried adding some ports to closer match your example, but that was no problem either.


问:
Check if string contains a substring from a list Excel VBA
I have cells that contain account numbers in column A and strings that contain text and account numbers in column B.

[Data example]

I would like to create a list of accounts and then check if any of those accounts is contained in column B. If it is I want to extract this account number to column C (in the same row it was found). I am a VBA noob so I'm not sure how this could be done.

I asked a similar but much more complex question earlier this week, but this should be easier to "solve".

[This is how I would like it to look like after processing]

There might be other numbers with the same length as the account numbers in column B that are NOT account numbers, so this excludes some solutions.

Body:
In cell C1, use this formula and copy down:

=IF(A1="",INDEX($A$1:$A$16,MATCH(1,INDEX(COUNTIF(B1,"*"&$A$1:$A$16&"*")*($A$1:$A$16<>""),),0)),A1)


问:
Fixed point multiply/divide for 15.16 numbers
I am looking for an algorithm to multiply and divide fixed point 15.16 numbers.

I already have addition and subtraction. Those were easy - simple 32-bit add and subtract. With multiply and divide, I can also add many trigonometric and exponential/log functions. And I think I can deal with just multiply, as my library has a reciprocal function and I can use that to implement division: a * (1/b) = a / b. But a 32-bit multiply does not work as it ignores the radix point.

I am working on a 16-bit microcontroller, so I would like to avoid anything more than 32-bit multiply, which takes about 4 cycles on my processor. It's not crucial though, I'm just trying to replace floating point math.

I have heard I need to shift or rotate the result, but I am not sure how this would help or specifically how to shift it. Any suggestions or help appreciated!

答:
Think of is this way: your number a.b is represented as (a.b * 65536)

If you multiply a.b * c.d the value you get is (a.b * 65536) * (c.d * 65536), so to put this back in the right representation you need to divide by 65536.

When you divide a.b / c.d the value you get is (a.b * 65536) / (c.d * 65536), so to put this back in the right representation you need to multiply by 65536. You should multiply by 65536 before the divide to preserve as many bits as possible in the result.

Of course you can substitute (<< 16) for (* 65536) if that is faster on your processor. Similarly you can substitute (>> 16) for (/ 65536).

Here's a.b * c.d:

```<code>uint32_t result_low = (b * d);
uint32_t result_mid = (a * d) + (b * c);
uint32_t result_high = (a * c);
uint32_t result = (result_high << 16) + result_mid + (result_low >> 16)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Think of is this way: your number a.b is represented as (a.b * 65536)

If you multiply a.b * c.d the value you get is (a.b * 65536) * (c.d * 65536), so to put this back in the right representation you need to divide by 65536.

When you divide a.b / c.d the value you get is (a.b * 65536) / (c.d * 65536), so to put this back in the right representation you need to multiply by 65536. You should multiply by 65536 before the divide to preserve as many bits as possible in the result.

Of course you can substitute (<< 16) for (* 65536) if that is faster on your processor. Similarly you can substitute (>> 16) for (/ 65536).

Here's a.b * c.d:

uint32_t result_low = (b * d);
uint32_t result_mid = (a * d) + (b * c);
uint32_t result_high = (a * c);
uint32_t result = (result_high << 16) + result_mid + (result_low >> 16)


问:
how to select the checkboxes automatically as per the values in an array?
I have some checkboxes like this in my form...

```<code><label><input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label>
</code>```

Now, in javascript I have a string in a format of comma separated values like,

```<code>var projDepts = "1,2,3,4";
</code>```

after using the split function of javascript i have converted it to an array.

Now, my question is I want to select all those checkboxes as per the values in the array. I have tried something but its not working for me,

```<code>var projDepts = "1,2,3,4";
var projDeptArray = projDepts.split(',');
var project_depts = document.getElementsByName("prdept[]");
for (var i = 0; i < projDeptArray.length; i++) {
  for (var j = 0; j < project_depts.length; j++) {
    if (projDeptArray[i] == project_depts[j]) {
      $(project_depts[i]).prop("checked", true)
    }
  }
}
</code>```

This code is not working and none of the checkboxes got checked, I know I am getting somewhere wrong. Please someone help me to a solution for this.

答:
```<code>var projDepts = "1,2,3,4";
var aProjDepts = projDepts.split(",");
var el;

for (var key in aProjDepts) { //Loops through Array
  /*
  Get element where name starts with "project_dept" and value is equal the
  current array value in loop
  */
  el = document.querySelectorAll("[name^=project_dept][value='" + aProjDepts[key] + "']")[0];
  if (el) { //if this element exists...
    el.setAttribute("checked", true); //...set the checkbox true
  }
}
</code>```

Body:
I have some checkboxes like this in my form...

<input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development
 <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing
 <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing
 <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance

Now, in javascript I have a string in a format of comma separated values like,

var projDepts = "1,2,3,4";

after using the split function of javascript i have converted it to an array.

Now, my question is I want to select all those checkboxes as per the values in the array. I have tried something but its not working for me,

var projDepts = "1,2,3,4";
var projDeptArray = projDepts.split(',');
var project_depts = document.getElementsByName("prdept[]");
for (var i = 0; i < projDeptArray.length; i++) {
  for (var j = 0; j < project_depts.length; j++) {
    if (projDeptArray[i] == project_depts[j]) {
      $(project_depts[i]).prop("checked", true)
    }
  }
}

This code is not working and none of the checkboxes got checked, I know I am getting somewhere wrong. Please someone help me to a solution for this.


问:
Why LinkedHashSet has boolean accessOrder set to false
In Java LinkedHashSet is created with backing HashSet creating LinkedHashMap with following LinkedHashMap constructor

```<code>map = new LinkedHashMap<>(initialCapacity, loadFactor);
</code>```

Now in LinkedHashMap, the above constructor in turn calls

```<code> public LinkedHashMap(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor);
    accessOrder = false;
}
</code>```

so is there any way to have a LinkedHashSet with accessOrder set to true?
This can help create LRU cache implementation with LinkedHashSet.

答:
LinkedHashSet doesn't support access order, since you are not accessing elements of a LinkedHashSet.

You add elements to the LinkedHashSet, and you can iterate over them in insertion order.

When you check if an element is a member of the LinkedHashSet, you are not accessing it. You check membership via boolean contains(Object o), calls map.containsKey(o) for the backing map. However, containsKey() doesn't affect the access order of the Map.

On the other hand, the get(Object key) method of LinkedHashMap does affect access order, but it is never used by LinkedHashSet.

Body:
In Java LinkedHashSet is created with backing HashSet creating LinkedHashMap with following LinkedHashMap constructor

map = new LinkedHashMap<>(initialCapacity, loadFactor);

Now in LinkedHashMap, the above constructor in turn calls

 public LinkedHashMap(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor);
    accessOrder = false;
}

so is there any way to have a LinkedHashSet with accessOrder set to true?
This can help create LRU cache implementation with LinkedHashSet.


问:
No such file or directory error when configuring aws on cygwin
I downloaded Cygwin and Python version 2.5. Now I am about to set up an deep learning computer at aws (following this tutorial: https://www.youtube.com/watch?v=8rjRfW4JM2I)

If i run pip install awscli I get this (which is good)

```<code> $ pip install awscli
 Requirement already satisfied: awscli in c:\users\marc\anaconda2    \lib\site-packages
 Requirement already satisfied: s3transfer<0.2.0,>=0.1.9 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
 Requirement already satisfied: rsa<=3.5.0,>=3.1.2 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
 Requirement already satisfied: PyYAML<=3.12,>=3.10 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
 Requirement already satisfied: docutils>=0.10 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
Requirement already satisfied: botocore==1.4.92 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
Requirement already satisfied: colorama<=0.3.7,>=0.2.5 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
Requirement already satisfied: futures<4.0.0,>=2.2.0; python_version == "2.6" or python_version == "2.7" in c:\users\marc\anaconda2\lib\site- packages (from s3transfer<0.2.0,>=0.1.9->awscli)
Requirement already satisfied: pyasn1>=0.1.3 in c:\users\marc\anaconda2\lib\site-packages (from rsa<=3.5.0,>=3.1.2->awscli)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in c:\users\marc\anaconda2\lib\site-packages (from botocore==1.4.92->awscli)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in c:\users\marc\anaconda2\lib\site-packages (from botocore==1.4.92->awscli)
Requirement already satisfied: six>=1.5 in c:\users\marc\anaconda2\lib\site-packages (from python-dateutil<3.0.0,>=2.1->botocore==1.4.92->awscli)
</code>```

However when I want to configure everything and type aws I get:

```<code>$ aws
C:\Users\Marc\Anaconda2\python.exe: can't open file '/cygdrive/c/Users/Marc/Anaconda2/Scripts/aws': [Errno 2] No such file or directory
</code>```

答:
I got on track with the answer by Ryan Chase (however I can't comment on his answer due to insufficient credit on stackoverflow)

after step 4: apt-cyg install python,
which python would return the desired usr/bin/python.
However, running python -i from cygwin still opened up my local anaconda python instead of the cygwin python.

I ended up using this workflow:

pip uninstall awscli

wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg

install apt-cyg /bin

apt-cyg install python

wget https://bootstrap.pypa.io/get-pip.py

/bin/python ~/get-pip.py

/bin/pip install awscli

/bin/aws

etc. so each time, use /bin/... to force cygwin to use it's local version of the program. It's pretty cumbersome, maybe I'll look into better ways of getting cygwin to prefer it's own version of python over the anaconda version.

I also needed to change the setup files from windows to unix style, so:

apt-cyg install dos2unix

dos2unix setup_p2.sh

dos2unix setup_instance.sh

then finally, bash setup_p2.sh

Body:
I downloaded Cygwin and Python version 2.5. Now I am about to set up an deep learning computer at aws (following this tutorial: https://www.youtube.com/watch?v=8rjRfW4JM2I)

If i run pip install awscli I get this (which is good)

 $ pip install awscli
 Requirement already satisfied: awscli in c:\users\marc\anaconda2    \lib\site-packages
 Requirement already satisfied: s3transfer<0.2.0,>=0.1.9 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
 Requirement already satisfied: rsa<=3.5.0,>=3.1.2 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
 Requirement already satisfied: PyYAML<=3.12,>=3.10 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
 Requirement already satisfied: docutils>=0.10 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
Requirement already satisfied: botocore==1.4.92 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
Requirement already satisfied: colorama<=0.3.7,>=0.2.5 in c:\users\marc\anaconda2\lib\site-packages (from awscli)
Requirement already satisfied: futures<4.0.0,>=2.2.0; python_version == "2.6" or python_version == "2.7" in c:\users\marc\anaconda2\lib\site- packages (from s3transfer<0.2.0,>=0.1.9->awscli)
Requirement already satisfied: pyasn1>=0.1.3 in c:\users\marc\anaconda2\lib\site-packages (from rsa<=3.5.0,>=3.1.2->awscli)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in c:\users\marc\anaconda2\lib\site-packages (from botocore==1.4.92->awscli)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in c:\users\marc\anaconda2\lib\site-packages (from botocore==1.4.92->awscli)
Requirement already satisfied: six>=1.5 in c:\users\marc\anaconda2\lib\site-packages (from python-dateutil<3.0.0,>=2.1->botocore==1.4.92->awscli)

However when I want to configure everything and type aws I get:

$ aws
C:\Users\Marc\Anaconda2\python.exe: can't open file '/cygdrive/c/Users/Marc/Anaconda2/Scripts/aws': [Errno 2] No such file or directory


问:
Assign value to combination of two column values in R
I'm looking for an easier way to assign a unique value to a combination of string values from two columns, where:

(colA=2 and colB=4) and (colA=4 and colB=2) are given the same ID

(colA=1 and colB=1) can't happen

colA and colB are strings

Here is a minimal example of a solution that would work if colA and colB where numerics:

```<code>set.seed(3)
a <- sample(1:5, 20, replace = T)
b <- sample(1:5, 20, replace = T)

df<- data.frame(a, b)

library(dplyr)

df<- df %>%
      filter(a!=b) %>%
      mutate(abCombination = a*b) %>%
      arrange(abCombination)

df$abFactor <- factor(df$abCombination, labels = c("combination 1", "combination 2",
                                                   "combination 3", "combination 4",
                                                   "combination 5", "combination 6",
                                                   "combination 7"))
</code>```

I feel that this is an easy task but can't think of:

solution working with strings

more elegant (concise) way to code it.

答:
Assuming that we are looking for a more general approach that works on both numeric/non-numeric, one option is to use the pmin/pmax to paste the elements and then do the factor

```<code>df %>%
   filter(a != b) %>%
   mutate(abCombination = sprintf('%s %s', pmin(a, b), pmax(a, b))) %>%
   arrange(abCombination) %>%
   mutate(abFactor = factor(abCombination, levels = unique(abCombination),
        labels = paste('Combination', seq_len(n_distinct(abCombination))) ))
</code>```

Body:
I'm looking for an easier way to assign a unique value to a combination of string values from two columns, where:

(colA=2 and colB=4) and (colA=4 and colB=2) are given the same ID

(colA=1 and colB=1) can't happen

colA and colB are strings

Here is a minimal example of a solution that would work if colA and colB where numerics:

set.seed(3)
a <- sample(1:5, 20, replace = T)
b <- sample(1:5, 20, replace = T)

df<- data.frame(a, b)

library(dplyr)

df<- df %>%
      filter(a!=b) %>%
      mutate(abCombination = a*b) %>%
      arrange(abCombination)

df$abFactor <- factor(df$abCombination, labels = c("combination 1", "combination 2",
                                                   "combination 3", "combination 4",
                                                   "combination 5", "combination 6",
                                                   "combination 7"))

I feel that this is an easy task but can't think of:

solution working with strings

more elegant (concise) way to code it.

Body:
Assuming that we are looking for a more general approach that works on both numeric/non-numeric, one option is to use the pmin/pmax to paste the elements and then do the factor

df %>%
   filter(a != b) %>%
   mutate(abCombination = sprintf('%s %s', pmin(a, b), pmax(a, b))) %>%
   arrange(abCombination) %>%
   mutate(abFactor = factor(abCombination, levels = unique(abCombination),
        labels = paste('Combination', seq_len(n_distinct(abCombination))) ))


问:
Rails Nginx Passenger not serving font icon files

I am running a Rails 5.1.4 app in production mode. I am using Semantic UI as my css framework and have already ran RAILS_ENV=production rails assets:precompile to compile my assets and font files in the public/assets folder. When I load my website everything works except the icons are replaced by squares.

Here is my config/application.rb:

```<code>class Application < Rails::Application
  config.load_defaults 5.1

  config.assets.paths << Rails.root.join('semantic', 'dist')
  config.assets.precompile << 'themes/default/assets/fonts/*'
end
</code>```

My Nginx file:

```<code>server {
    listen       80;
    server_name  atrium.michaelvasallo.com;
    passenger_enabled on;
    rails_env production;
    root /var/www/atrium/public;
}
</code>```

As you can see Semantic UI is looking in themes/default/assets/fonts/ and that is where my icon files are located. They are all showing up in the public/assets folder when I precompile but they are not being served when the page is loaded.

答:
Not a fix, but I found a better solution. In my semantic/src/site/globals/site.variables I set the font path to the Semantic UI CDN instead of fetching from local files.

```<code>@fontPath: 'https://cdn.jsdelivr.net/npm/semantic-ui@2.2.13/dist/themes/default/assets/fonts';
</code>```

Body:
I am running a Rails 5.1.4 app in production mode. I am using Semantic UI as my css framework and have already ran RAILS_ENV=production rails assets:precompile to compile my assets and font files in the public/assets folder. When I load my website everything works except the icons are replaced by squares.

Here is my config/application.rb:

class Application < Rails::Application
  config.load_defaults 5.1

  config.assets.paths << Rails.root.join('semantic', 'dist')
  config.assets.precompile << 'themes/default/assets/fonts/*'
end

My Nginx file:

server {
    listen       80;
    server_name  atrium.michaelvasallo.com;
    passenger_enabled on;
    rails_env production;
    root /var/www/atrium/public;
}

As you can see Semantic UI is looking in themes/default/assets/fonts/ and that is where my icon files are located. They are all showing up in the public/assets folder when I precompile but they are not being served when the page is loaded.

Body:
Not a fix, but I found a better solution. In my semantic/src/site/globals/site.variables I set the font path to the Semantic UI CDN instead of fetching from local files.

@fontPath: 'https://cdn.jsdelivr.net/npm/semantic-ui@2.2.13/dist/themes/default/assets/fonts';


问:
Possible to update cache from subdomain?
is it possible to renew or reach the cached data from subdomain?

For instance I have a blog domain (http://foo.com) and my blog admin is in the subdomain (http://admin.foo.com) and they are in same hosting. In blog page I'm caching articles. When I added new article from adminpage I want to renew the cache so people on the blog page they can see new article.
I also wrote same cached method when I added new article to renew cache to admin side but nothing happened.

I'm using HttpCache.

```<code>CacheHelper.Add("Articles", myArticles, 180, CacheEnum.HttpCache);

HttpContext.Current.Cache.Insert(
                    name,
                    obj,
                    null,
                    DateTime.Now.AddMinutes(minutes),
                    Cache.NoSlidingExpiration,
                    System.Web.Caching.CacheItemPriority.Normal,
                    null);
</code>```

答:
You can't update main domain cache from sub domain. Because both main and sub domain are using different cache and session area on IIS.

But you can use http post.
If you send request a key to main URL, you can getting value key on main domain URL and you can process by key.

Body:
is it possible to renew or reach the cached data from subdomain?

For instance I have a blog domain (http://foo.com) and my blog admin is in the subdomain (http://admin.foo.com) and they are in same hosting. In blog page I'm caching articles. When I added new article from adminpage I want to renew the cache so people on the blog page they can see new article.
I also wrote same cached method when I added new article to renew cache to admin side but nothing happened.

I'm using HttpCache.

CacheHelper.Add("Articles", myArticles, 180, CacheEnum.HttpCache);

HttpContext.Current.Cache.Insert(
                    name,
                    obj,
                    null,
                    DateTime.Now.AddMinutes(minutes),
                    Cache.NoSlidingExpiration,
                    System.Web.Caching.CacheItemPriority.Normal,
                    null);


问:
UIDatePicker changing size
How do I change the size of a UIDatePicker? Setting the frame doesn't seem to work. It only changes the size of the black background on a UIDatePicker, not the actual components within the Picker.</p>

答:
You can only change the width of a UIPickerView.

However, a common user interface solution is to put the picker into an UIActionSheet (or other similar modal dialog).

Title: UIDatePicker changing size


问:
Each row editable using ui-grid AngularJS
I need to make row editable instead of each field/column. I am also following the tutorial for tutorial for row edit feature

Please find the plnkr link also where I am trying to make row editable instead of each column. I have the button on each row but it doesn't have any functioning.

plnkr link

```<code>  $scope.gridOptions.columnDefs = [
    { name: 'id'},
    { name: 'age'  },
    {name: " Edit" , cellTemplate:'<button class=\"btn btn-xs btn-primary\" ng-click=\"grid.appScope.openModal(grid, row)\"> <i class="fa fa-edit" ></i></button>' }];
</code>```

答:
You can use the 'cellEditableCondition' option on each field and then put one variable to change the status of the fields.

```<code>  $scope.gridOptions.columnDefs = [
{ name: 'id'},
{ name: 'age', edicellEditableCondition : variable (true or false) }...]
</code>```

And then you can change all rows only with one.
Hope it helps.

Body:
I need to make row editable instead of each field/column. I am also following the tutorial for tutorial for row edit feature

Please find the plnkr link also where I am trying to make row editable instead of each column. I have the button on each row but it doesn't have any functioning.

plnkr link

  $scope.gridOptions.columnDefs = [
    { name: 'id'},
    { name: 'age'  },
    {name: " Edit" , cellTemplate:'<button class=\"btn btn-xs btn-primary\" ng-click=\"grid.appScope.openModal(grid, row)\"> </button>' }];

Body:
You can use the 'cellEditableCondition' option on each field and then put one variable to change the status of the fields.

  $scope.gridOptions.columnDefs = [
{ name: 'id'},
{ name: 'age', edicellEditableCondition : variable (true or false) }...]

And then you can change all rows only with one.
Hope it helps.


问:
Master and Worker Clustering: On which core is the Master running?
On the documentation-page of Node.js clusters there are some examples where the workers are "spawned" like this:

```<code>  // Start workers and listen for messages containing notifyRequest
  const numCPUs = require('os').cpus().length;
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
</code>```

This means that for every CPU - core one worker is spawned, right?
On which CPU-Core is the master ? Node.js is single threaded so if there is only one master then there has to be 2 processes on at least one CPU - Core because the master has to run on one of the CPU-Cores. Is my assumption correct?

答:
Yes, if you, for example, have 4 logical cores, a master node will be sharing a core with one of 4 workers, which isn't a big deal since the master node shouldn't handle any heavy load.

But here is a catch as os.cpus returns an amount of logical cores, not physical ones <s>it still should be fine if your application is I/O bound but for heavy computation tasks, you probably should consider limiting the number of workers to amount physical cores instead(or use another runtime).</s>

Body:
On the documentation-page of Node.js clusters there are some examples where the workers are "spawned" like this:

  // Start workers and listen for messages containing notifyRequest
  const numCPUs = require('os').cpus().length;
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

This means that for every CPU - core one worker is spawned, right?
On which CPU-Core is the master ? Node.js is single threaded so if there is only one master then there has to be 2 processes on at least one CPU - Core because the master has to run on one of the CPU-Cores. Is my assumption correct?

ContentLicense: CC BY-SA 4.0


问:
D3 sunburst second tier doesn't occupy full width of first tier
I'm making a D3 sunburst plot, with the inner layer the first categories, and outer layer the subcategories of the first categories. For example in my data, I want to show that out of all samples, there are 67% unverified and 33% verified, and out of the verified category 51% of those are illegal and 49% are not, and out of the unverified category, 36% of those are low risk, 20% mid and 44% high risk. I expected the second layer to occupy the full width of the category they belong to in the first layer, but it is not the case, I get the following instead.

Here is my code, could someone maybe point me in the right direction of how to get the results I am looking for? Thank you.

var nodeData = {
  "name": "CATEGORY",
  "children": [{
    "name": "verified",
    "size": 33,
    "children": [{
      "name": "illegal",
      "size": 51
    }, {
      "name": "legal",
      "size": 49
    }]
  }, {
    "name": "unverified",
    "size": 67,
    "children": [{
      "name": "low risk",
      "size": 36
    }, {
      "name": "mid risk",
      "size": 20
    }, {
      "name": "high risk",
      "size": 44
    }]
  }]
};

var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory20b);
var g = d3.select('svg')
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');

var partition = d3.partition()
  .size([2 * Math.PI, radius]);

var root = d3.hierarchy(nodeData)
  .sum(function(d) {
    return d.size
  });

partition(root);
var arc = d3.arc()
  .startAngle(function(d) {
    return d.x0
  })
  .endAngle(function(d) {
    return d.x1
  })
  .innerRadius(function(d) {
    return d.y0
  })
  .outerRadius(function(d) {
    return d.y1
  });

g.selectAll('path')
  .data(root.descendants())
  .enter()
  .append('path')
  .attr("display", function(d) {
    return d.depth ? null : "none";
  })
  .attr("d", arc)
  .style('stroke', '#fff')
  .style("fill", function(d) {
    return color((d.children ? d : d.parent).data.name);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg></code>```

答:
You should have size only for the children. Total children sum should be equal 100.

```<code>var nodeData = {"name": "CATEGORY","children": [{
"name": "verified",
"children": [{
  "name": "illegal",
  "size": 33 * (51/100)
}, {
  "name": "legal",
  "size": 33 * (49/100) }]}, {
"name": "unverified",
"children": [{
  "name": "low risk",
  "size": 67 * (36/100)}, {
  "name": "mid risk",
  "size": 67 * (20/100)}, {
  "name": "high risk",
  "size": 67 * (44/100)}] }]};
</code>```

here is fiddle

Body:
I'm making a D3 sunburst plot, with the inner layer the first categories, and outer layer the subcategories of the first categories. For example in my data, I want to show that out of all samples, there are 67% unverified and 33% verified, and out of the verified category 51% of those are illegal and 49% are not, and out of the unverified category, 36% of those are low risk, 20% mid and 44% high risk. I expected the second layer to occupy the full width of the category they belong to in the first layer, but it is not the case, I get the following instead.

Here is my code, could someone maybe point me in the right direction of how to get the results I am looking for? Thank you.

var nodeData = {
  "name": "CATEGORY",
  "children": [{
    "name": "verified",
    "size": 33,
    "children": [{
      "name": "illegal",
      "size": 51
    }, {
      "name": "legal",
      "size": 49
    }]
  }, {
    "name": "unverified",
    "size": 67,
    "children": [{
      "name": "low risk",
      "size": 36
    }, {
      "name": "mid risk",
      "size": 20
    }, {
      "name": "high risk",
      "size": 44
    }]
  }]
};

var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory20b);
var g = d3.select('svg')
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');

var partition = d3.partition()
  .size([2 * Math.PI, radius]);

var root = d3.hierarchy(nodeData)
  .sum(function(d) {
    return d.size
  });

partition(root);
var arc = d3.arc()
  .startAngle(function(d) {
    return d.x0
  })
  .endAngle(function(d) {
    return d.x1
  })
  .innerRadius(function(d) {
    return d.y0
  })
  .outerRadius(function(d) {
    return d.y1
  });

g.selectAll('path')
  .data(root.descendants())
  .enter()
  .append('path')
  .attr("display", function(d) {
    return d.depth ? null : "none";
  })
  .attr("d", arc)
  .style('stroke', '#fff')
  .style("fill", function(d) {
    return color((d.children ? d : d.parent).data.name);
  });

<svg></svg>

Body:
You should have size only for the children. Total children sum should be equal 100.

var nodeData = {"name": "CATEGORY","children": [{
"name": "verified",
"children": [{
  "name": "illegal",
  "size": 33 * (51/100)
}, {
  "name": "legal",
  "size": 33 * (49/100) }]}, {
"name": "unverified",
"children": [{
  "name": "low risk",
  "size": 67 * (36/100)}, {
  "name": "mid risk",
  "size": 67 * (20/100)}, {
  "name": "high risk",
  "size": 67 * (44/100)}] }]};

here is fiddle


问:
How to detect resizing of ttk.Treeview column?
I have a ttk.Notebook and each tab contains a ttk.Treeview. All treeviews have the same columns but contain different items, like in the code below.

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

notebook = ttk.Notebook(root)
notebook.pack()

tree1 = ttk.Treeview(notebook, columns=['a', 'b', 'c'])
tree1.insert('', 'end', text='item1', values=('a1', 'b1', 'c1'))
tree2 = ttk.Treeview(notebook, columns=['a', 'b', 'c'])
tree2.insert('', 'end', text='item2', values=('a2', 'b2', 'c2'))
tree2.insert('', 'end', text='item2', values=('a2', 'b2', 'c2'))

notebook.add(tree1, text='Tab 1')
notebook.add(tree2, text='Tab 2')

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

I would like all trees to always have the same column widths. So, for instance, when the user resizes the column 'a' of tree1, the column 'a' of tree2 should be resized too.

I know I can get the size of a column with
tree1.column('a', 'width') and set it  with tree2.column('a', width=300).

But how can I detect that the size of a column has changed?

I have checked that the treeview <Configure> event is not triggered by a column resizing.

答:
Following CommonSense suggestions, I have made a binding on <ButtonRelease-1> to check if a column has been resized. If tree.identify_region(event.x, event.y) is 'separator' then there was a resizing. Then I need to identify the columns on both sides of the separator.
tree.identify_column(event.x) gives me the column on the left in the form '#<column number>' and from it I can get the id of the column on the right.
Finally, I execute the function that resize the columns in all trees.

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def on_click_release(event):
    tree = event.widget
    if tree.identify_region(event.x, event.y) == 'separator':
        left_column = tree.identify_column(event.x)
        right_column = '#%i' % (int(tree.identify_column(event.x)[1:]) + 1)
        width_l = tree.column(left_column, 'width')
        width_r = tree.column(right_column, 'width')
        for tree2 in trees:
            if tree2 != tree:
                tree2.column(left_column, width=width_l)
                tree2.column(right_column, width=width_r)

notebook = ttk.Notebook(root)
notebook.pack()

trees = [ttk.Treeview(notebook, columns=['a', 'b', 'c']) for i in range(4)]

for i, tree in enumerate(trees):
    tree.bind('<ButtonRelease-1>', on_click_release)
    notebook.add(tree, text='Tab %i' % i)

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

EDIT: I realized that the above method does not work if we move the column separator too quickly (tree.identify_region(event.x, event.y) does not return 'separator'). So I have found a different method: When the user changes tab, then the width of each column of the current tab is set to the width of the corresponding column of the previously visible tab.

```<code>import tkinter as tk
from tkinter import ttk

def tab_changed(event):
    global current_tab
    tab = notebook.index('current')  # get newly visible tab number
    tree1 = trees[current_tab]  # get previously visible tree
    tree2 = trees[tab]   # get newly visible tree
    cols = ('#0', ) + tree1.cget('columns')  # tuple of all columns
    for column in cols:
        tree2.column(column, width=tree1.column(column, 'width'))
    current_tab = tab

root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()

trees = [ttk.Treeview(notebook, columns=['a', 'b', 'c']) for i in range(4)]
current_tab = 0  # store currently visible tab number

for i, tree in enumerate(trees):
    notebook.bind('<<NotebookTabChanged>>', tab_changed)
    notebook.add(tree, text='Tab %i' % i)

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

Body:
I have a ttk.Notebook and each tab contains a ttk.Treeview. All treeviews have the same columns but contain different items, like in the code below.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

notebook = ttk.Notebook(root)
notebook.pack()

tree1 = ttk.Treeview(notebook, columns=['a', 'b', 'c'])
tree1.insert('', 'end', text='item1', values=('a1', 'b1', 'c1'))
tree2 = ttk.Treeview(notebook, columns=['a', 'b', 'c'])
tree2.insert('', 'end', text='item2', values=('a2', 'b2', 'c2'))
tree2.insert('', 'end', text='item2', values=('a2', 'b2', 'c2'))

notebook.add(tree1, text='Tab 1')
notebook.add(tree2, text='Tab 2')

root.mainloop()

I would like all trees to always have the same column widths. So, for instance, when the user resizes the column 'a' of tree1, the column 'a' of tree2 should be resized too.

I know I can get the size of a column with
tree1.column('a', 'width') and set it  with tree2.column('a', width=300).

But how can I detect that the size of a column has changed?

I have checked that the treeview <Configure> event is not triggered by a column resizing.

Body:
Following CommonSense suggestions, I have made a binding on <ButtonRelease-1> to check if a column has been resized. If tree.identify_region(event.x, event.y) is 'separator' then there was a resizing. Then I need to identify the columns on both sides of the separator.
tree.identify_column(event.x) gives me the column on the left in the form '#<column number>' and from it I can get the id of the column on the right.
Finally, I execute the function that resize the columns in all trees.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def on_click_release(event):
    tree = event.widget
    if tree.identify_region(event.x, event.y) == 'separator':
        left_column = tree.identify_column(event.x)
        right_column = '#%i' % (int(tree.identify_column(event.x)[1:]) + 1)
        width_l = tree.column(left_column, 'width')
        width_r = tree.column(right_column, 'width')
        for tree2 in trees:
            if tree2 != tree:
                tree2.column(left_column, width=width_l)
                tree2.column(right_column, width=width_r)

notebook = ttk.Notebook(root)
notebook.pack()

trees = [ttk.Treeview(notebook, columns=['a', 'b', 'c']) for i in range(4)]

for i, tree in enumerate(trees):
    tree.bind('<ButtonRelease-1>', on_click_release)
    notebook.add(tree, text='Tab %i' % i)

root.mainloop()

EDIT: I realized that the above method does not work if we move the column separator too quickly (tree.identify_region(event.x, event.y) does not return 'separator'). So I have found a different method: When the user changes tab, then the width of each column of the current tab is set to the width of the corresponding column of the previously visible tab.

import tkinter as tk
from tkinter import ttk

def tab_changed(event):
    global current_tab
    tab = notebook.index('current')  # get newly visible tab number
    tree1 = trees[current_tab]  # get previously visible tree
    tree2 = trees[tab]   # get newly visible tree
    cols = ('#0', ) + tree1.cget('columns')  # tuple of all columns
    for column in cols:
        tree2.column(column, width=tree1.column(column, 'width'))
    current_tab = tab

root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()

trees = [ttk.Treeview(notebook, columns=['a', 'b', 'c']) for i in range(4)]
current_tab = 0  # store currently visible tab number

for i, tree in enumerate(trees):
    notebook.bind('<<NotebookTabChanged>>', tab_changed)
    notebook.add(tree, text='Tab %i' % i)

root.mainloop()


问:
Confusion with string pointers
```<code>#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}
</code>```

The output is: C is here.

Can anyone explain this to me its confusing me.

答:
Here, switch(*(1+"AB" "CD"+1)) is evaluated like switch(*(2+"ABCD")). *(2+"ABCD") points to character C. that's why output of your code is C is here.

*(any thing) is evaluated as pointer to a string literal.

Title: Confusion with string pointers

Body:
#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}

The output is: C is here.

Can anyone explain this to me its confusing me.


问:
Bulk importing JSON into SQL Server
I need to bulk import data into a SQL Server database.

My JSON looks like this:

```<code>$projectsJSON = @"
[
    {
        "id":  35,
        "created_at":  "2016-01-12T11:40:36+01:00",
        "customer_id":  34,
        "name":  ".com",
        "note":  "COMXXXX-",
        "updated_at":  "2016-07-15T12:13:54+02:00",
        "archived":  false,
        "customer_name":  "PMName"
    },
    {
        "id":  23,
        "created_at":  "2010-01-11T12:58:50+01:00",
        "customer_id":  43,
        "name":  "PN",
        "note":  "{\r\n    \"Billable\": 1\r\n}\r\n",
        "updated_at":  "2017-11-24T15:49:31+01:00",
        "archived":  false,
        "customer_name":  "MSM"
    }
]
"@

$projects = $projectsJSON |ConvertFrom-Json
$dt2 = New-Object system.Data.DataTable
$dt2 = $projects|select-object id, created_at, customer_id, name, note, updated_at, archived, customer_name

$bulkCopy = New-Object Data.SqlClient.SqlBulkCopy($DestConnStr, [System.Data.SqlClient.SqlBulkCopyOptions]::KeepIdentity)
$bulkCopy.BulkCopyTimeout = 600
$bulkCopy.DestinationTableName = "project"
$bulkCopy.WriteToServer($dt2)
</code>```

Unfortunatelly, I keep getting this error:

Cannot convert argument "rows", with value: "System.Object[]", for
  "WriteToServer" to type "System.Data.DataRow[]": "Cannot convert the
  "@{id=35; created_at=2016-01-12T11:40:36+01:00; customer_id=34;
  name=.com; note=COMXXXX-; updated_at=2016-07-15T12:13:54+02:00;
  archived=False; customer_name=PMName}" value of type
  "Selected.System.Management.Automation.PSCustomObject" to type
  "System.Data.DataRow"." At P:\PsideSync\sync.ps1:261 char:3
  +         $bulkCopy.WriteToServer($dt2)
  +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodException
      + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

What would be the right way to import lots of JSON Data into SQL Server?

TIA

答:
As @IRon notes you are filling $dt2 twice. I assume you want to go with the second initialization.

You could get Out-DataTable from here: https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-8048468d29dd

Then it's just a matter of calling

```<code>$projects = $projectsJSON |ConvertFrom-Json
$dt2 = $projects|select-object id, created_at, customer_id, name, note, updated_at, archived, customer_name

$bulkCopy = New-Object Data.SqlClient.SqlBulkCopy($DestConnStr, [System.Data.SqlClient.SqlBulkCopyOptions]::KeepIdentity)
$bulkCopy.BulkCopyTimeout = 600
$bulkCopy.DestinationTableName = "project"
$bulkCopy.WriteToServer($dt2 | Out-DataTable)
</code>```

Disclaimer: I haven't tried this myself.

Title: Bulk importing JSON into SQL Server

Body:
I need to bulk import data into a SQL Server database.

My JSON looks like this:

$projectsJSON = @"
[
    {
        "id":  35,
        "created_at":  "2016-01-12T11:40:36+01:00",
        "customer_id":  34,
        "name":  ".com",
        "note":  "COMXXXX-",
        "updated_at":  "2016-07-15T12:13:54+02:00",
        "archived":  false,
        "customer_name":  "PMName"
    },
    {
        "id":  23,
        "created_at":  "2010-01-11T12:58:50+01:00",
        "customer_id":  43,
        "name":  "PN",
        "note":  "{\r\n    \"Billable\": 1\r\n}\r\n",
        "updated_at":  "2017-11-24T15:49:31+01:00",
        "archived":  false,
        "customer_name":  "MSM"
    }
]
"@

$projects = $projectsJSON |ConvertFrom-Json
$dt2 = New-Object system.Data.DataTable
$dt2 = $projects|select-object id, created_at, customer_id, name, note, updated_at, archived, customer_name

$bulkCopy = New-Object Data.SqlClient.SqlBulkCopy($DestConnStr, [System.Data.SqlClient.SqlBulkCopyOptions]::KeepIdentity)
$bulkCopy.BulkCopyTimeout = 600
$bulkCopy.DestinationTableName = "project"
$bulkCopy.WriteToServer($dt2)

Unfortunatelly, I keep getting this error:

Cannot convert argument "rows", with value: "System.Object[]", for
  "WriteToServer" to type "System.Data.DataRow[]": "Cannot convert the
  "@{id=35; created_at=2016-01-12T11:40:36+01:00; customer_id=34;
  name=.com; note=COMXXXX-; updated_at=2016-07-15T12:13:54+02:00;
  archived=False; customer_name=PMName}" value of type
  "Selected.System.Management.Automation.PSCustomObject" to type
  "System.Data.DataRow"." At P:\PsideSync\sync.ps1:261 char:3
  +         $bulkCopy.WriteToServer($dt2)
  +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodException
      + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

What would be the right way to import lots of JSON Data into SQL Server?

TIA

Body:
As @IRon notes you are filling $dt2 twice. I assume you want to go with the second initialization.

You could get Out-DataTable from here: https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-8048468d29dd

Then it's just a matter of calling

$projects = $projectsJSON |ConvertFrom-Json
$dt2 = $projects|select-object id, created_at, customer_id, name, note, updated_at, archived, customer_name

$bulkCopy = New-Object Data.SqlClient.SqlBulkCopy($DestConnStr, [System.Data.SqlClient.SqlBulkCopyOptions]::KeepIdentity)
$bulkCopy.BulkCopyTimeout = 600
$bulkCopy.DestinationTableName = "project"
$bulkCopy.WriteToServer($dt2 | Out-DataTable)

Disclaimer: I haven't tried this myself.


问:
Need help to gather data from a txt file and insert in a web page?
could someone advise me on the most efficient way to gather data from one source, select a specific piece of data and insert it in a web page? Specifically, I wish to:

Call up this buoy data text file: http://www.ndbc.noaa.gov/data/realtime2/46237.txt

Find the water temperature and insert that value in my web page.

First big question: What scripting language should I use? (I'm assuming Fortran is not an option :-)

Second not so big question: This same data set is available in graphic and xml format. Would either of these data formats be more useful than the .txt file?

Thanks in advance.

答:
This text file format is just about as simple as it could ever get. Just about any scripting or general purpose programming language will work. The critical part is to split each line on a regex "\s+". i.e. in Python it would be:

```<code>import re

theFileObject = open('/path/to/downloaded/file.txt')
for line in theFileObject.readlines():
    columns = re.split(r'\s+', line)
    # each column is columns[0] through columns[19]
</code>```

So basically choose whatever programming language seems easiest to you. Any .NET language would be equally capable, as well as ruby, python, scheme, etc. I personally have a distaste for perl because I find it very difficult to read

Body:
This text file format is just about as simple as it could ever get. Just about any scripting or general purpose programming language will work. The critical part is to split each line on a regex "\s+". i.e. in Python it would be:

import re

theFileObject = open('/path/to/downloaded/file.txt')
for line in theFileObject.readlines():
    columns = re.split(r'\s+', line)
    # each column is columns[0] through columns[19]

So basically choose whatever programming language seems easiest to you. Any .NET language would be equally capable, as well as ruby, python, scheme, etc. I personally have a distaste for perl because I find it very difficult to read


问:
Not able to start MongoDB
I have installed MongoDB in the C drive. the bin folder is in the below path.
i have also created the data and log folders.within the data folder have created a folder named db

```<code>C:\Program Files\MongoDB\Server\3.4\bin
</code>```

i have opened the cmd and navigated to the bin folder and type the below command

```<code>mongod --directoryperdb --dbpath C:\Program Files\MongoDB\Server\3.4\data\db --logpath C:\Program Files\MongoDB\Server\3.4\log\mongo.log --logappend --rest --install
</code>```

i am getting the below error

and when i type the below command also i am getting an error

guys i am clueless ,pls help me out

答:
can you try this:

```<code>mongod --directoryperdb --dbpath "C:\Program Files\MongoDB\Server\3.4\data\db" --logpath "C:\Program Files\MongoDB\Server\3.4\log\mongo.log" --logappend --rest --install
</code>```

The error can be because of the space between "Program Files".

For the second error, it is because MongoDB is not installed as a service.
You can check you this answer to see how to setup mongo as a service.

Title: Not able to start MongoDB

Body:
I have installed MongoDB in the C drive. the bin folder is in the below path.
i have also created the data and log folders.within the data folder have created a folder named db

C:\Program Files\MongoDB\Server\3.4\bin

i have opened the cmd and navigated to the bin folder and type the below command

mongod --directoryperdb --dbpath C:\Program Files\MongoDB\Server\3.4\data\db --logpath C:\Program Files\MongoDB\Server\3.4\log\mongo.log --logappend --rest --install

i am getting the below error

and when i type the below command also i am getting an error

guys i am clueless ,pls help me out

Body:
can you try this:

mongod --directoryperdb --dbpath "C:\Program Files\MongoDB\Server\3.4\data\db" --logpath "C:\Program Files\MongoDB\Server\3.4\log\mongo.log" --logappend --rest --install

The error can be because of the space between "Program Files".

For the second error, it is because MongoDB is not installed as a service.
You can check you this answer to see how to setup mongo as a service.


问:
How to combine (append) generic Lists in Java without using Javas Collection Framework?
is there an efficient way to combine two generic doube linked lists without using the Collection Framework of Java? The lists are already sorted, so it is only necessary to append the second list to the first one. So far I tried this way, but I am not sure if this is the correct approach:

```<code>public void combineWith(List<T> anotherList) {
    DoubleLinkedList<T> list1 = new DoubleLinkedList<>();

    anotherList = new DoubleLinkedList<>();

    list1= this;

    if(this.next==null) {
        list1.next= (DoubleLinkedList<T>) anotherList;

    }
</code>```

Thanks in advance.

答:
Try the Method I posted below. Obviously this only works if it is placed within the class DoubleLinkedList, which I assume it is, since you set list1 = this which would only be possible if this already is a DoubleLinkedList.

first is the first element (or node) of the DoubleLinkedList and last is the last element (or node) of the DoubleLinkedList. If you don't have those saved as a global variable, I'd either do so or implement another method to find the first and last element.

```<code>public void combineWith(DoubleLinkedList<T> anotherList) {
        if(anotherList.isEmpty()) return;
        if(this.isEmpty()){
                this = anotherList;
                return;
        }
        this.last.next = anotherList.first;
        anotherList.first.previous = this.last;
}
</code>```

Body:
is there an efficient way to combine two generic doube linked lists without using the Collection Framework of Java? The lists are already sorted, so it is only necessary to append the second list to the first one. So far I tried this way, but I am not sure if this is the correct approach:

public void combineWith(List<T> anotherList) {
    DoubleLinkedList<T> list1 = new DoubleLinkedList<>();

    anotherList = new DoubleLinkedList<>();

    list1= this;

    if(this.next==null) {
        list1.next= (DoubleLinkedList<T>) anotherList;

    }

Thanks in advance.

Body:
Try the Method I posted below. Obviously this only works if it is placed within the class DoubleLinkedList, which I assume it is, since you set list1 = this which would only be possible if this already is a DoubleLinkedList.

first is the first element (or node) of the DoubleLinkedList and last is the last element (or node) of the DoubleLinkedList. If you don't have those saved as a global variable, I'd either do so or implement another method to find the first and last element.

public void combineWith(DoubleLinkedList<T> anotherList) {
        if(anotherList.isEmpty()) return;
        if(this.isEmpty()){
                this = anotherList;
                return;
        }
        this.last.next = anotherList.first;
        anotherList.first.previous = this.last;
}


问:
Joining two Models with the same name in Keras Tensorflow
I was trying to combine two models to concatenate outputs to a new model so that i could get prediction of both models like this

model_age = load_model('age.h5')
# model_age.get_layer(name= 'model').name='predictions_1'

model_gender = load_model('gender.h5')
# model_gender.get_layer(name='model_1').name='predictions_2'

x = Input(shape=[100, 100, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])

data = cv2.imread(image)
p_age, p_gender = model.predict(data)

print(p_age)
print(p_gender)
```

<p>but this error keeps happening that says </p>

```RuntimeError: (u'The name "model_1" is used 2 times in the model. All
layer names should be unique. Layer names: ', ['input_1', u'model_1',
u'model_1'])
```

tried solving that using the code commented above but says those models don't have a layer named 'model_1'

答:
Models are Containers, which are also Layers. This allows us to easily re-utilize entire networks' weights:

x = Input(...)
layer_output = Dense(...)(x)
model_output = Model(...)(x)
```

<p>You have this problem because both models were created without a name, in different python executions:</p>

<pre class="lang-py prettyprint-override"><code># this was done:
m = Model(inputs=x, outputs=y)

# instead of this:
m = Model(inputs=x, outputs=y, name='model_age')
# and this, in a different execution:
m = Model(inputs=x, outputs=y, name='model_gender')
</code>```

This results in two models with the same default name, which is 'model_1'. Because no model can contain multiple layers with the same name (model.get_layer(...) wouldn't know what to do), you need to modify one of their names (or both) before merging into a single model:

model_age.name = 'model_age'
model_gender.name = 'model_gender'

x = Input(shape=[100, 100, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])
```

Body:
I was trying to combine two models to concatenate outputs to a new model so that i could get prediction of both models like this

model_age = load_model('age.h5')
# model_age.get_layer(name= 'model').name='predictions_1'

model_gender = load_model('gender.h5')
# model_gender.get_layer(name='model_1').name='predictions_2'

x = Input(shape=[100, 100, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])

data = cv2.imread(image)
p_age, p_gender = model.predict(data)

print(p_age)
print(p_gender)

but this error keeps happening that says

RuntimeError: (u'The name "model_1" is used 2 times in the model. All
layer names should be unique. Layer names: ', ['input_1', u'model_1',
u'model_1'])

tried solving that using the code commented above but says those models don't have a layer named 'model_1'

Body:
Models are Containers, which are also Layers. This allows us to easily re-utilize entire networks' weights:

x = Input(...)
layer_output = Dense(...)(x)
model_output = Model(...)(x)

You have this problem because both models were created without a name, in different python executions:

# this was done:
m = Model(inputs=x, outputs=y)

# instead of this:
m = Model(inputs=x, outputs=y, name='model_age')
# and this, in a different execution:
m = Model(inputs=x, outputs=y, name='model_gender')

This results in two models with the same default name, which is 'model_1'. Because no model can contain multiple layers with the same name (model.get_layer(...) wouldn't know what to do), you need to modify one of their names (or both) before merging into a single model:

model_age.name = 'model_age'
model_gender.name = 'model_gender'

x = Input(shape=[100, 100, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])