问:
Encrypting in C# and Decrypting with Crypto++ does not work
Encryption :

```<code>    public static byte[] EncryptAES(Message msg)
    {

        byte[] encText; // This will keep the encrypted text
        byte[] encLength; // This will keep the length of the encrypted text
        byte[] finalEncText = null; // This keeps the encLength + encText (#####[encText] / [encLength][encText])

        // Building the plaintext message :
        string plainText = msg.MessageCode.ToString();

        if (msg.Parameters != null)
            foreach (string parameter in msg.Parameters)
                plainText += parameter;

        // Encrypting the plaintext :
        encText = EncryptAES(plainText);

        string encLen = encText.Length.ToString();
        string fittedEncLen = MessageSender.FitStringIntoSize(encLen, Globals.MESSAGE_LENGTH_LEN); // Fit the length of the encrypted text into a certain size
        encLength = Encoding.ASCII.GetBytes(fittedEncLen); // convert the length into byte[]

        finalEncText = new byte[encLength.Length + encText.Length];
        System.Buffer.BlockCopy(encLength, 0, finalEncText, 0, encLength.Length);
        System.Buffer.BlockCopy(encText, 0, finalEncText, encLength.Length, encText.Length); // Copy the byte arrays into the new byte array

        return finalEncText;
    }

    private static byte[] EncryptAES(string text)
    {
        // This function encrypts a plaintext message using the aes key we have from the server

        if (AesKey == null || IV == null) // If we dont have an aes key / iv, dont encrypt
            return Encoding.ASCII.GetBytes(text);

        byte[] encryptedText;

        try
        {
            Aes aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            aes.Key = Encoding.ASCII.GetBytes(AesKey);
            aes.IV = Encoding.ASCII.GetBytes(IV);

            ICryptoTransform cryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream memStream = new MemoryStream())
            {
                using (CryptoStream crypotStream = new CryptoStream(memStream, cryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter writerStream = new StreamWriter(crypotStream))
                    {
                        writerStream.Write(text);
                    }
                    encryptedText = memStream.ToArray();
                }
            }

            aes.Dispose();
        }
        catch
        {
            // In case of an error while encrypting, dont encrypt
            encryptedText = Encoding.ASCII.GetBytes(text);
        }
        return encryptedText;
    }
</code>```

[The added fittedEncLen is basically a prefix of fixed length of 5 chars, that contains the length of the encrypted message following it, before decrypting the server reads those 5 chars and then it decrypts the encrypted part]

Sending the message to the server [TCPClient] [C#] :

```<code>public int Send(Message message)
        {
            /*
             * Encrpyts the message and then sends it to the network stream.
             *
             * Return code:
             *      0 on success.
             *      -1 on failure.
             */

            byte[] msg = Cryptography.EncryptAES(message); // Encrypt the message
            // Sending message

            try
            {
                this._networkStream.Write(msg, 0, msg.Length);
                this._networkStream.Flush();
            }
            catch
            {
                return -1;
            }
            return 0;
        }
</code>```

Receiving [C++] :

```<code>wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    std::wstringstream cls;
    cls << getPartFromSocket(sc, bytesNum, 0);
    return cls.str();
}

char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
    if (bytesNum == 0)
        return "";

    char* data = new char[bytesNum + 1];
    int res = recv(sc, data, bytesNum, flags);

    if (res == INVALID_SOCKET)
    {
        string s = "Error while recieving from socket: ";
        s += to_string(sc);
        throw exception(s.c_str());
    }

    data[bytesNum] = 0;

    return data;
}

BufferedString* Helper::makeBufferedString(SOCKET sc)
    {
        /*
            The socket contains <length of encrypted message (unencrypted)> <encrypted message>.

            This function will read the length of the unencrypted message, read
            the encrypted message, decrypt it, store it in a BufferedString
            object and return the object.

            Length of length number: MESSAGE_LENGTH_LEN.
        */

        int sizeOfMessage = Helper::getIntPartFromSocket(sc, MESSAGE_LENGTH_LEN);
        if (sizeOfMessage == 0)
            return NULL;

        wstring wideString = getWideStringPartFromSocket(sc, sizeOfMessage);
        string decrypted = "";

        if (wideString.length() < sizeOfMessage)
        {
            std::wstringstream cls;
            cls << wideString;
            cls << getWideStringPartFromSocket(sc, sizeOfMessage - wideString.length());
            wideString = cls.str();
        }

        SocketEncryptionKeychain* keyChain = SocketEncryptionKeychain::getKeychain(sc);

        if (keyChain != nullptr) // If the socket has a keychain, decrypt the message
            decrypted = Cryptography::decryptAES(wideString, keyChain->getKey(), keyChain->getIV()); // Try to decrypt the message
        else // If the keychain is null, just convert the widestring to a string
            decrypted = wideStringToString(wideString);

        return new BufferedString(decrypted);
    }
</code>```

SocketEncryptionKeychain basically contains the AES Key and IV for each socket
BufferedString is a class that contains the string, and you can read from it like you read from a socket [its a buffer that once you read from it, what you read is deleted] [basically a string buffer, nothing special]

Decrypting [C++]:

```<code>string Cryptography::decryptAES(wstring cipherText, byte aesKey[], byte iv[])
{
    if (aesKey == nullptr || iv == nullptr) // If the key or iv are null, dont decrypt
        return Helper::wideStringToString(cipherText);

    string plaintext;
    try
    {
        // Decrypt :
        byte* cipher = wideStringToByteArray(cipherText); // Convert the wide string to byte*

        CryptoPP::AES::Decryption aesDecryption(aesKey, 32);
        CryptoPP::CBC_Mode_ExternalCipher::Decryption ecbDecryption(aesDecryption, iv);

        CryptoPP::StreamTransformationFilter stfDecryptor(ecbDecryption, new CryptoPP::StringSink(plaintext), StreamTransformationFilter::ZEROS_PADDING);
        stfDecryptor.Put(cipher, cipherText.length());
        stfDecryptor.MessageEnd();

        Helper::safeDelete(cipher);
    }
    catch (CryptoPP::InvalidCiphertext& ex)
    {
        // In case of an error don't decrypt
        plaintext = Helper::wideStringToString(cipherText);
    }

    return plaintext;
}

byte* Cryptography::wideStringToByteArray(wstring text)
{
    // This function translates the wstring into a byte*
    byte* bytes = new byte[text.length()]; // Convert the wstring to byte*
    for (int i = 0; i < text.length(); i++)
    {
        bytes[i] = text[i];
    }
    return bytes;
}
</code>```

[Helper::safeDelete is a function that just deletes the pointer and sets it as null]

The decryption only fails once in a while

答:
So, the problem was while parsing the char* to wstring in the function

The problem in this function is the way I parse it:

```<code>wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    std::wstringstream cls;
    cls << getPartFromSocket(sc, bytesNum, 0);
    return cls.str();
}
</code>```

I used a wstringstream, and the encrypted text can sometimes contain null-terminating character.

So instead of using a wstringstream I used this:

```<code>wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    char* readBuffer = getPartFromSocket(sc, bytesNum, 0);

    return wstring(&readBuffer[0], &readBuffer[bytesNum]);
}
</code>```

and then it does not cut the message at null-character

Body:
Encryption :

    public static byte[] EncryptAES(Message msg)
    {

        byte[] encText; // This will keep the encrypted text
        byte[] encLength; // This will keep the length of the encrypted text
        byte[] finalEncText = null; // This keeps the encLength + encText (#####[encText] / [encLength][encText])

        // Building the plaintext message :
        string plainText = msg.MessageCode.ToString();

        if (msg.Parameters != null)
            foreach (string parameter in msg.Parameters)
                plainText += parameter;

        // Encrypting the plaintext :
        encText = EncryptAES(plainText);

        string encLen = encText.Length.ToString();
        string fittedEncLen = MessageSender.FitStringIntoSize(encLen, Globals.MESSAGE_LENGTH_LEN); // Fit the length of the encrypted text into a certain size
        encLength = Encoding.ASCII.GetBytes(fittedEncLen); // convert the length into byte[]

        finalEncText = new byte[encLength.Length + encText.Length];
        System.Buffer.BlockCopy(encLength, 0, finalEncText, 0, encLength.Length);
        System.Buffer.BlockCopy(encText, 0, finalEncText, encLength.Length, encText.Length); // Copy the byte arrays into the new byte array

        return finalEncText;
    }

    private static byte[] EncryptAES(string text)
    {
        // This function encrypts a plaintext message using the aes key we have from the server

        if (AesKey == null || IV == null) // If we dont have an aes key / iv, dont encrypt
            return Encoding.ASCII.GetBytes(text);

        byte[] encryptedText;

        try
        {
            Aes aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            aes.Key = Encoding.ASCII.GetBytes(AesKey);
            aes.IV = Encoding.ASCII.GetBytes(IV);

            ICryptoTransform cryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream memStream = new MemoryStream())
            {
                using (CryptoStream crypotStream = new CryptoStream(memStream, cryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter writerStream = new StreamWriter(crypotStream))
                    {
                        writerStream.Write(text);
                    }
                    encryptedText = memStream.ToArray();
                }
            }

            aes.Dispose();
        }
        catch
        {
            // In case of an error while encrypting, dont encrypt
            encryptedText = Encoding.ASCII.GetBytes(text);
        }
        return encryptedText;
    }

[The added fittedEncLen is basically a prefix of fixed length of 5 chars, that contains the length of the encrypted message following it, before decrypting the server reads those 5 chars and then it decrypts the encrypted part]

Sending the message to the server [TCPClient] [C#] :

public int Send(Message message)
        {
            /*
             * Encrpyts the message and then sends it to the network stream.
             *
             * Return code:
             *      0 on success.
             *      -1 on failure.
             */

            byte[] msg = Cryptography.EncryptAES(message); // Encrypt the message
            // Sending message

            try
            {
                this._networkStream.Write(msg, 0, msg.Length);
                this._networkStream.Flush();
            }
            catch
            {
                return -1;
            }
            return 0;
        }

Receiving [C++] :

wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    std::wstringstream cls;
    cls << getPartFromSocket(sc, bytesNum, 0);
    return cls.str();
}

char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
    if (bytesNum == 0)
        return "";

    char* data = new char[bytesNum + 1];
    int res = recv(sc, data, bytesNum, flags);

    if (res == INVALID_SOCKET)
    {
        string s = "Error while recieving from socket: ";
        s += to_string(sc);
        throw exception(s.c_str());
    }

    data[bytesNum] = 0;

    return data;
}

BufferedString* Helper::makeBufferedString(SOCKET sc)
    {
        /*
            The socket contains <length of encrypted message (unencrypted)> <encrypted message>.

            This function will read the length of the unencrypted message, read
            the encrypted message, decrypt it, store it in a BufferedString
            object and return the object.

            Length of length number: MESSAGE_LENGTH_LEN.
        */

        int sizeOfMessage = Helper::getIntPartFromSocket(sc, MESSAGE_LENGTH_LEN);
        if (sizeOfMessage == 0)
            return NULL;

        wstring wideString = getWideStringPartFromSocket(sc, sizeOfMessage);
        string decrypted = "";

        if (wideString.length() < sizeOfMessage)
        {
            std::wstringstream cls;
            cls << wideString;
            cls << getWideStringPartFromSocket(sc, sizeOfMessage - wideString.length());
            wideString = cls.str();
        }

        SocketEncryptionKeychain* keyChain = SocketEncryptionKeychain::getKeychain(sc);

        if (keyChain != nullptr) // If the socket has a keychain, decrypt the message
            decrypted = Cryptography::decryptAES(wideString, keyChain->getKey(), keyChain->getIV()); // Try to decrypt the message
        else // If the keychain is null, just convert the widestring to a string
            decrypted = wideStringToString(wideString);

        return new BufferedString(decrypted);
    }

SocketEncryptionKeychain basically contains the AES Key and IV for each socket
BufferedString is a class that contains the string, and you can read from it like you read from a socket [its a buffer that once you read from it, what you read is deleted] [basically a string buffer, nothing special]

Decrypting [C++]:

string Cryptography::decryptAES(wstring cipherText, byte aesKey[], byte iv[])
{
    if (aesKey == nullptr || iv == nullptr) // If the key or iv are null, dont decrypt
        return Helper::wideStringToString(cipherText);

    string plaintext;
    try
    {
        // Decrypt :
        byte* cipher = wideStringToByteArray(cipherText); // Convert the wide string to byte*

        CryptoPP::AES::Decryption aesDecryption(aesKey, 32);
        CryptoPP::CBC_Mode_ExternalCipher::Decryption ecbDecryption(aesDecryption, iv);

        CryptoPP::StreamTransformationFilter stfDecryptor(ecbDecryption, new CryptoPP::StringSink(plaintext), StreamTransformationFilter::ZEROS_PADDING);
        stfDecryptor.Put(cipher, cipherText.length());
        stfDecryptor.MessageEnd();

        Helper::safeDelete(cipher);
    }
    catch (CryptoPP::InvalidCiphertext& ex)
    {
        // In case of an error don't decrypt
        plaintext = Helper::wideStringToString(cipherText);
    }

    return plaintext;
}

byte* Cryptography::wideStringToByteArray(wstring text)
{
    // This function translates the wstring into a byte*
    byte* bytes = new byte[text.length()]; // Convert the wstring to byte*
    for (int i = 0; i < text.length(); i++)
    {
        bytes[i] = text[i];
    }
    return bytes;
}

[Helper::safeDelete is a function that just deletes the pointer and sets it as null]

The decryption only fails once in a while

Body:
So, the problem was while parsing the char* to wstring in the function

The problem in this function is the way I parse it:

wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    std::wstringstream cls;
    cls << getPartFromSocket(sc, bytesNum, 0);
    return cls.str();
}

I used a wstringstream, and the encrypted text can sometimes contain null-terminating character.

So instead of using a wstringstream I used this:

wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    char* readBuffer = getPartFromSocket(sc, bytesNum, 0);

    return wstring(&readBuffer[0], &readBuffer[bytesNum]);
}

and then it does not cut the message at null-character


来源: stackexchange

问:
Checkbox style Foreground color not changing although style definded
Please see this Checkbox style:

```<code><Style TargetType="{x:Type CheckBox}">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="Height" Value="20" />
    <Setter Property="FocusVisualStyle" Value="{DynamicResource MyFocusVisualStyte}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CheckBox}">
                <BulletDecorator>
                    <BulletDecorator.Bullet>
                        <Grid Height="{TemplateBinding Height}"
                                  Width="{Binding RelativeSource={RelativeSource Self}, Path=Height, UpdateSourceTrigger=PropertyChanged}"
                                  MinHeight="20"
                                  MinWidth="20"
                                  ShowGridLines="False">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="4*" />
                                <ColumnDefinition Width="1*" />
                                <ColumnDefinition Width="1*" />
                                <ColumnDefinition Width="4*" />
                                <ColumnDefinition Width="1*" />
                                <ColumnDefinition Width="1*" />
                                <ColumnDefinition Width="2*" />
                                <ColumnDefinition Width="2*" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="3*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="4*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="4*" />
                            </Grid.RowDefinitions>
                            <Border
                                Name="MainBorder"
                                Grid.ColumnSpan="9"
                                Grid.RowSpan="9"
                                CornerRadius="4"
                                BorderThickness="1"
                                Background="Transparent" />
                            <Border
                                Name="InnerBorder"
                                Grid.Column="1"
                                Grid.ColumnSpan="5"
                                Grid.Row="2"
                                Grid.RowSpan="5"
                                BorderThickness="1"
                                BorderBrush="Gray" />
                            <Path
                                Name="InnerPath"
                                Grid.Column="1"
                                Grid.ColumnSpan="5"
                                Grid.Row="2"
                                Grid.RowSpan="5"
                                Data="M31,5 L19.5,5 19.5,19.5 34.5,19.5 34.5,11.75"
                                Stretch="Fill"
                                Stroke="Gray"/>
                            <Path
                                Name="CheckMark"
                                Grid.Column="2"
                                Grid.ColumnSpan="5"
                                Grid.Row="1"
                                Grid.RowSpan="5"
                                Opacity="0"
                                Data="M9.07743946676476E-09,4.31805768640244L4.68740335877841,8.86361158398516C4.68740335877841,8.86361158398516,16.3281249985376,-2.42451336648723,16.3281249985376,-2.42451336648723L14.0622100581796,-4.77304938341948 4.68740335877846,4.31805791992662 2.22656251699567,1.93164208562579z"
                                Fill="Orange"
                                Stretch="Fill"
                                Stroke="Orange" />
                            <Path
                                Name="InderminateMark"
                                Grid.Column="3"
                                Grid.Row="4"
                                Data="M0,4 L1,5 5,1 4,0"
                                Opacity="0"
                                Stretch="Fill"
                                StrokeThickness="0"
                                Fill="#808080" />
                        </Grid>
                    </BulletDecorator.Bullet>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CheckStates">
                            <VisualState x:Name="Checked">
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                         Storyboard.TargetName="CheckMark" Duration="0:0:0.2" To="1" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unchecked" >
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                         Storyboard.TargetName="CheckMark" Duration="0:0:0.2" To="0" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Indeterminate">
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                         Storyboard.TargetName="InderminateMark" Duration="0:0:0.2" To="1" />
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter
                            Margin="4,0,4,0"
                            VerticalAlignment="Center"
                            HorizontalAlignment="Left"
                            RecognizesAccessKey="True" />
                </BulletDecorator>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="InnerBorder" Property="BorderBrush" Value="#FF7AA0CD" />
                        <Setter TargetName="InnerPath" Property="Stroke" Value="#FF7AA0CD" />
                        <Setter TargetName="CheckMark" Property="Fill" Value="Gainsboro"/>
                        <Setter TargetName="CheckMark" Property="Stroke" Value="Gainsboro"/>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
                        <Setter Property="Foreground" Value="#303030"/>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter TargetName="MainBorder" Property="Background" Value="#81d2eb" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="True">
                        <Setter Property="Foreground" Value="Gainsboro"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Foreground" Value="#55B3B3B6"/>
                        <Setter TargetName="CheckMark" Property="Fill" Value="Orange" />
                        <Setter TargetName="CheckMark" Property="Stroke" Value="Orange" />
                        <Setter TargetName="InnerPath" Property="Stroke" Value="#55649EB4" />
                        <Setter TargetName="InderminateMark" Property="Fill" Value="#cccccc" />
                        <Setter TargetName="InnerBorder" Property="BorderBrush" Value="#55649EB4" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

So i try to add very simple style for Foreground Color when my Checkbox is checked:

```<code><Trigger Property="IsChecked" Value="True">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
    <Setter Property="Foreground" Value="#303030"/>
</Trigger>
</code>```

And for some reason this is not working and Foreground color not changing.
Any suggestion why ?

Update

This is my Checkbox:

```<code><CheckBox
    FontSize="14"
    Height="25"
    FontFamily="Ariel"/>
</code>```

As you can see i am not set here Foreground property.

答:
Here's the order of some of your triggers:

```<code><Trigger Property="IsChecked" Value="True">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
    <Setter Property="Foreground" Value="Red"/>
</Trigger>
<Trigger Property="IsChecked" Value="False">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
    <Setter TargetName="MainBorder" Property="Background" Value="#81d2eb" />
</Trigger>
<Trigger Property="IsEnabled" Value="True">
    <Setter Property="Foreground" Value="Gainsboro"/>
</Trigger>
</code>```

(I changed your "if checked" foreground to Red for obviousness.)

If it's checked, make the foreground Red (or #303030 in your case).

Then if it's not checked, collapse InnerBorder.

Then if it's pressed, set MainBorder's background.

Finally, if it's enabled, set Foreground to Gainsboro.

So whenever it's enabled, it sets the Foreground to Gainsboro.

You're overriding the IsChecked foreground. Simple fix, you've already figured it out:

```<code><Trigger Property="IsChecked" Value="False">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
    <Setter TargetName="MainBorder" Property="Background" Value="#81d2eb" />
</Trigger>
<Trigger Property="IsEnabled" Value="True">
    <Setter Property="Foreground" Value="Gainsboro"/>
</Trigger>
<!--
Move this one so it comes after IsEnabled="True", but before IsEnabled="False"
-->
<Trigger Property="IsChecked" Value="True">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
    <Setter Property="Foreground" Value="Red"/>
</Trigger>
</code>```

You don't need to explicitly apply Foreground to the ContentPresenter, that was the senility kicking in.

ContentLicense: CC BY-SA 3.0

Body:
Please see this Checkbox style:

So i try to add very simple style for Foreground Color when my Checkbox is checked:

<Trigger Property="IsChecked" Value="True">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
    <Setter Property="Foreground" Value="#303030"/>
</Trigger>

And for some reason this is not working and Foreground color not changing.
Any suggestion why ?

Update

This is my Checkbox:

<CheckBox
    FontSize="14"
    Height="25"
    FontFamily="Ariel"/>

As you can see i am not set here Foreground property.

Body:
Here's the order of some of your triggers:

<Trigger Property="IsChecked" Value="True">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
    <Setter Property="Foreground" Value="Red"/>
</Trigger>
<Trigger Property="IsChecked" Value="False">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
    <Setter TargetName="MainBorder" Property="Background" Value="#81d2eb" />
</Trigger>
<Trigger Property="IsEnabled" Value="True">
    <Setter Property="Foreground" Value="Gainsboro"/>
</Trigger>

(I changed your "if checked" foreground to Red for obviousness.)

If it's checked, make the foreground Red (or #303030 in your case).

Then if it's not checked, collapse InnerBorder.

Then if it's pressed, set MainBorder's background.

Finally, if it's enabled, set Foreground to Gainsboro.

So whenever it's enabled, it sets the Foreground to Gainsboro.

You're overriding the IsChecked foreground. Simple fix, you've already figured it out:

<Trigger Property="IsChecked" Value="False">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
    <Setter TargetName="MainBorder" Property="Background" Value="#81d2eb" />
</Trigger>
<Trigger Property="IsEnabled" Value="True">
    <Setter Property="Foreground" Value="Gainsboro"/>
</Trigger>
<!--
Move this one so it comes after IsEnabled="True", but before IsEnabled="False"
-->
<Trigger Property="IsChecked" Value="True">
    <Setter TargetName="InnerBorder" Property="Visibility" Value="Collapsed" />
    <Setter Property="Foreground" Value="Red"/>
</Trigger>

You don't need to explicitly apply Foreground to the ContentPresenter, that was the senility kicking in.


问:
Loop through entire file python
I've put together this piece of code:

```<code>flux =[31.,29,27.,25.]
F=[]
with open("results.rdx", "r") as file1:
for line in enumerate(file1):
    f_list = [float(i) for line in file1 for i in line.split(',') if
    i.strip()]
    F = f_list[7:11]
    with open("results.txt", "a+") as file2:
            file2.write(str(chisqfunc(flux,F)))
            file2.write("\n")
</code>```

And my input file looks like this:

```<code>5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
5.0, 1000.0, 500000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
4.873E-09, 8.890E-09, 8.243E-10, 9.974E-12, 4.157, 3.704, 3.582, 3.649
5.0, 1000.0, 1000000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
8.883E-09, 1.705E-08, 1.668E-09, 2.039E-11, 4.212, 3.731, 3.577, 3.648
</code>```

Actually there are way more lines, but it's pointless to post it all. The function does some array multiplication etc. What I was hoping the code would do is: Read the first line, append the values of the columns 7-10 to the array F[], call chisqfunc and print its result into the file results.txt. Afterwards proceed to the second line, append the new values to F etc.
But all it does is start from line 2 and do the above described procedure for line 2 and only print the value for line 2.
I suspect the problem is in the way I declared for.
Any help is greatly appreciated.

答:
The issue is the way you've declared your loop, indeed. In particular, you're using the enumerate function, which returns a (index, line) tuple. You don't capture the index separately, so you don't get the output you're looking for.

```<code>for line in file1:
    F = list(map(float, map(str.strip, line.strip().split(','))))[7:11]
    ...
</code>```

Here's a much better way to do this, especially if you're working with a large file of numbers: Use numpy.

```<code>In [84]: x = np.loadtxt('data.in', delimiter=',')

In [88]: F = x[:, 7:11]

In [89]: F
Out[89]:
array([[  1.05300000e-09,   1.83900000e-09,   1.63200000e-10,
          1.95900000e-12],
       [  4.87300000e-09,   8.89000000e-09,   8.24300000e-10,
          9.97400000e-12],
       [  8.88300000e-09,   1.70500000e-08,   1.66800000e-09,
          2.03900000e-11]])
</code>```

Here I've assumed that in the data you posted, you've manually added extra newlines which I removed to make this work. F contains the required data for all your rows.

Title: Loop through entire file python

Body:
I've put together this piece of code:

flux =[31.,29,27.,25.]
F=[]
with open("results.rdx", "r") as file1:
for line in enumerate(file1):
    f_list = [float(i) for line in file1 for i in line.split(',') if
    i.strip()]
    F = f_list[7:11]
    with open("results.txt", "a+") as file2:
            file2.write(str(chisqfunc(flux,F)))
            file2.write("\n")

And my input file looks like this:

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
5.0, 1000.0, 500000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
4.873E-09, 8.890E-09, 8.243E-10, 9.974E-12, 4.157, 3.704, 3.582, 3.649
5.0, 1000.0, 1000000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
8.883E-09, 1.705E-08, 1.668E-09, 2.039E-11, 4.212, 3.731, 3.577, 3.648

Actually there are way more lines, but it's pointless to post it all. The function does some array multiplication etc. What I was hoping the code would do is: Read the first line, append the values of the columns 7-10 to the array F[], call chisqfunc and print its result into the file results.txt. Afterwards proceed to the second line, append the new values to F etc.
But all it does is start from line 2 and do the above described procedure for line 2 and only print the value for line 2.
I suspect the problem is in the way I declared for.
Any help is greatly appreciated.

Body:
The issue is the way you've declared your loop, indeed. In particular, you're using the enumerate function, which returns a (index, line) tuple. You don't capture the index separately, so you don't get the output you're looking for.

for line in file1:
    F = list(map(float, map(str.strip, line.strip().split(','))))[7:11]
    ...

Here's a much better way to do this, especially if you're working with a large file of numbers: Use numpy.

In [84]: x = np.loadtxt('data.in', delimiter=',')

In [88]: F = x[:, 7:11]

In [89]: F
Out[89]:
array([[  1.05300000e-09,   1.83900000e-09,   1.63200000e-10,
          1.95900000e-12],
       [  4.87300000e-09,   8.89000000e-09,   8.24300000e-10,
          9.97400000e-12],
       [  8.88300000e-09,   1.70500000e-08,   1.66800000e-09,
          2.03900000e-11]])

Here I've assumed that in the data you posted, you've manually added extra newlines which I removed to make this work. F contains the required data for all your rows.


问:
What does `this` point at in the following js arrow functions in mocha tests?
What does this point here?

```<code>const expect = require('chai').expect;
const sinon = require('sinon');

describe('test', () => {
  describe('test()', () => {
    afterEach(function _test() {
      this.xxx = undefined; // What does `this` point here?
    });
  });

  describe('test2()', () => {
    afterEach(function _test2() {
      this.yyy = undefined; // What does `this` point here?
    });
  });
});
</code>```

By the way, it is good to use this in the above codes if both this(s) point at the same object?

UPDATE

Code

```<code>describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(() => {
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});
</code>```

output:

```<code>1 {}
4 {}

  test
2 {}
    going deeper
3 {}
6 {}
      ✓ has increased someVal to 3

  1 passing (4ms)
</code>```

code (changed one arrow function to normal function):

```<code>describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(function() { // HERE
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});
</code>```

output:

```<code>1 {}
4 {}

  test
2 {}
    going deeper
3 {}
      1) "before each" hook for "has increased someVal to 3"

  0 passing (6ms)
  1 failing

  1) test going deeper "before each" hook for "has increased someVal to 3":
     TypeError: Converting circular structure to JSON
      at Object.stringify (native)
      at formatValue (util.js:352:36)
      at inspect (util.js:186:10)
      at exports.format (util.js:72:24)
      at Console.log (console.js:43:37)
      at Context.<anonymous> (test3.js:32:15)
</code>```

答:
This is a good question because it is something that is not addressed in a lot of arrow function tutorials.

Arrow functions have there "this" context bound at definition time, but more importantly your question. The this will inherit recursively.

```<code>describe('test', () => {                 // `this` is the global object
  describe('test()', () => {             // `this` is the global object
    afterEach(function _test() {
      this.xxx = undefined;              // `this` is the global object
    });
  });

  describe('test2()', () => {            // `this` is the global object
    afterEach(function _test2() {
      this.yyy = undefined;              // `this` is the global object
    });
  });
});
</code>```

Here is an example

 const foo = ()=>{
  console.log("foo is window?",this === window);
  const a = (input)=>{console.log("a is window?",this === window); this._=input };
  const b = ()=> {console.log("b is window?",this === window);return this._}
  return { a,b }
 }

 const bar= foo()
 console.log(bar.b()) // undefined
 bar.a(5)
 console.log(bar.b()) // 5
 console.log(window._) // 5```
</div>
</div>
</p>

<p>if you change </p>

```const b = ()=> {console.log("b is window?",this === window);return this._}
```

<p>to</p>

```const b = function() {console.log("b is window?",this === window);return this._}
```

<p>the <code>this</code> now points to the wrapping Object <code>{ a,b }</code></p>

<p>If you use an ES6 to ES5 ⚠ will replace <code>this</code> with <code>undefined</code></p>

```"use strict"; // https://es6console.com/

var foo = function foo() {
    console.log("foo is window?", undefined === window);
    var a = function a(input) {
        console.log("a is window?", undefined === window);undefined._ = input;
    };
    var b = function b() {
        console.log("b is window?", undefined === window);return undefined._;
    };
    return { a: a, b: b };
};
```

Body:
What does this point here?

const expect = require('chai').expect;
const sinon = require('sinon');

describe('test', () => {
  describe('test()', () => {
    afterEach(function _test() {
      this.xxx = undefined; // What does `this` point here?
    });
  });

  describe('test2()', () => {
    afterEach(function _test2() {
      this.yyy = undefined; // What does `this` point here?
    });
  });
});

By the way, it is good to use this in the above codes if both this(s) point at the same object?

UPDATE

Code

describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(() => {
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});

output:

1 {}
4 {}

  test
2 {}
    going deeper
3 {}
6 {}
      ✓ has increased someVal to 3

  1 passing (4ms)

code (changed one arrow function to normal function):

describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(function() { // HERE
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});

output:

1 {}
4 {}

  test
2 {}
    going deeper
3 {}
      1) "before each" hook for "has increased someVal to 3"

  0 passing (6ms)
  1 failing

  1) test going deeper "before each" hook for "has increased someVal to 3":
     TypeError: Converting circular structure to JSON
      at Object.stringify (native)
      at formatValue (util.js:352:36)
      at inspect (util.js:186:10)
      at exports.format (util.js:72:24)
      at Console.log (console.js:43:37)
      at Context.<anonymous> (test3.js:32:15)

Body:
This is a good question because it is something that is not addressed in a lot of arrow function tutorials.

Arrow functions have there "this" context bound at definition time, but more importantly your question. The this will inherit recursively.

describe('test', () => {                 // `this` is the global object
  describe('test()', () => {             // `this` is the global object
    afterEach(function _test() {
      this.xxx = undefined;              // `this` is the global object
    });
  });

  describe('test2()', () => {            // `this` is the global object
    afterEach(function _test2() {
      this.yyy = undefined;              // `this` is the global object
    });
  });
});

Here is an example

 const foo = ()=>{
  console.log("foo is window?",this === window);
  const a = (input)=>{console.log("a is window?",this === window); this._=input };
  const b = ()=> {console.log("b is window?",this === window);return this._}
  return { a,b }
 }

 const bar= foo()
 console.log(bar.b()) // undefined
 bar.a(5)
 console.log(bar.b()) // 5
 console.log(window._) // 5

if you change

const b = ()=> {console.log("b is window?",this === window);return this._}

to

const b = function() {console.log("b is window?",this === window);return this._}

the this now points to the wrapping Object { a,b }

If you use an ES6 to ES5 ⚠ will replace this with undefined

"use strict"; // https://es6console.com/

var foo = function foo() {
    console.log("foo is window?", undefined === window);
    var a = function a(input) {
        console.log("a is window?", undefined === window);undefined._ = input;
    };
    var b = function b() {
        console.log("b is window?", undefined === window);return undefined._;
    };
    return { a: a, b: b };
};


问:
2 rows of images (odd numbers of images)
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="0">

  <tr>

    <td>
      <figure style="margin: 0;">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin:0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

  </tr>

  <tr>

    <td>
      <figure style="margin: 0;">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin:0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin: 0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

  </tr>

</table></code>```

View on JSFiddle

答:
You can drop the table and center tags and use a single div.

Then the flex-layout makes it much easier : see https://css-tricks.com/snippets/css/a-guide-to-flexbox/

/* use the flex model */
div {
  display:flex;
  flex-wrap:wrap;/* allow wrapping on multiple rows*/
  justify-content:center;/* horizontal centering */
}

figure:nth-child(1),
figure:nth-child(2)
{
  order:-1;/* reorder the first 2 image ahead anything else */
}
/* add an element to push to next line the last elements */
div:before {
  content:'';
  width:100%;/* use a full row */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <figure>
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</figure>
<figure>
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</figure>
<figure>
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</figure>
<figure>
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</figure>
<figure>
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</figure>
</div></code>```

demo to play with

Body:
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}

View on JSFiddle

Body:
You can drop the table and center tags and use a single div.

Then the flex-layout makes it much easier : see https://css-tricks.com/snippets/css/a-guide-to-flexbox/

/* use the flex model */
div {
  display:flex;
  flex-wrap:wrap;/* allow wrapping on multiple rows*/
  justify-content:center;/* horizontal centering */
}

figure:nth-child(1),
figure:nth-child(2)
{
  order:-1;/* reorder the first 2 image ahead anything else */
}
/* add an element to push to next line the last elements */
div:before {
  content:'';
  width:100%;/* use a full row */
}

<div>
  <figure>
  <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
</figure>
<figure>
  <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
</figure>
<figure>
  <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
</figure>
<figure>
  <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
</figure>
<figure>
  <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
</figure>
</div>

demo to play with


问:
How to git reset --hard a subdirectory

UPDATE²: With Git 2.23 (August 2019), there's a new command git restore that does this, see the accepted answer.

UPDATE: This will work more intuitively as of Git 1.8.3, see my own answer.

Imagine the following use case: I want to get rid of all changes in a specific subdirectory of my Git working tree, leaving all other subdirectories intact.

I can do git checkout . , but git checkout . adds directories excluded by sparse checkout

There is git reset --hard, but it won't let me do it for a subdirectory:

```<code>> git reset --hard .
fatal: Cannot do hard reset with paths.
</code>```

Again: Why git can't do hard/soft resets by path?

I can reverse-patch the current state using git diff subdir | patch -p1 -R, but this is a rather weird way of doing this.

What is the proper Git command for this operation?

The script below illustrates the problem. Insert the proper command below the How to make files comment -- the current command will restore the file a/c/ac which is supposed to be excluded by the sparse checkout. Note that I do not want to explicitly restore a/a and a/b, I only "know" a and want to restore everything below. EDIT: And I also don't "know" b, or which other directories reside on the same level as a.

#!/bin/sh

rm -rf repo; git init repo; cd repo
for f in a b; do
  for g in a b c; do
    mkdir -p $f/$g
    touch $f/$g/$f$g
    git add $f/$g
    git commit -m "added $f/$g"
  done
done
git config core.sparsecheckout true
echo a/a > .git/info/sparse-checkout
echo a/b >> .git/info/sparse-checkout
echo b/a >> .git/info/sparse-checkout
git read-tree -m -u HEAD
echo "After read-tree:"
find * -type f

rm a/a/aa
rm a/b/ab
echo >> b/a/ba
echo "After modifying:"
find * -type f
git status

# How to make files a/* reappear without changing b and without recreating a/c?
git checkout -- a

echo "After checkout:"
git status
find * -type f
```

答:
If the size of the subdirectory is not particularly huge, and you wish to stay away from the CLI, here's a quick solution to manually reset the subdirectory:

Switch to the master branch and copy the subdirectory to be reset.

Now switch back to your feature branch and replace the subdirectory with the copy you just created in step 1.

Commit the changes.

Cheers. You just manually reset a subdirectory in your feature branch to be same as that of the master branch!

ContentLicense: CC BY-SA 4.0

Title: How to git reset --hard a subdirectory

Body:
UPDATE²: With Git 2.23 (August 2019), there's a new command git restore that does this, see the accepted answer.

UPDATE: This will work more intuitively as of Git 1.8.3, see my own answer.

Imagine the following use case: I want to get rid of all changes in a specific subdirectory of my Git working tree, leaving all other subdirectories intact.

I can do git checkout . , but git checkout . adds directories excluded by sparse checkout

There is git reset --hard, but it won't let me do it for a subdirectory:

> git reset --hard .
fatal: Cannot do hard reset with paths.

Again: Why git can't do hard/soft resets by path?

I can reverse-patch the current state using git diff subdir | patch -p1 -R, but this is a rather weird way of doing this.

What is the proper Git command for this operation?

The script below illustrates the problem. Insert the proper command below the How to make files comment -- the current command will restore the file a/c/ac which is supposed to be excluded by the sparse checkout. Note that I do not want to explicitly restore a/a and a/b, I only "know" a and want to restore everything below. EDIT: And I also don't "know" b, or which other directories reside on the same level as a.

#!/bin/sh

rm -rf repo; git init repo; cd repo
for f in a b; do
  for g in a b c; do
    mkdir -p $f/$g
    touch $f/$g/$f$g
    git add $f/$g
    git commit -m "added $f/$g"
  done
done
git config core.sparsecheckout true
echo a/a > .git/info/sparse-checkout
echo a/b >> .git/info/sparse-checkout
echo b/a >> .git/info/sparse-checkout
git read-tree -m -u HEAD
echo "After read-tree:"
find * -type f

rm a/a/aa
rm a/b/ab
echo >> b/a/ba
echo "After modifying:"
find * -type f
git status

# How to make files a/* reappear without changing b and without recreating a/c?
git checkout -- a

echo "After checkout:"
git status
find * -type f


问:
Why does jQuery mask say it's not a function?
When trying to use the jQuery mask() function, I get the following error in the console:

```<code>TypeError: $(...).mask is not a function
</code>```

This is a sample of my code where this is happening:

```<code><html>
<body>
<input type='text' id='phone' />
</body>

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>

<script>
//alert($);
$(document).ready(function(){

        $("#phone").mask("(99) 9999-9999");
});
</script>

</html>
</code>```

How do I fix this?

答:
Change this line from

$(document).ready(function(){

to

$(document).ready(function($){

Body:
When trying to use the jQuery mask() function, I get the following error in the console:

TypeError: $(...).mask is not a function

This is a sample of my code where this is happening:

<input type='text' id='phone' />

How do I fix this?


问:
unable to connect to default instance using it's full name
I am developing an app that needs to get from a user a server name or address and a db name and build a folder structure based on that. The problem is that in order to have the same folder for all the different ways there are to get the path to the instance (localhost, ip address, etc.) i'm running the following Query:

```<code>select cast(SERVERPROPERTY('MachineName')as varchar)+'\'+@@servicename
</code>```

on the target server and set my folder structure based on that, and in that format saves the connection that the user gave (doesn't matter if i got ip or a server name, there is one connection string for all).

My problem is that when the instance is the default instance on the target machine, I cant seem to connect using MACHINE_NAME\MSSQLSERVER. I can only log in using the machine without instance name. So I need to either find a way to connect to the instance using its full name (preferred) or to find a way figure out if the targeted instance is the default one.

Any help would be very appreciated.

答:
'MSSQLSERVER' is reserved for default instance, so you can</p>

```<code>SELECT CAST(SERVERPROPERTY('MachineName')AS VARCHAR)+ CASE WHEN CHARINDEX('MSSQLSERVER', @@SERVICENAME, 1) >0 THEN '' ELSE '\'+@@SERVICENAME END
</code>```

Body:
I am developing an app that needs to get from a user a server name or address and a db name and build a folder structure based on that. The problem is that in order to have the same folder for all the different ways there are to get the path to the instance (localhost, ip address, etc.) i'm running the following Query:

select cast(SERVERPROPERTY('MachineName')as varchar)+'\'+@@servicename

on the target server and set my folder structure based on that, and in that format saves the connection that the user gave (doesn't matter if i got ip or a server name, there is one connection string for all).

My problem is that when the instance is the default instance on the target machine, I cant seem to connect using MACHINE_NAME\MSSQLSERVER. I can only log in using the machine without instance name. So I need to either find a way to connect to the instance using its full name (preferred) or to find a way figure out if the targeted instance is the default one.

Any help would be very appreciated.

Body:
'MSSQLSERVER' is reserved for default instance, so you can

SELECT CAST(SERVERPROPERTY('MachineName')AS VARCHAR)+ CASE WHEN CHARINDEX('MSSQLSERVER', @@SERVICENAME, 1) >0 THEN '' ELSE '\'+@@SERVICENAME END


问:
ASP.net do not cache page with a specific querystring
I know that i can use the VaryByParam attribute, but what it does is not exactly what i am aiming for.

What happens is that different versions of the page are cached based on the query string.

For example Page.aspx?ID=Tom has its own cached version and ID=Arnold has another. Now what i want to do is not to cache Arnold at all. I only want to cache the page when the query string is Tom.

Any ideas?

答:
For C#

```<code>    public static void cacheOutput(Page page, double minutes)
    {
        page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(minutes));
        page.Response.Cache.SetCacheability(HttpCacheability.Server);
        page.Response.Cache.SetValidUntilExpires(true);
    }
</code>```

It's better to take a double for minutes.
Good solution!
Thx!

ContentLicense: CC BY-SA 2.5

Body:
For C#

    public static void cacheOutput(Page page, double minutes)
    {
        page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(minutes));
        page.Response.Cache.SetCacheability(HttpCacheability.Server);
        page.Response.Cache.SetValidUntilExpires(true);
    }

It's better to take a double for minutes.
Good solution!
Thx!


问:
Send Mouse Coordinates Over Tcp Issues
I am working on program in which I want to move cursor of remote pc from my pc but here is a little problem receiving mouse coordinates on remote pc the data receive by tcp server on remote machine due to delay not pushing immediately on some places here is the code and output coordinates which i saved in a file for both client send and server receive.

Client Code to Send Coordinates.

```<code>private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();
            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes($"{pX}#{pY}");
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\client.txt", $"{pX}#{pY}" + Environment.NewLine);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch (Exception ex)
        {
        }
    }
}
</code>```

Server Code to Receive Coordinates

```<code>while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    try
    {
        // Translate data bytes to a ASCII string.
        // Receive mouse coordinates here
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

        string Coordinates = data.ToString();
        string X = Coordinates.Substring(0, Coordinates.IndexOf('#'));
        string Y = Coordinates.Substring(Coordinates.IndexOf('#') + 1);
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));

        // Change coordinates
        System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
        Cursor.Clip = new Rectangle(this.Location, this.Size);
        System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

    }
    catch (Exception E)
    {
        //  MessageBox.Show(E.ToString());
    }
}
</code>```

Send Coordinates from client

653#492
659#490
669#489
677#486
684#483
693#476
699#470
709#460
715#453
720#444
724#437

Receive Coordinates on Server
653 and 492
659 and 490
669 and 489
677 and 486
684 and 483
693 and 476
699 and 470
709 and 460715#453720#444
724 and 437

Here problem is with709 and 460715#453720#444 because old coordinates were not pushed forward and appending with new which is not suitable for mouse position Please help.

答:
you problem is that you are treating TCP like a block protocol. It is not, TCP is a streaming protocol. The only guarantee is that you send some bytes and that they will be received in the same order. You could send one chunk of 100 bytes and receive 50 2 bytes chunks, or 1 100 byte, or 100 1 byte message. You need to be able to read the stream and know how much data you need and to block until you have read it all.

I would use c# binary writer / reader. That prepends length information and the receive will wait till it has everything.

Title: Send Mouse Coordinates Over Tcp Issues

Body:
I am working on program in which I want to move cursor of remote pc from my pc but here is a little problem receiving mouse coordinates on remote pc the data receive by tcp server on remote machine due to delay not pushing immediately on some places here is the code and output coordinates which i saved in a file for both client send and server receive.

Client Code to Send Coordinates.

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();
            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes($"{pX}#{pY}");
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\client.txt", $"{pX}#{pY}" + Environment.NewLine);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch (Exception ex)
        {
        }
    }
}

Server Code to Receive Coordinates

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    try
    {
        // Translate data bytes to a ASCII string.
        // Receive mouse coordinates here
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

        string Coordinates = data.ToString();
        string X = Coordinates.Substring(0, Coordinates.IndexOf('#'));
        string Y = Coordinates.Substring(Coordinates.IndexOf('#') + 1);
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));

        // Change coordinates
        System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
        Cursor.Clip = new Rectangle(this.Location, this.Size);
        System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

    }
    catch (Exception E)
    {
        //  MessageBox.Show(E.ToString());
    }
}

Send Coordinates from client

653#492
659#490
669#489
677#486
684#483
693#476
699#470
709#460
715#453
720#444
724#437

Receive Coordinates on Server
653 and 492
659 and 490
669 and 489
677 and 486
684 and 483
693 and 476
699 and 470
709 and 460715#453720#444
724 and 437

Here problem is with709 and 460715#453720#444 because old coordinates were not pushed forward and appending with new which is not suitable for mouse position Please help.


问:
pg-promise doesn't delete but doesn't throw error either
I have the following query which successfully delete records when I run it in the psql shell:

```<code>delete from schedule_set USING schedule, event WHERE (schedule.schedule_set_id = schedule_set.id) and (schedule_set.id = ${id}) and (select count(*) from event where (complete IS TRUE)) = 0 RETURNING *
</code>```

I'm generating the query with a JS function - that's why I have ${id} in the query, than call the following:

```<code>    return db.any(schedule.deleteSchedulesByScheduleSetId(params), params)
        .catch(err => {
            console.log(err);
        });
</code>```

When I have a syntax error in the query I get an error - this tells me that the query is being ran against the database. When I fix the syntax I don't get any errors but nothing is deleted either.

Any ideas why or how to debug? - thanks

答:
Method any, as documented, only rejects when executing the query results in an error. If your DELETE query doesn't delete anything, it is not an error.

If you want your DELETE query to result in an error when it doesn't delete anything, you can use RETURNING * in the end of the query, and execute it either with many or one, depending on how many records it is expected to delete (and thus return) normally.

The most practical approach however is not to use any of the above, because returning deleted rows is an extra operation, typically useless. Instead, you should rely on the number of rows actually deleted, and then act accordingly.

For that you would you use method result, converting the output into the number of rows affected (deleted in your case):

```<code>db.result(query, values, a => a.rowCount)
    .then(count => {
        // count = number of rows deleted
    })
    .catch(error => {
        // error
    })
</code>```

Body:
I have the following query which successfully delete records when I run it in the psql shell:

delete from schedule_set USING schedule, event WHERE (schedule.schedule_set_id = schedule_set.id) and (schedule_set.id = ${id}) and (select count(*) from event where (complete IS TRUE)) = 0 RETURNING *

I'm generating the query with a JS function - that's why I have ${id} in the query, than call the following:

    return db.any(schedule.deleteSchedulesByScheduleSetId(params), params)
        .catch(err => {
            console.log(err);
        });

When I have a syntax error in the query I get an error - this tells me that the query is being ran against the database. When I fix the syntax I don't get any errors but nothing is deleted either.

Any ideas why or how to debug? - thanks

Body:
Method any, as documented, only rejects when executing the query results in an error. If your DELETE query doesn't delete anything, it is not an error.

If you want your DELETE query to result in an error when it doesn't delete anything, you can use RETURNING * in the end of the query, and execute it either with many or one, depending on how many records it is expected to delete (and thus return) normally.

The most practical approach however is not to use any of the above, because returning deleted rows is an extra operation, typically useless. Instead, you should rely on the number of rows actually deleted, and then act accordingly.

For that you would you use method result, converting the output into the number of rows affected (deleted in your case):

db.result(query, values, a => a.rowCount)
    .then(count => {
        // count = number of rows deleted
    })
    .catch(error => {
        // error
    })


问:
Fastest way to find index of elements in a list
I have a set of samples (say X) with some features (say Y) on which I need to run some machine learning algorithms (say PCA). One way is to generate the matrix (sample, feature). My approach to constructing the matrix involves 2 steps:

Get all the feature values for the entire dataset. Let's call it a pool.

For a sample, for each value in the sample, find the value's index in the pool. The index's where the value is present is 1 and absent is 0.

Ex: Consider the below example

```<code>sample1 = A, B, D
sample2 = A, C, E
sample3 = A, C, D
</code>```

Generated pool = A, B, C, D, E

Generated matrix

sample 1 => 1, 1, 0, 1, 0

sample 2 => 1, 0, 1, 0, 1

sample 3 => 1, 0, 0, 1, 0

The challenge in generating this matrix is that, the data is very huge. The number of rows are 465337 and the number of columns are 35526155.

Generating the pool took around 20 minutes and even though this is slow, I am fine with it. But when generating the vector (i.e. row) of the matrix, I have to get for all the values of the sample under consideration the index of that value in the pool.

This is taking a huge time. Is there a better approach to find the index of elements? If the procedure itself is not optimal, please let me know of a better way to generate the matrix.

Also, I am just storing the indices and constructing a CSR matrix out of it instead of a dense matrix.

答:
As I mentioned in the comments, you want to be using a sklearn.feature_extraction.text.CountVectorizer for this, with the binary=True argument, since you don't actually want counts. You this creates your encoding and outputs a sparse-matrix to boot!

However, if you are interested in the underlying problem with your approach, fundamentally the issue is that you are using a sequence type, a list, where the .index method is a linear-time operation. You are feeling the pain of this fact when you try to use your list. Here is a sketch of how you could do this way more efficiently, using only a dictionary:

```<code>In [15]: tokens = list('qwertydfgndjfkgnf')

In [16]: pool = {}

In [17]: for t in tokens:
    ...:     pool.setdefault(t, len(pool))
    ...:

In [18]: pool
Out[18]:
{'d': 6,
 'e': 2,
 'f': 7,
 'g': 8,
 'j': 10,
 'k': 11,
 'n': 9,
 'q': 0,
 'r': 3,
 't': 4,
 'w': 1,
 'y': 5}

In [19]: tokens.index('g') # ew, O(n) time complexity
Out[19]: 8

In [20]: pool['g'] # nice! O(1) time complexity
Out[20]: 8
</code>```

This pool now contains an encoding from tokens to index. And accessing the index is a constant time operation here. This will significantly improve performance. And indeed, since we are just making a dict to begin with, and not converting from a set to a list, this will cut down on your constant factors by a lot.

Note, the above is essentially what the sklearn object is doing.

https://github.com/scikit-learn/scikit-learn/blob/ab93d65/sklearn/feature_extraction/text.py#L745

Note, however, they use a defaultdict, which is optimized for this sort of thing, with the following delightful little approach:

```<code>In [24]: from collections import defaultdict

In [25]: pool = defaultdict()

In [26]: pool.default_factory = pool.__len__

In [27]: for t in tokens:
    ...:     pool[t]
    ...:

In [28]: pool
Out[28]:
defaultdict(<method-wrapper '__len__' of collections.defaultdict object at 0x1088aa9f8>,
            {'d': 6,
             'e': 2,
             'f': 7,
             'g': 8,
             'j': 10,
             'k': 11,
             'n': 9,
             'q': 0,
             'r': 3,
             't': 4,
             'w': 1,
             'y': 5})
</code>```

The also build the sparse representation as they loop over the documents, so they actually only do one pass over the data set. So the sklearn object is about as optimized as you are going to get. The sklearn source code is actually pretty approachable, and it is worth checking out what they accomplish using just pure python without Cython extensions or anything.

Body:
I have a set of samples (say X) with some features (say Y) on which I need to run some machine learning algorithms (say PCA). One way is to generate the matrix (sample, feature). My approach to constructing the matrix involves 2 steps:

Get all the feature values for the entire dataset. Let's call it a pool.

For a sample, for each value in the sample, find the value's index in the pool. The index's where the value is present is 1 and absent is 0.

Ex: Consider the below example

sample1 = A, B, D
sample2 = A, C, E
sample3 = A, C, D

Generated pool = A, B, C, D, E

Generated matrix

sample 1 => 1, 1, 0, 1, 0

sample 2 => 1, 0, 1, 0, 1

sample 3 => 1, 0, 0, 1, 0

The challenge in generating this matrix is that, the data is very huge. The number of rows are 465337 and the number of columns are 35526155.

Generating the pool took around 20 minutes and even though this is slow, I am fine with it. But when generating the vector (i.e. row) of the matrix, I have to get for all the values of the sample under consideration the index of that value in the pool.

This is taking a huge time. Is there a better approach to find the index of elements? If the procedure itself is not optimal, please let me know of a better way to generate the matrix.

Also, I am just storing the indices and constructing a CSR matrix out of it instead of a dense matrix.

Body:
As I mentioned in the comments, you want to be using a sklearn.feature_extraction.text.CountVectorizer for this, with the binary=True argument, since you don't actually want counts. You this creates your encoding and outputs a sparse-matrix to boot!

However, if you are interested in the underlying problem with your approach, fundamentally the issue is that you are using a sequence type, a list, where the .index method is a linear-time operation. You are feeling the pain of this fact when you try to use your list. Here is a sketch of how you could do this way more efficiently, using only a dictionary:

In [15]: tokens = list('qwertydfgndjfkgnf')

In [16]: pool = {}

In [17]: for t in tokens:
    ...:     pool.setdefault(t, len(pool))
    ...:

In [18]: pool
Out[18]:
{'d': 6,
 'e': 2,
 'f': 7,
 'g': 8,
 'j': 10,
 'k': 11,
 'n': 9,
 'q': 0,
 'r': 3,
 't': 4,
 'w': 1,
 'y': 5}

In [19]: tokens.index('g') # ew, O(n) time complexity
Out[19]: 8

In [20]: pool['g'] # nice! O(1) time complexity
Out[20]: 8

This pool now contains an encoding from tokens to index. And accessing the index is a constant time operation here. This will significantly improve performance. And indeed, since we are just making a dict to begin with, and not converting from a set to a list, this will cut down on your constant factors by a lot.

Note, the above is essentially what the sklearn object is doing.

https://github.com/scikit-learn/scikit-learn/blob/ab93d65/sklearn/feature_extraction/text.py#L745

Note, however, they use a defaultdict, which is optimized for this sort of thing, with the following delightful little approach:

In [24]: from collections import defaultdict

In [25]: pool = defaultdict()

In [26]: pool.default_factory = pool.__len__

In [27]: for t in tokens:
    ...:     pool[t]
    ...:

In [28]: pool
Out[28]:
defaultdict(<method-wrapper '__len__' of collections.defaultdict object at 0x1088aa9f8>,
            {'d': 6,
             'e': 2,
             'f': 7,
             'g': 8,
             'j': 10,
             'k': 11,
             'n': 9,
             'q': 0,
             'r': 3,
             't': 4,
             'w': 1,
             'y': 5})

The also build the sparse representation as they loop over the documents, so they actually only do one pass over the data set. So the sklearn object is about as optimized as you are going to get. The sklearn source code is actually pretty approachable, and it is worth checking out what they accomplish using just pure python without Cython extensions or anything.