问:
AES Encrypt and Decrypt between C# and PHP MCrypt
I seem to be having problems getting an AES256 string to decode between a PHP and .NET application. I get an error in the .Net application stating "Padding is invalid and cannot be removed." This error fires in the using statement for the CrytoStream. The workflow is pretty straight forward. The PHP application encrypts a value and passes it to the .NET application as a URL parameter. The .NET application needs to decrypt that value for later use. The .NET method works from .NET to .NET, but PHP to .NET is the problem.

The PHP code:

```<code>   function encrypt($text) {
    $key = "M2AZULUALPHA";
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($text) % $block);
    $text .= str_repeat(chr($padding), $padding);

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, 'TripBuilder2017');
    return base64_encode($crypttext);
 }
</code>```

The .NET Decrypt method:

```<code>    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "M2AZULUALPHA";
        byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017");

        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, saltArray);
            encryptor.KeySize = 256;
            encryptor.Padding = PaddingMode.PKCS7;
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
</code>```

UPDATE
I changed the mode in PHP to Rijndael256 and I also changed AES to RijndaelManaged in .NET. Again, I am able to get this working between .NET applications, but not with the PHP application. I am wondering if there is an issue with the padding the PHP application is using.

答:
I updated answer completely after messages :-)

php:

```<code>function encrypt($text)
    {

    //$key = "M2AZULUALPHA"; //  type 2 -- mcrypt_encrypt(): Key of size 12 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported -- at line 7
    $key = "M2AZULUALPHA1234";
    //$vi ='TripBuilder2017'; // type 2 -- mcrypt_encrypt(): Received initialization vector of size 15, but size 16 is required for this encryption mode -- at line 9
    $vi ='TripBuilder20170';
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($text) % $block);
    $text .= str_repeat(chr($padding), $padding);
    $crypttext = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $vi));
    return $crypttext;
    }

    $result = encrypt("abcdcddsfdafdfe");
    echo"$result";
</code>```

output is "pPPH8amRhqbdX6D83jr74A=="

c# with RijndaelManaged

```<code>public String Decrypt(string cipherText)
        {
            var result = "";
            var cypher = Convert.FromBase64String(cipherText);
            var encoding = System.Text.Encoding.UTF8;
            var Key = encoding.GetBytes("M2AZULUALPHA1234");
            var IV = encoding.GetBytes("TripBuilder20170");
            using (var rj = new RijndaelManaged())
            {
                rj.Padding = PaddingMode.PKCS7;
                rj.Mode = CipherMode.CBC;
                rj.KeySize = 256;
                rj.Key = Key;
                rj.IV = IV;
                var ms = new MemoryStream(cypher);
                using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                using (var sr = new StreamReader(cs))
                    result = sr.ReadToEnd();
            }

            return result;
        }
</code>```

test:

```<code>var result = Decrypt("pPPH8amRhqbdX6D83jr74A==");
Debug.WriteLine(result);
</code>```

output is "abcdcddsfdafdfe"

Body:
I seem to be having problems getting an AES256 string to decode between a PHP and .NET application. I get an error in the .Net application stating "Padding is invalid and cannot be removed." This error fires in the using statement for the CrytoStream. The workflow is pretty straight forward. The PHP application encrypts a value and passes it to the .NET application as a URL parameter. The .NET application needs to decrypt that value for later use. The .NET method works from .NET to .NET, but PHP to .NET is the problem.

The PHP code:

   function encrypt($text) {
    $key = "M2AZULUALPHA";
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($text) % $block);
    $text .= str_repeat(chr($padding), $padding);

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, 'TripBuilder2017');
    return base64_encode($crypttext);
 }

The .NET Decrypt method:

    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "M2AZULUALPHA";
        byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017");

        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, saltArray);
            encryptor.KeySize = 256;
            encryptor.Padding = PaddingMode.PKCS7;
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }

UPDATE
I changed the mode in PHP to Rijndael256 and I also changed AES to RijndaelManaged in .NET. Again, I am able to get this working between .NET applications, but not with the PHP application. I am wondering if there is an issue with the padding the PHP application is using.

Body:
I updated answer completely after messages :-)

php:

function encrypt($text)
    {

    //$key = "M2AZULUALPHA"; //  type 2 -- mcrypt_encrypt(): Key of size 12 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported -- at line 7
    $key = "M2AZULUALPHA1234";
    //$vi ='TripBuilder2017'; // type 2 -- mcrypt_encrypt(): Received initialization vector of size 15, but size 16 is required for this encryption mode -- at line 9
    $vi ='TripBuilder20170';
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($text) % $block);
    $text .= str_repeat(chr($padding), $padding);
    $crypttext = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $vi));
    return $crypttext;
    }

    $result = encrypt("abcdcddsfdafdfe");
    echo"$result";

output is "pPPH8amRhqbdX6D83jr74A=="

c# with RijndaelManaged

public String Decrypt(string cipherText)
        {
            var result = "";
            var cypher = Convert.FromBase64String(cipherText);
            var encoding = System.Text.Encoding.UTF8;
            var Key = encoding.GetBytes("M2AZULUALPHA1234");
            var IV = encoding.GetBytes("TripBuilder20170");
            using (var rj = new RijndaelManaged())
            {
                rj.Padding = PaddingMode.PKCS7;
                rj.Mode = CipherMode.CBC;
                rj.KeySize = 256;
                rj.Key = Key;
                rj.IV = IV;
                var ms = new MemoryStream(cypher);
                using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                using (var sr = new StreamReader(cs))
                    result = sr.ReadToEnd();
            }

            return result;
        }

test:

var result = Decrypt("pPPH8amRhqbdX6D83jr74A==");
Debug.WriteLine(result);

output is "abcdcddsfdafdfe"


来源: stackexchange

问:
Python generate all possible strings of length n
I am learning ethical hacking. I have the hash key of a password and the crypt algorithm (sha256/sha512). I want to parse all the strings from a file and to check if the hash of the password matches the hash of each of the string from the file.

The generated String may contain small letters, big letters and numbers.

Any ideas how to generate all the possible Strings of length n which may contain letters and numbers?

答:
Here's a piece of code that uses [Python 3.Docs]: itertools.product(*iterables, repeat=1).

Note that the number of generated strings is 62 ** length, so for testing purposes use small values for length:

import string
import itertools

def generate_strings(length=3):
    chars = string.ascii_letters + string.digits  # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    for item in itertools.product(chars, repeat=length):
        yield "".join(item)
```

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Retrieving a nested object inside a JSON string using rapidjson
I need to retrieve a nested object inside a JSON string and I'm trying to do it using rapidjson. All I've found is how to retrieve arrays and basic types, but not sub-objects. I have created the following toy example which gives an error:

```<code>rapidjson::Document document;
std::string test =  " { \"a\": { \"z\" : 21 } } ";
std::cout << test << std::endl;
if ( document.Parse<0>( test.c_str() ).HasParseError() ) {
    std::cout << "Parsing error" << std::endl;
} else {
    if ( document[ "a" ].IsObject() ) {
        std::cout << "OK" << std::endl;
        std::cout << document[ "a" ].GetString() << std::endl;
    }
}
</code>```

This is the output when executed:

```<code>{ "a": { "z" : 21 } }
OK
JSONTest: ../rapidjson/document.h:441: const typename Encoding::Ch* rapidjson::GenericValue<Encoding, Allocator>::GetString() const [with Encoding = rapidjson::UTF8<char>, Allocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>]: Assertion `IsString()' failed. Aborted
</code>```

How do I retrieve the inner object to continue my parsing? Thanks.

Edit: What I need is to obtain the string representation of the inner object so I can call another function that is going to parse it.

Edit 2: code that allows to retrieve the inner object as a string:

```<code>rapidjson::Document document;
std::string test =  "{\"a\":{\"z\":21}} ";
if ( document.Parse<0>( test.c_str() ).HasParseError() ) {
    std::cout << "Error parsing" << std::endl;
} else {
    if ( document[ "a" ].IsObject() ) {
        rapidjson::StringBuffer sb;
        rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
        document[ "a" ].Accept( writer );
        std::cout << sb.GetString() << std::endl;
    }
}
</code>```

答:
This is something I recently worked on:

```<code>void enter(const Value &obj, size_t indent = 0) { //print JSON tree

if (obj.IsObject()) { //check if object
    for (Value::ConstMemberIterator itr = obj.MemberBegin(); itr != obj.MemberEnd(); ++itr) {   //iterate through object
        const Value& objName = obj[itr->name.GetString()]; //make object value

        for (size_t i = 0; i != indent; ++i) //indent
            cout << " ";

        cout << itr->name.GetString() << ": "; //key name

        if (itr->value.IsNumber()) //if integer
            std::cout << itr->value.GetInt() ;

        else if (itr->value.IsString()) //if string
            std::cout << itr->value.GetString();

        else if (itr->value.IsBool()) //if bool
            std::cout << itr->value.GetBool();

        else if (itr->value.IsArray()){ //if array

            for (SizeType i = 0; i < itr->value.Size(); i++) {
                if (itr->value[i].IsNumber()) //if array value integer
                    std::cout << itr->value[i].GetInt() ;

                else if (itr->value[i].IsString()) //if array value string
                    std::cout << itr->value[i].GetString() ;

                else if (itr->value[i].IsBool()) //if array value bool
                    std::cout << itr->value[i].GetBool() ;

                else if (itr->value[i].IsObject()){ //if array value object
                    cout << "\n  ";
                    const Value& m = itr->value[i];
                    for (auto& v : m.GetObject()) { //iterate through array object
                        if (m[v.name.GetString()].IsString()) //if array object value is string
                            cout << v.name.GetString() << ": " <<   m[v.name.GetString()].GetString();
                        else //if array object value is integer
                            cout << v.name.GetString() << ": "  <<  m[v.name.GetString()].GetInt();

                       cout <<  "\t"; //indent
                    }
                }
                cout <<  "\t"; //indent
            }
        }

        cout << endl;
        enter(objName, indent + 1); //if couldn't find in object, enter object and repeat process recursively
    }
}
}
</code>```

This can handle any type of JSON tree. All you have to do is pass a Value as such:

```<code>Value v = document.GetObject();
Value& m= v;
enter(m);
</code>```

And you're done!

Body:
I need to retrieve a nested object inside a JSON string and I'm trying to do it using rapidjson. All I've found is how to retrieve arrays and basic types, but not sub-objects. I have created the following toy example which gives an error:

rapidjson::Document document;
std::string test =  " { \"a\": { \"z\" : 21 } } ";
std::cout << test << std::endl;
if ( document.Parse<0>( test.c_str() ).HasParseError() ) {
    std::cout << "Parsing error" << std::endl;
} else {
    if ( document[ "a" ].IsObject() ) {
        std::cout << "OK" << std::endl;
        std::cout << document[ "a" ].GetString() << std::endl;
    }
}

This is the output when executed:

{ "a": { "z" : 21 } }
OK
JSONTest: ../rapidjson/document.h:441: const typename Encoding::Ch* rapidjson::GenericValue<Encoding, Allocator>::GetString() const [with Encoding = rapidjson::UTF8<char>, Allocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>]: Assertion `IsString()' failed. Aborted

How do I retrieve the inner object to continue my parsing? Thanks.

Edit: What I need is to obtain the string representation of the inner object so I can call another function that is going to parse it.

Edit 2: code that allows to retrieve the inner object as a string:

rapidjson::Document document;
std::string test =  "{\"a\":{\"z\":21}} ";
if ( document.Parse<0>( test.c_str() ).HasParseError() ) {
    std::cout << "Error parsing" << std::endl;
} else {
    if ( document[ "a" ].IsObject() ) {
        rapidjson::StringBuffer sb;
        rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
        document[ "a" ].Accept( writer );
        std::cout << sb.GetString() << std::endl;
    }
}

Body:
This is something I recently worked on:

void enter(const Value &obj, size_t indent = 0) { //print JSON tree

if (obj.IsObject()) { //check if object
    for (Value::ConstMemberIterator itr = obj.MemberBegin(); itr != obj.MemberEnd(); ++itr) {   //iterate through object
        const Value& objName = obj[itr->name.GetString()]; //make object value

        for (size_t i = 0; i != indent; ++i) //indent
            cout << " ";

        cout << itr->name.GetString() << ": "; //key name

        if (itr->value.IsNumber()) //if integer
            std::cout << itr->value.GetInt() ;

        else if (itr->value.IsString()) //if string
            std::cout << itr->value.GetString();

        else if (itr->value.IsBool()) //if bool
            std::cout << itr->value.GetBool();

        else if (itr->value.IsArray()){ //if array

            for (SizeType i = 0; i < itr->value.Size(); i++) {
                if (itr->value[i].IsNumber()) //if array value integer
                    std::cout << itr->value[i].GetInt() ;

                else if (itr->value[i].IsString()) //if array value string
                    std::cout << itr->value[i].GetString() ;

                else if (itr->value[i].IsBool()) //if array value bool
                    std::cout << itr->value[i].GetBool() ;

                else if (itr->value[i].IsObject()){ //if array value object
                    cout << "\n  ";
                    const Value& m = itr->value[i];
                    for (auto& v : m.GetObject()) { //iterate through array object
                        if (m[v.name.GetString()].IsString()) //if array object value is string
                            cout << v.name.GetString() << ": " <<   m[v.name.GetString()].GetString();
                        else //if array object value is integer
                            cout << v.name.GetString() << ": "  <<  m[v.name.GetString()].GetInt();

                       cout <<  "\t"; //indent
                    }
                }
                cout <<  "\t"; //indent
            }
        }

        cout << endl;
        enter(objName, indent + 1); //if couldn't find in object, enter object and repeat process recursively
    }
}
}

This can handle any type of JSON tree. All you have to do is pass a Value as such:

Value v = document.GetObject();
Value& m= v;
enter(m);

And you're done!


问:
sbt 0.13 on Windows - Cannot Access Repositories
I've gone through almost everything related to installing sbt on Window on stackoverflow (there are quite a few people having the same problem with me). However, the answer seems unclear/unreproducible on my machine.

Here is what I did:

Download sbt-0.13.13 on this site

Install it successfully and set the PATH

Try sbt version to see if it is installed successfully. Error
returned (as at the end of this post)

A few things we should know:

I already have JDK

I don't use Proxy on my computer (tested with netsh winhttp show
proxy)

Someone said it is because sbt doesn't support ASCII character - but
the solution wasn't clear

```<code>    problems summary
WARNINGS
    module not found: org.fusesource.jansi#jansi;1.11

local: tried

  C:\Users\buidu\.ivy2\local\org.fusesource.jansi\jansi\1.11\ivys\ivy.xml

  -- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

  C:\Users\buidu\.ivy2\local\org.fusesource.jansi\jansi\1.11\jars\jansi.jar

==== Maven Central: tried

  https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

  -- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

  https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

==== typesafe-ivy-releases: tried

  https://repo.typesafe.com/typesafe/ivy-releases/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

==== sbt-ivy-snapshots: tried

  https://repo.scala-sbt.org/scalasbt/ivy-snapshots/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

 UNRESOLVED DEPENDENCIES

 org.fusesource.jansi#jansi;1.11: not found

Server access Error: Permission denied: connect url=https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

Server access Error: Permission denied: connect url=https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

Server access Error: Permission denied: connect url=https://repo.typesafe.com/typesafe/ivy-releases/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

Server access Error: Permission denied: connect url=https://repo.scala-sbt.org/scalasbt/ivy-snapshots/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml
</code>```

答: I was struggling with the same for a week. The only thing, that helped, was to uninstall sbt from the default location (c:\Program Files(x86)\sbt) and reinstall it to some location without spaces (I've installed it to d:\sbt).</p>

Body:
I've gone through almost everything related to installing sbt on Window on stackoverflow (there are quite a few people having the same problem with me). However, the answer seems unclear/unreproducible on my machine.

Here is what I did:

Download sbt-0.13.13 on this site

Install it successfully and set the PATH

Try sbt version to see if it is installed successfully. Error
returned (as at the end of this post)

A few things we should know:

I already have JDK

I don't use Proxy on my computer (tested with netsh winhttp show
proxy)

Someone said it is because sbt doesn't support ASCII character - but
the solution wasn't clear

    problems summary
WARNINGS
    module not found: org.fusesource.jansi#jansi;1.11

local: tried

  C:\Users\buidu\.ivy2\local\org.fusesource.jansi\jansi\1.11\ivys\ivy.xml

  -- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

  C:\Users\buidu\.ivy2\local\org.fusesource.jansi\jansi\1.11\jars\jansi.jar

==== Maven Central: tried

  https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

  -- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

  https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

==== typesafe-ivy-releases: tried

  https://repo.typesafe.com/typesafe/ivy-releases/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

==== sbt-ivy-snapshots: tried

  https://repo.scala-sbt.org/scalasbt/ivy-snapshots/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

 UNRESOLVED DEPENDENCIES

 org.fusesource.jansi#jansi;1.11: not found

Server access Error: Permission denied: connect url=https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

Server access Error: Permission denied: connect url=https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

Server access Error: Permission denied: connect url=https://repo.typesafe.com/typesafe/ivy-releases/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

Server access Error: Permission denied: connect url=https://repo.scala-sbt.org/scalasbt/ivy-snapshots/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml


问:
How to leave a copy of the original file when we save the file
When modifying and saving a file, how to leave a copy of the original file, say give it *.bak?Is there a built-in support?</p>

答:
Here is a short example:</p>

```<code>// This is the current file
string filePath = @"C:\temp\test.txt";

//Now change file extension to text.bak
string filePathBak = Path.ChangeExtension(filePath, "bak");

// Save orginal file
File.Move(filePath, filePathBak);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is a short example:

// This is the current file
string filePath = @"C:\temp\test.txt";

//Now change file extension to text.bak
string filePathBak = Path.ChangeExtension(filePath, "bak");

// Save orginal file
File.Move(filePath, filePathBak);


问:
Firebase Cloud Messaging in Xamarin.Android - Push notification status bar icon not being set correctly
I have a Xamarin.Android application which is registered for push notifications with Firebase. Everything works perfectly when the app is in the foreground. However, when the app is in the background and I send it a notification from the Firebase console, the icon that I've set as the default for notifications is not being used, and Android is using a greyscale version of the application's launcher instead:

And the same goes for the notification in the tray:

This shouldn't be happening, since I have the following line in my AndroidManifest:

```<code><meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" />
</code>```

And I have monochrome icons in my drawable folders which follow the guidelines detailed by the Android documentation.

I understand the the Firebase console only sends messages without the Data payload, which is why OnMessageReceived in my FirebaseMessagingService is not called when the app is in the background. What I don't understand is why Android is using my launcher icon instead of the one specified in the manifest for notification-payload-only FCM messages.

I am using version 32.961.0 of Xamarin.Firebase.Messaging, since version 42.1001.0 (the latest stable version) has dependencies which break my app in other ways. Is this likely to be an issue with my version of the package, or is there something else I may be doing wrong?

答: Updating to Xamarin.Firebase.Messaging version 42.1001.0 fixes the issue; it appears to have been a limitation in Firebase Messaging SDK < 9.8.0 (32.961.0 maps to version 9.6.1).

Body:
I have a Xamarin.Android application which is registered for push notifications with Firebase. Everything works perfectly when the app is in the foreground. However, when the app is in the background and I send it a notification from the Firebase console, the icon that I've set as the default for notifications is not being used, and Android is using a greyscale version of the application's launcher instead:

And the same goes for the notification in the tray:

This shouldn't be happening, since I have the following line in my AndroidManifest:

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" />

And I have monochrome icons in my drawable folders which follow the guidelines detailed by the Android documentation.

I understand the the Firebase console only sends messages without the Data payload, which is why OnMessageReceived in my FirebaseMessagingService is not called when the app is in the background. What I don't understand is why Android is using my launcher icon instead of the one specified in the manifest for notification-payload-only FCM messages.

I am using version 32.961.0 of Xamarin.Firebase.Messaging, since version 42.1001.0 (the latest stable version) has dependencies which break my app in other ways. Is this likely to be an issue with my version of the package, or is there something else I may be doing wrong?


问:
How to change input file button size?
I am working with styling input file with opacity method - real input file button has opacity 0 and in front of it, using z-index is another input (with opacity: 1). Unfortunatelly I want my visible button to be squared picture (width:height: 1:1) - and unvisible input file is always rectangular (input box and select box with aspect ratio about 1:10). Question is - how to resize input file button to be squared (or any size) to make whole visible button area clickable (because only clicking invisible button causes opening browser window). Now only part of on visible button is "clickable".

CSS:

```<code>   <style type="text/css">
   .upload {
        position:relative;
    width:100px;
   }

   .realupload {
    position:absolute;
    top:0;
    right:0;
    opacity:0.5;
    -moz-opacity:0.5;
    filter:alpha(opacity:0.5);
    z-index:2;
    width:100px;
   }

   form .fakeupload {
    background: url(images/bglines.png);
   }

   form .fakeupload input {
    width:0px;
   }

   </style>
</code>```

And html:

```<code><form>
   <li class="upload">
    <div class="fakeupload">
        <input type="text" name="fakeupload" style="opacity: 0;"/>
    </div>
    <input type="file" name="upload" id="realupload" class="realupload" onchange="this.form.fakeupload.value = this.value;" style="font-size: 5px;" />
   </li>
   </form>
</code>```

答:
To shorten input type file button clickable area you can try to use this:

```<code>form .fakeupload input {
    width:20px;
    transform: scale(0.23,1);
}
</code>```

This will narrow the clickable area of input type file. (You can use transform: scale(x,y) - with x and y is number that will fits your need.
Remember to add proper styling for mobile devices or different browsers.

Title: How to change input file button size?

Body:
I am working with styling input file with opacity method - real input file button has opacity 0 and in front of it, using z-index is another input (with opacity: 1). Unfortunatelly I want my visible button to be squared picture (width:height: 1:1) - and unvisible input file is always rectangular (input box and select box with aspect ratio about 1:10). Question is - how to resize input file button to be squared (or any size) to make whole visible button area clickable (because only clicking invisible button causes opening browser window). Now only part of on visible button is "clickable".

CSS:

And html:

<form>

        <input type="text" name="fakeupload" style="opacity: 0;"/>

    <input type="file" name="upload" id="realupload" class="realupload" onchange="this.form.fakeupload.value = this.value;" style="font-size: 5px;" />

   </form>

Body:
To shorten input type file button clickable area you can try to use this:

form .fakeupload input {
    width:20px;
    transform: scale(0.23,1);
}

This will narrow the clickable area of input type file. (You can use transform: scale(x,y) - with x and y is number that will fits your need.
Remember to add proper styling for mobile devices or different browsers.


问:
Access denied for user 'root'@'localhost' (using password: YES) IN WAMPSERVER
I am using Wampserver. I am currently programming in jsp,but it gives me an error:
Access denied for user 'root'@'localhost' (using password: YES)

My Code is :

```<code>    <%@ page import ="java.sql.*" %>
    <%
    try{
    String user = request.getParameter("uname");
    String pwd = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/quiz",
        "root", " ");
Statement st = con.createStatement();
//ResultSet rs;
int i = st.executeUpdate("insert into members(first_name, last_name, email, uname, pass, regdate) values ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "', CURDATE())");
if (i > 0) {
    //session.setAttribute("userid", user);
    response.sendRedirect("welcome.jsp");
   // out.print("Registration Successfull!"+"<a href='index.jsp'>Go to       Login</a>");
} else {
    response.sendRedirect("index.jsp");
}
}
 catch(Exception e)
 {
  out.print(e.getMessage());
 }
 %>
</code>```

答:
you should put the correct password and not (" ") or create new user in wampServer

like this :

'

```<code>CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

FLUSH PRIVILEGES;
</code>```

'

and your code will be :

```<code>    <%@ page import ="java.sql.*" %>
    <%
    try{
    String user = request.getParameter("uname");
    String pwd = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/quiz",
        "user", "password");
Statement st = con.createStatement();
//ResultSet rs;
int i = st.executeUpdate("insert into members(first_name, last_name, email, uname, pass, regdate) values ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "', CURDATE())");
if (i > 0) {
    //session.setAttribute("userid", user);
    response.sendRedirect("welcome.jsp");
   // out.print("Registration Successfull!"+"<a href='index.jsp'>Go to       Login</a>");
} else {
    response.sendRedirect("index.jsp");
}
}
 catch(Exception e)
 {
  out.print(e.getMessage());
 }
 %>
</code>```

Body:
I am using Wampserver. I am currently programming in jsp,but it gives me an error:
Access denied for user 'root'@'localhost' (using password: YES)

My Code is :

    <%@ page import ="java.sql.*" %>
    <%
    try{
    String user = request.getParameter("uname");
    String pwd = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/quiz",
        "root", " ");
Statement st = con.createStatement();
//ResultSet rs;
int i = st.executeUpdate("insert into members(first_name, last_name, email, uname, pass, regdate) values ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "', CURDATE())");
if (i > 0) {
    //session.setAttribute("userid", user);
    response.sendRedirect("welcome.jsp");
   // out.print("Registration Successfull!"+"Go to       Login");
} else {
    response.sendRedirect("index.jsp");
}
}
 catch(Exception e)
 {
  out.print(e.getMessage());
 }
 %>

Body:
you should put the correct password and not (" ") or create new user in wampServer

like this :

'

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

FLUSH PRIVILEGES;

'

and your code will be :

    <%@ page import ="java.sql.*" %>
    <%
    try{
    String user = request.getParameter("uname");
    String pwd = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/quiz",
        "user", "password");
Statement st = con.createStatement();
//ResultSet rs;
int i = st.executeUpdate("insert into members(first_name, last_name, email, uname, pass, regdate) values ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "', CURDATE())");
if (i > 0) {
    //session.setAttribute("userid", user);
    response.sendRedirect("welcome.jsp");
   // out.print("Registration Successfull!"+"<a href='index.jsp'>Go to       Login</a>");
} else {
    response.sendRedirect("index.jsp");
}
}
 catch(Exception e)
 {
  out.print(e.getMessage());
 }
 %>


问:
Android Studio app crashes on real device, but works on emulator
I started using Android Studio a few weeks ago. I've worked on an app with a normal login screen and on the emulator everything works fine. But if I try to run the app on my Samsung Galaxy S7 Edge (Android 7.0) the app crashes instantly.

I've emulated an Nexus 5 with API 23, when I try it with an emulated Pixel with API 24 the emulator also crashes. So I guess the problem depends on the Android version?

Logcat (I tinified all images I am using, now this is my new Logcat):

```<code>03-30 15:53:13.841 31645-31645/de.mm.uchron E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: de.mm.uchron, PID: 31645
                                                                      java.lang.OutOfMemoryError: Failed to allocate a 3686412 byte allocation with 2474312 free bytes and 2MB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:700)
                                                                          at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:535)
                                                                          at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1179)
                                                                          at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:770)
                                                                          at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:621)
                                                                          at android.content.res.Resources.loadDrawable(Resources.java:1727)
                                                                          at android.content.res.TypedArray.getDrawable(TypedArray.java:945)
                                                                          at android.widget.ImageView.<init>(ImageView.java:157)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:85)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:81)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:60)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:56)
                                                                          at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                                          at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
                                                                          at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at de.mm.uchron.LoginActivity.onCreate(LoginActivity.java:32)
                                                                          at android.app.Activity.performCreate(Activity.java:6912)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                                                                          at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6688)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
03-30 15:53:20.016 31645-31656/de.mm.uchron I/art: Clamp target GC heap from 261MB to 256MB
</code>```

I've also tried it with my another real device (Samsung GT-I9300 with Android 5.1.1, API 22). The MainActivity loads, but without the background image and if I try to login, the app crashes.

My SDK Tools have all the newest version

```<code>Android Emulator: 26.0.0
Android SDK Platform-Tools: 25.0.4
Android SDK Tools: 26.0.0
Google Play services, rev 39: 39.0.0
Google USB Driver, rev 11: 11.0.0
Google Web driver: 2
Intel x86 Emulator Accelerator (HAXM installer): 6.0.5
</code>```

xml file for the MainActivity (LoginActivity):

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:background="@drawable/loginbg">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/rect"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

    </LinearLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:layout_marginLeft="30dp">

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="222dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:textColor="#000"
        android:fontFamily="Montserrat"
        android:textSize="16dp"
        android:hint="BENUTZERNAME" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_below="@id/signup_input_layout_name">

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="223dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:fontFamily="Montserrat"
            android:hint="PASSWORT"
            android:inputType="textPassword"
            android:textColor="#000"
            android:textSize="16dp" />
    </android.support.design.widget.TextInputLayout>

    <ImageButton
        android:id="@+id/bSignIn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="@null"
        android:layout_marginBottom="60dp"
        android:layout_marginLeft="260dp"
        android:fontFamily="Montserrat"
        android:scaleType="fitXY"
        android:src="@drawable/loginbutton"
        android:text="Login" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="NEUER ACCOUNT"
        android:id="@+id/tvRegisterLink"
        android:textSize="12sp"
        android:textColor="#B2B2B2"
        android:fontFamily="Montserrat"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_alignStart="@+id/signup_input_layout_pass" />

</RelativeLayout>
</code>```

Like I said I am new to Android Studio and I become exasperated with this problem.

Thanks in advance!

Solved: Resizing the images solved the problem. I used the suggestions from this link to reduce the resolution of my background files. Now everything works like a charm!

答:
You mention that you're using an image with dimensions 1500 x 2668 in this comment. As shown in the logcat, Android is using BitmapFactory to inflate this image, and Bitmaps take up memory based on image dimensions. In your case this is a lot of memory, more than the device has available for your app, thus the OutOfMemoryException.

Scale the dimensions of @drawable/loginbg down as far as you can without compromising quality. I'd recommend reading about how to support multiple screen sizes using images of different dimensions: https://developer.android.com/guide/practices/screens_support.html

Body:
I started using Android Studio a few weeks ago. I've worked on an app with a normal login screen and on the emulator everything works fine. But if I try to run the app on my Samsung Galaxy S7 Edge (Android 7.0) the app crashes instantly.

I've emulated an Nexus 5 with API 23, when I try it with an emulated Pixel with API 24 the emulator also crashes. So I guess the problem depends on the Android version?

Logcat (I tinified all images I am using, now this is my new Logcat):

03-30 15:53:13.841 31645-31645/de.mm.uchron E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: de.mm.uchron, PID: 31645
                                                                      java.lang.OutOfMemoryError: Failed to allocate a 3686412 byte allocation with 2474312 free bytes and 2MB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:700)
                                                                          at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:535)
                                                                          at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1179)
                                                                          at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:770)
                                                                          at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:621)
                                                                          at android.content.res.Resources.loadDrawable(Resources.java:1727)
                                                                          at android.content.res.TypedArray.getDrawable(TypedArray.java:945)
                                                                          at android.widget.ImageView.<init>(ImageView.java:157)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:85)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:81)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:60)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:56)
                                                                          at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                                          at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
                                                                          at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at de.mm.uchron.LoginActivity.onCreate(LoginActivity.java:32)
                                                                          at android.app.Activity.performCreate(Activity.java:6912)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                                                                          at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6688)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
03-30 15:53:20.016 31645-31656/de.mm.uchron I/art: Clamp target GC heap from 261MB to 256MB

I've also tried it with my another real device (Samsung GT-I9300 with Android 5.1.1, API 22). The MainActivity loads, but without the background image and if I try to login, the app crashes.

My SDK Tools have all the newest version

Android Emulator: 26.0.0
Android SDK Platform-Tools: 25.0.4
Android SDK Tools: 26.0.0
Google Play services, rev 39: 39.0.0
Google USB Driver, rev 11: 11.0.0
Google Web driver: 2
Intel x86 Emulator Accelerator (HAXM installer): 6.0.5

xml file for the MainActivity (LoginActivity):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:background="@drawable/loginbg">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/rect"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

    </LinearLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:layout_marginLeft="30dp">

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="222dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:textColor="#000"
        android:fontFamily="Montserrat"
        android:textSize="16dp"
        android:hint="BENUTZERNAME" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_below="@id/signup_input_layout_name">

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="223dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:fontFamily="Montserrat"
            android:hint="PASSWORT"
            android:inputType="textPassword"
            android:textColor="#000"
            android:textSize="16dp" />
    </android.support.design.widget.TextInputLayout>

    <ImageButton
        android:id="@+id/bSignIn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="@null"
        android:layout_marginBottom="60dp"
        android:layout_marginLeft="260dp"
        android:fontFamily="Montserrat"
        android:scaleType="fitXY"
        android:src="@drawable/loginbutton"
        android:text="Login" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="NEUER ACCOUNT"
        android:id="@+id/tvRegisterLink"
        android:textSize="12sp"
        android:textColor="#B2B2B2"
        android:fontFamily="Montserrat"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_alignStart="@+id/signup_input_layout_pass" />

</RelativeLayout>

Like I said I am new to Android Studio and I become exasperated with this problem.

Thanks in advance!

Solved: Resizing the images solved the problem. I used the suggestions from this link to reduce the resolution of my background files. Now everything works like a charm!


问:
SaveAs password protected document without password - Excel VBA
I am opening a password protected Word document using the below macro in Excel, then I want to save a copy of the document without the password protection. Currently, I am still prompted for the original password when I try and open the newly saved document.

```<code>Dim DPObj
Dim DPApp As Object
Dim YourOwnPassword As String
Dim DocPath As String
DocSrcPath = "C:\Users\ADMIN\Desktop\Sources\SourceDoc.doc"
DocTgtPath = "C:\Users\ADMIN\Desktop\Targets\TargetDoc.doc"
YourOwnPassword = "TestPWD"
Set DPApp = CreateObject("word.Application")
'Open Password enabled document
DPDoc = DPApp.Documents.Open(DocSrcPath, PasswordDocument:=YourOwnPassword)
'Make some changes to the document.
'Save the edited document without a password
DPApp.ActiveDocument.SaveAs2 DocTgtPath
</code>```

Does anybody know how to make it so that the TargetDoc.doc is not still password protected?

答:
Using a blank password should work:</p>

```<code>DPApp.ActiveDocument.SaveAs2 DocTgtPath, Password:=""
</code>```

Body:
I am opening a password protected Word document using the below macro in Excel, then I want to save a copy of the document without the password protection. Currently, I am still prompted for the original password when I try and open the newly saved document.

Dim DPObj
Dim DPApp As Object
Dim YourOwnPassword As String
Dim DocPath As String
DocSrcPath = "C:\Users\ADMIN\Desktop\Sources\SourceDoc.doc"
DocTgtPath = "C:\Users\ADMIN\Desktop\Targets\TargetDoc.doc"
YourOwnPassword = "TestPWD"
Set DPApp = CreateObject("word.Application")
'Open Password enabled document
DPDoc = DPApp.Documents.Open(DocSrcPath, PasswordDocument:=YourOwnPassword)
'Make some changes to the document.
'Save the edited document without a password
DPApp.ActiveDocument.SaveAs2 DocTgtPath

Does anybody know how to make it so that the TargetDoc.doc is not still password protected?

Body:
Using a blank password should work:

DPApp.ActiveDocument.SaveAs2 DocTgtPath, Password:=""


问:
Auto Increment Custom data type in SQL Server 2008
I'm using a program which I don't have access to its code, but I do have access to its database in SQLServer 2008.

I'm developing another program to interact with that database but, trying to insert a row with a null id so that it appeared auto-incremented, it threw an Error at the 2nd attempt due to the default value ((0)).

I've found several tables whose Primary Key is a User Defined Data Type called "Autonumeric".

The definition of the data type is:

CREATE TYPE [dbo].[AutoNumerico] FROM [int] NOT NULL
Custom field

This field autoincrements when inserting with the Original program, but it doesn´t have the Identity property.

The creation of the Primary Key is:

CREATE TABLE [dbo].[tbTableName](
    [IDEstrComp] [dbo].[AutoNumerico] NOT NULL,
    ...
 CONSTRAINT [PK_tbTableName] PRIMARY KEY CLUSTERED
(
    [IDEstrComp] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] Primary key

Does this mean that the key is generated in the program?

Is there any reason to increment in the program instead of using an auto-increment field in the database?

答:
I've found a stored procedure that inserts into an auxiliar table, deletes the inserted row and returns the @@IDENTITY generated</p>

```<code>ALTER PROCEDURE [dbo].[spValorAutonumerico]
(
    @Value INT output
)
AS

BEGIN

    INSERT INTO  xAutoNumeric
    (Valor)
    VALUES
    (0)

    SET @Valor = @@IDENTITY

    DELETE FROM xAutoNumeric
    WHERE ID = @Valor
END
</code>```

Body:
I've found a stored procedure that inserts into an auxiliar table, deletes the inserted row and returns the @@IDENTITY generated

ALTER PROCEDURE [dbo].[spValorAutonumerico]
(
    @Value INT output
)
AS

BEGIN

    INSERT INTO  xAutoNumeric
    (Valor)
    VALUES
    (0)

    SET @Valor = @@IDENTITY

    DELETE FROM xAutoNumeric
    WHERE ID = @Valor
END


问:
How to get Time Zone through IP Address in PHP
I want to get time zone through an IP Address in PHP. Actually, I have an application which will run at the client machine. I have the IP address of the client machine. But I am not able to get the time zone for each client machine.</p>

答:
```<code>$ip = "189.240.194.147";  //$_SERVER['REMOTE_ADDR']
$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);
$ipInfo = json_decode($ipInfo);
$timezone = $ipInfo->timezone;
date_default_timezone_set($timezone);
echo date_default_timezone_get();
echo date('Y/m/d H:i:s');
</code>```

Sometime it won't work on local server so try on server.

Edit: This data is coming from ip-api.com, they're free to use as long as you don't exceed 45 requests per minute and not using commercially. See their TOS, not a long a page.

Body:
$ip = "189.240.194.147";  //$_SERVER['REMOTE_ADDR']
$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);
$ipInfo = json_decode($ipInfo);
$timezone = $ipInfo->timezone;
date_default_timezone_set($timezone);
echo date_default_timezone_get();
echo date('Y/m/d H:i:s');

Sometime it won't work on local server so try on server.

Edit: This data is coming from ip-api.com, they're free to use as long as you don't exceed 45 requests per minute and not using commercially. See their TOS, not a long a page.


问:
When computing with the Ornstein Uhlenbeck Model for millisecond data, what should dt equal?
The ornstein uhlenbeck is the following SDE:

dx_{t}=\theta (\mu -x_{t})\,dt+\sigma \,dW_{t}

generally dt is in years, but is this necessary?

答:
Since with OU the Green's function is known you can use whatever time step is convenient and update exactly:</p>

```<code>ou(t + dt) = ou(t) + (mu - ou(t)) * (1 - np.exp(-theta*dt)) \
    + scipy.stats.norm(loc=0, scale=sigma*np.sqrt(1/(2*theta)*(1 - np.exp(-2*theta*dt)))).rvs()
</code>```

Body:
Since with OU the Green's function is known you can use whatever time step is convenient and update exactly:

ou(t + dt) = ou(t) + (mu - ou(t)) * (1 - np.exp(-theta*dt)) \
    + scipy.stats.norm(loc=0, scale=sigma*np.sqrt(1/(2*theta)*(1 - np.exp(-2*theta*dt)))).rvs()


问:
OPC UA java library
I am new to OPC UA standard and being a java developer was trying to search for a good java library for the standard.

I cam across https://github.com/OPCFoundation/UA-Java and Eclipse Milo(or digitalpetri).

How does Eclipse Milo compare with UA-Java? which one should I choose?

My use case is to develop a NIFI(nifi.apache.org) custom processor that can read data from an OPC UA server like Kepware and channel that data into our bigdata store and later build analytics on top of it.  I want to implement OPC features like subscription and historical data access as well in the processor.

答:
I may be a little biased as I'm the primary author of Eclipse Milo, but you should use it because it's both a stack and SDK implementation of OPC UA where the code provided by the foundation is only a stack.

If you don't have extensive knowledge of OPC UA and time to write a lot of code that SDKs have typically already written then you don't want just a stack.

Title: OPC UA java library


问:
Catch if user presses enter key in textbox
I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.

This is my Event code for the Textbox:

```<code>Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub
</code>```

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?

I tried changing the Textbox property to AcceptsReturn = True but no luck.

Extra info: The textbox is located on a UserControl and not a form control.

答:
If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead.

It might work, but it all depends on where in the event chain that the parent intercepts the message.

```<code>Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then
        'Do your stuff here.
        Return True 'We've handled the key press.
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function
</code>```

Body:
I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.

This is my Event code for the Textbox:

Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?

I tried changing the Textbox property to AcceptsReturn = True but no luck.

Extra info: The textbox is located on a UserControl and not a form control.

Body:
If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead.

It might work, but it all depends on where in the event chain that the parent intercepts the message.

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then
        'Do your stuff here.
        Return True 'We've handled the key press.
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function


问:
Why isn't the size of an empty list 0 bytes?
Today itself I ran the code given below in Python 2.7.13 and found that the list size isn't 0 when it is empty:

```<code>import sys
data = []
for k in range(n):
    a = len(data)
    b = sys.getsizeof(data)
    print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
    data.append(None)
</code>```

Output on my Machine:

```<code>Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes : 136
Length: 8; Size in bytes : 136
Length: 9; Size in bytes : 200
Length: 10; Size in bytes : 200
Length: 11; Size in bytes : 200
Length: 12; Size in bytes : 200
Length: 13; Size in bytes : 200
Length: 14; Size in bytes : 200
Length: 15; Size in bytes : 200
Length: 16; Size in bytes : 200
Length: 17; Size in bytes : 272
Length: 18; Size in bytes : 272
Length: 19; Size in bytes : 272
</code>```

I want to know why is this happening?

It seems that Python is reserving memory for something.
  What is that something??

答:
Because the size of the list, as returned from sys.getsizeof, doesn't include only the elements that list contains.

Every object in Python is represented by a C-struct; this struct contains pointers to all the things that make the list a list (its methods, mainly). It's also taken into consideration when sys.getsizeof is invoked.

You can always take a look at the implementation of list.__sizeof__ in the master branch of the CPython repository on GitHub:

```<code>static PyObject *
list___sizeof___impl(PyListObject *self)
{
    Py_ssize_t res;

    res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
    return PyLong_FromSsize_t(res);
}
</code>```

(Trimmed off unrelated arg clinic output.)

The sizeof function for 2.x does the same thing.

The return value res also includes the size of the list object type _PyObject_SIZE(Py_Type(self)).

Since everything in Python is an object, this behavior can be observed everywhere, e.x, integer 0:

```<code>>>> getsizeof(0)
24
</code>```

while you wouldn't normally expect this, it makes perfect sense when you realize everything in Python has "additional baggage" which allows behavior we take for granted.

Body:
Today itself I ran the code given below in Python 2.7.13 and found that the list size isn't 0 when it is empty:

import sys
data = []
for k in range(n):
    a = len(data)
    b = sys.getsizeof(data)
    print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
    data.append(None)

Output on my Machine:

Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes : 136
Length: 8; Size in bytes : 136
Length: 9; Size in bytes : 200
Length: 10; Size in bytes : 200
Length: 11; Size in bytes : 200
Length: 12; Size in bytes : 200
Length: 13; Size in bytes : 200
Length: 14; Size in bytes : 200
Length: 15; Size in bytes : 200
Length: 16; Size in bytes : 200
Length: 17; Size in bytes : 272
Length: 18; Size in bytes : 272
Length: 19; Size in bytes : 272

I want to know why is this happening?

It seems that Python is reserving memory for something.
  What is that something??

Body:
Because the size of the list, as returned from sys.getsizeof, doesn't include only the elements that list contains.

Every object in Python is represented by a C-struct; this struct contains pointers to all the things that make the list a list (its methods, mainly). It's also taken into consideration when sys.getsizeof is invoked.

You can always take a look at the implementation of list.__sizeof__ in the master branch of the CPython repository on GitHub:

static PyObject *
list___sizeof___impl(PyListObject *self)
{
    Py_ssize_t res;

    res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
    return PyLong_FromSsize_t(res);
}

(Trimmed off unrelated arg clinic output.)

The sizeof function for 2.x does the same thing.

The return value res also includes the size of the list object type _PyObject_SIZE(Py_Type(self)).

Since everything in Python is an object, this behavior can be observed everywhere, e.x, integer 0:

>>> getsizeof(0)
24

while you wouldn't normally expect this, it makes perfect sense when you realize everything in Python has "additional baggage" which allows behavior we take for granted.


问:
How can I copy a file and update SQL database as a single transaction?
My application needs to monitor a folder to incoming files and when it notices a new file has arrived, I need to copy it to another location and insert a record into a SQL database.

The problem is that these two actions are independent and do not succeed or fail together as a transaction.

Are there any options to solve this?

One option is to update SQL first and then copy the file and then update SQL and if it fails delete the file, but that delete operation can also fail causing both actions to become out of sync.

There is a system called Transactional NTFS but Microsoft recommends against using it.

答:
I do not think you need a transaction. You can monitor a folder for incoming files with a FileSystemWatcher. Once the file has been copied, perform the database operation.

FileSystemWatcher Example

```<code>FileSystemWatcher watcher;

private void Watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;

  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
   CopyFile(e.FullPath);
}

private void CopyFile(string fileNameAndPath)
{
   // copy file
   // make sure file exists at new  location
   // perform database operation
}
</code>```

Body:
I do not think you need a transaction. You can monitor a folder for incoming files with a FileSystemWatcher. Once the file has been copied, perform the database operation.

FileSystemWatcher Example

FileSystemWatcher watcher;

private void Watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;

  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
   CopyFile(e.FullPath);
}

private void CopyFile(string fileNameAndPath)
{
   // copy file
   // make sure file exists at new  location
   // perform database operation
}


问:
Java Jade : not displaying in console
I begun learning Jade platform, I created a first simple agent but it doesn't display anything in the console.

```<code>package firstJade;

import jade.core.Agent;

public class firstAgent extends Agent {

    @Override
    protected void setup(){
        System.out.println("hello Jade !");
        System.out.println("my agent name is " + getLocalName());
        doDelete();
    }
}
</code>```

After running the Jade remote window does open but the messages in my code doesn't appear

INFOS: --------------------------------------

Agent container Main-Container@192.168.1.81 is ready.

答:
Add this in your java class with main method and run it to start your agent.

```<code>String[] args1 = {"-gui","ClusteringAgent:multi.agent_clustering.ClusteringAgent"};

            jade.Boot.main(args1);
</code>```

That is

```<code>String[] args1 = {"-gui","Agent Name:package.Agent-class-name"};

 jade.Boot.main(args1);
</code>```

You can even add agent in containers by making following changes:

```<code>String[] args1 = {"-container","ClusteringAgent:multi.agent_clustering.ClusteringAgent"};

            jade.Boot.main(args1);
</code>```

By replacing -gui with  -container.
But make sure you have added your first agent with jade GUI before adding subsequent agents in new containers.

Title: Java Jade : not displaying in console

Body:
I begun learning Jade platform, I created a first simple agent but it doesn't display anything in the console.

package firstJade;

import jade.core.Agent;

public class firstAgent extends Agent {

    @Override
    protected void setup(){
        System.out.println("hello Jade !");
        System.out.println("my agent name is " + getLocalName());
        doDelete();
    }
}

After running the Jade remote window does open but the messages in my code doesn't appear

INFOS: --------------------------------------

Agent container Main-Container@192.168.1.81 is ready.

Body:
Add this in your java class with main method and run it to start your agent.

String[] args1 = {"-gui","ClusteringAgent:multi.agent_clustering.ClusteringAgent"};

            jade.Boot.main(args1);

That is

String[] args1 = {"-gui","Agent Name:package.Agent-class-name"};

 jade.Boot.main(args1);

You can even add agent in containers by making following changes:

String[] args1 = {"-container","ClusteringAgent:multi.agent_clustering.ClusteringAgent"};

            jade.Boot.main(args1);

By replacing -gui with  -container.
But make sure you have added your first agent with jade GUI before adding subsequent agents in new containers.


问:
pandas multiindex ewma rolling for each sample type
suppose I want to measure the length of an organ, lets say stomach of several species, ordered by type,
I create a multi index dataframe from a .csv with repeating values , and I take a sample everyday, making my measures noisy.

How do I apply a rolling  ewma on 60 last samples, for each of the species included in the multiindexed dataframe  ?

dataframe example :

```<code>arrays = [['mamal', 'mamal','mamal', 'mamal', 'mamal', 'mamal', 'mamal','mamal', 'mamal', 'mamal','bird', 'bird','bird', 'bird', 'reptile', 'reptile'],
          ['whale','whale','whale','whale', 'dolphin', 'dolphin', 'dolphin', 'dolphin', 'cat', 'cat', 'canary', 'canary', 'eagle', 'eagle', 'boa', 'turtle'],
          ['2017-03-01','2017-03-02','2017-03-03','2017-03-04','2017-03-01','2017-03-02','2017-03-03','2017-03-04','2017-03-03','2017-03-04','2017-03-01','2017-03-02','2017-03-03','2017-03-01','2017-03-02','2017-03-03','2017-03-01','2017-03-02','2017-03-03']]

tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

s = pd.Series(np.random.randn(13), index=index)
print(s) :

type     species  measure_date
mamal    whale    2017-03-01      0.913916
                  2017-03-02      0.860045
                  2017-03-03      1.166217
                  2017-03-04     -0.439948
         dolphin  2017-03-01      0.590208
                  2017-03-02      0.297475
                  2017-03-03      0.067966
                  2017-03-04     -0.477495
         cat      2017-03-03     -1.261023
                  2017-03-04     -0.931671
bird     canary   2017-03-01     -1.367815
                  2017-03-02     -0.820792
         eagle    2017-03-03     -0.532935
                  2017-03-01     -0.152090
reptile  boa      2017-03-02     -2.070819
         turtle   2017-03-03      1.329004
dtype: float64
</code>```

suppose I now have longer measure history , keeping a day by day measure, what is the syntaxc to perform a rolling ewma for each species, keeping each of it separate( i don't want to roll over all the measures, but only on the one of the dolphin or the whale )

I have tried

```<code>b = s.groupby(level=2,group_keys=False).apply(lambda x: pd.ewma(x,ignore_na=True,min_periods=2,adjust=True,com=0.030927835051546))
</code>```

but it only rolls over all the species, not doing a distinction on it ...

```<code>type     species  measure_date
mamal    whale    2017-03-01           NaN
                  2017-03-02           NaN
                  2017-03-03           NaN
                  2017-03-04           NaN
         dolphin  2017-03-01      0.599637
                  2017-03-02      0.313861
                  2017-03-03      0.099954
                  2017-03-04     -0.476401
         cat      2017-03-03     -1.220229
                  2017-03-04     -0.918025
bird     canary   2017-03-01     -1.308843
                  2017-03-02     -0.786782
         eagle    2017-03-03     -0.553554
                  2017-03-01     -0.186791
reptile  boa      2017-03-02     -2.032299
         turtle   2017-03-03      1.272527
</code>```

Body:
suppose I want to measure the length of an organ, lets say stomach of several species, ordered by type,
I create a multi index dataframe from a .csv with repeating values , and I take a sample everyday, making my measures noisy.

How do I apply a rolling  ewma on 60 last samples, for each of the species included in the multiindexed dataframe  ?

dataframe example :

arrays = [['mamal', 'mamal','mamal', 'mamal', 'mamal', 'mamal', 'mamal','mamal', 'mamal', 'mamal','bird', 'bird','bird', 'bird', 'reptile', 'reptile'],
          ['whale','whale','whale','whale', 'dolphin', 'dolphin', 'dolphin', 'dolphin', 'cat', 'cat', 'canary', 'canary', 'eagle', 'eagle', 'boa', 'turtle'],
          ['2017-03-01','2017-03-02','2017-03-03','2017-03-04','2017-03-01','2017-03-02','2017-03-03','2017-03-04','2017-03-03','2017-03-04','2017-03-01','2017-03-02','2017-03-03','2017-03-01','2017-03-02','2017-03-03','2017-03-01','2017-03-02','2017-03-03']]

tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

s = pd.Series(np.random.randn(13), index=index)
print(s) :

type     species  measure_date
mamal    whale    2017-03-01      0.913916
                  2017-03-02      0.860045
                  2017-03-03      1.166217
                  2017-03-04     -0.439948
         dolphin  2017-03-01      0.590208
                  2017-03-02      0.297475
                  2017-03-03      0.067966
                  2017-03-04     -0.477495
         cat      2017-03-03     -1.261023
                  2017-03-04     -0.931671
bird     canary   2017-03-01     -1.367815
                  2017-03-02     -0.820792
         eagle    2017-03-03     -0.532935
                  2017-03-01     -0.152090
reptile  boa      2017-03-02     -2.070819
         turtle   2017-03-03      1.329004
dtype: float64

suppose I now have longer measure history , keeping a day by day measure, what is the syntaxc to perform a rolling ewma for each species, keeping each of it separate( i don't want to roll over all the measures, but only on the one of the dolphin or the whale )

I have tried

b = s.groupby(level=2,group_keys=False).apply(lambda x: pd.ewma(x,ignore_na=True,min_periods=2,adjust=True,com=0.030927835051546))

but it only rolls over all the species, not doing a distinction on it ...

type     species  measure_date
mamal    whale    2017-03-01           NaN
                  2017-03-02           NaN
                  2017-03-03           NaN
                  2017-03-04           NaN
         dolphin  2017-03-01      0.599637
                  2017-03-02      0.313861
                  2017-03-03      0.099954
                  2017-03-04     -0.476401
         cat      2017-03-03     -1.220229
                  2017-03-04     -0.918025
bird     canary   2017-03-01     -1.308843
                  2017-03-02     -0.786782
         eagle    2017-03-03     -0.553554
                  2017-03-01     -0.186791
reptile  boa      2017-03-02     -2.032299
         turtle   2017-03-03      1.272527

Body:
You just need to correct the level as @ScottBoston pointed out:

s.groupby(level="second").apply(lambda x: pd.ewma(x,ignore_na=True,min_periods=2,adjust=True,com=0.030927835051546))

first    second   third
mamal    whale    2017-03-01         NaN
                  2017-03-02    0.661551
                  2017-03-03   -0.726871
                  2017-03-04   -1.873301
         dolphin  2017-03-01         NaN
                  2017-03-02    0.242347
                  2017-03-03    0.276082
                  2017-03-04    0.071822
         cat      2017-03-03         NaN
                  2017-03-04    0.441826
bird     canary   2017-03-01         NaN
                  2017-03-02    1.426628
         eagle    2017-03-03         NaN
                  2017-03-01    0.382538
reptile  boa      2017-03-02         NaN
         turtle   2017-03-03         NaN
dtype: float64


问:
stripping html tags in php with allowing an exception
For the past hour I've been trying to add an exception to strip tags, allowing only

 to remain, but unfortunately I haven't been successful in making this work, I don't get any errors either, the trim is present because it's removing whitespace from the data, any feedback would be much appreciated, thank you very much

```<code>trim(strip_tags($html->find('div[id=data]',"<p></p>")));
</code>```

答:
Follow document on php.net

```<code>string strip_tags ( string $str [, string $allowable_tags ] )
</code>```

So if you want to keep
 tag your code should be:

```<code>trim(strip_tags($html->find('div[id=data]'), '<p>'));
</code>```

Body:
For the past hour I've been trying to add an exception to strip tags, allowing only

 to remain, but unfortunately I haven't been successful in making this work, I don't get any errors either, the trim is present because it's removing whitespace from the data, any feedback would be much appreciated, thank you very much

trim(strip_tags($html->find('div[id=data]',"

")));

Body:
Follow document on php.net

string strip_tags ( string $str [, string $allowable_tags ] )

So if you want to keep <p> tag your code should be:

trim(strip_tags($html->find('div[id=data]'), '<p>'));


问:
unable to clearFocus and keep query in SearchView after submitting search
App Structure: My Main Activity is also acting as a Search Activity with a SearchView in the ActionBar. When I search in the ActionBar I handle it with onNewIntent in the Main Activity. When the intent is ACTION_SEARCH I replace the current fragment in MainActivity (possibly nothing or a previous search fragment) with a new search fragment which then creates an ASyncTask to fetch some data from an API which then creates another ASyncTask to get more details about the data and then populates a list view in the fragment.

Problem: after performing a search the SearchView field is empty and focused again.

Goal: I want the SearchView to not be focused and the SearchText to stay in case the user wants to change it.

What I have succeeded with is closing the action view (and removing focus) with MenuItemCompat.collapseActionView()

I've tried clearFocus() and setQuery() and several other methods I've found by googling but nothing seems to work. I've also tried using both in the onQueryTextSumbit function onQueryTextListener without success. I've looked at how other Apps like F-Droid and Simpletask Cloudless achieve it and most of them use filters on already existing data, whereas I am using ASyncTasks, which I think could be a source of the problem.

答: So I found an alternative solution to what was proposed in the comments (Thank you regardless pskink). When my MainActivity received the SearchIntent it created a new search list Fragment (this was my mistake). I changed the search fragment creation to OnCreate in my MainActivity with a separate function to populate the already created fragment and now clearFocus() properly works in the onQueryTextSubmit function of my SearchView listener.</p>


问:
stl Linking Error on xcode
When to generate an executable with xcode, I have 3 Linking errors. I used Irrlicht 1.9 that I compile myself this morning.

I would like to say that the file CIrrDeviceOSX.mm is an objective-c file that can be found here :
https://github.com/zaki/irrlicht/blob/master/source/Irrlicht/CIrrDeviceOSX.h
https://github.com/zaki/irrlicht/blob/master/source/Irrlicht/CIrrDeviceOSX.mm

I think that the error is inside "std::map KeyCodes;" in CIrrDeviceOSX.h and used in CIrrDeviceOSX.mm

I dont know if the problem is that the file is in objective-c and the signature of the methods is different or that there are difference in version of the C++ (c++11 or ???).

Ld bin/Debug/minetest normal x86_64
    cd /Users/bluholm/Desktop/minetest-release/minetest
    export MACOSX_DEPLOYMENT_TARGET=10.12
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -L/Users/bluholm/Desktop/minetest-release/minetest/bin/Debug -F/Users/bluholm/Desktop/minetest-release/minetest/bin/Debug -filelist /Users/bluholm/Desktop/minetest-release/minetest-osx/src/minetest.build/Debug/minetest.build/Objects-normal/x86_64/minetest.LinkFileList -mmacosx-version-min=10.12 -Xlinker -object_path_lto -Xlinker /Users/bluholm/Desktop/minetest-release/minetest-osx/src/minetest.build/Debug/minetest.build/Objects-normal/x86_64/minetest_lto.o -Xlinker -no_deduplicate -lc++ -pagezero_size 10000 -image_base 100000000 -Wl,-search_paths_first -Wl,-headerpad_max_install_names /usr/lib/libz.dylib /usr/local/Cellar/irrlicht/1.9/lib/libIrrlicht.a -framework OpenGL -framework OpenAL /usr/local/lib/libvorbisfile.dylib /usr/local/lib/libvorbis.dylib /usr/local/lib/libogg.dylib /usr/lib/libsqlite3.dylib /usr/local/lib/libluajit-5.1.dylib /Users/bluholm/Desktop/minetest-release/minetest-osx/src/gmp/Debug/libgmp.a /Users/bluholm/Desktop/minetest-release/minetest-osx/src/jsoncpp/json/Debug/libjsoncpp.a -framework CoreFoundation -lpthread /usr/lib/libiconv.dylib -framework Carbon -framework Cocoa -framework IOKit /usr/lib/libiconv.dylib /usr/lib/libcurl.dylib /usr/local/lib/libfreetype.dylib /Users/bluholm/Desktop/minetest-release/minetest-osx/src/cguittfont/Debug/libcguittfont.a /usr/lib/libcurses.dylib /usr/lib/libform.dylib /usr/local/lib/libhiredis.dylib -framework Carbon -framework Cocoa -framework IOKit /usr/lib/libcurl.dylib /usr/lib/libcurses.dylib /usr/lib/libform.dylib /usr/local/lib/libhiredis.dylib /usr/lib/libz.dylib /usr/local/Cellar/irrlicht/1.9/lib/libIrrlicht.a /usr/local/lib/libfreetype.dylib -Xlinker -dependency_info -Xlinker /Users/bluholm/Desktop/minetest-release/minetest-osx/src/minetest.build/Debug/minetest.build/Objects-normal/x86_64/minetest_dependency_info.dat -o /Users/bluholm/Desktop/minetest-release/minetest/bin/Debug/minetest

Undefined symbols for architecture x86_64:

"std::_Rb_tree_decrement(std::_Rb_tree_node_base*)", referenced from:
      std::_Rb_tree_iterator >::operator--() in libIrrlicht.a(CIrrDeviceOSX.o)

"std::_Rb_tree_increment(std::_Rb_tree_node_base*)", referenced from:
      std::_Rb_tree_iterator >::operator++() in libIrrlicht.a(CIrrDeviceOSX.o)

"std::_Rb_tree_insert_and_rebalance(bool, std::_Rb_tree_node_base*, std::_Rb_tree_node_base*, std::_Rb_tree_node_base&)", referenced from:
      std::_Rb_tree, std::_Select1st >, std::less, std::allocator > >::_M_insert(std::_Rb_tree_node_base*, std::_Rb_tree_node_base*, std::pair const&) in libIrrlicht.a(CIrrDeviceOSX.o)

ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

答: Try to created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++</p>

Title: stl Linking Error on xcode


问:
Component paramaters not updating
For some reason the parameters in my component doesn't seem to be changing. The problem can be solved if I subscribe to the observable but I feel like something else must be going wrong and I cant figure it out.

I have the template and viewModel in their own file.

Here is my view model:

```<code>function model(params){
    var viewModel = {};
    viewModel.foo = ko.observable();
    params.value.subscribe(function(data){
        viewModel.foo(data);
    });
    return viewModel;
}
</code>```

Here is my template:

```<code>function template(){
    var template =`<div data-bind="text: foo></div>`;
    return template;
}
</code>```

And here is where I register it.

```<code>ko.components.register('foo-template', {
    viewModel: { createViewModel: model },
    template: template()
});
</code>```

Here is where I use it in the HTML. Foo would be a delcared observable in the main view model.

```<code><foo-template params="value: foo"></foo-template>
</code>```

Everything works fine if I subscribe to the params.value but I feel like I shouldn't need to use this.

答:
I think the problem is that you're trying to bind the data to a div. Divs do not normally support writable text and the text binding doesn't work well with them. If you replace the div in your template with a standard input text box everything seems to work as expected.

ko.components.register('foo-template', {
    viewModel: { createViewModel: model },
    template: template()
});

function model(params){
    var viewModel = {};
    viewModel.foo = params.value;
    //viewModel.foo = ko.observable('internal value');
    return viewModel;
}

function template(){
    var template =`Internal foo: <input type="text" data-bind="textInput: foo"></input>`;
    return template;
}

ko.applyBindings({foo: ko.observable('test')});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div>
  <foo-template params="value: foo"></foo-template>
  <br />
  External foo: <span data-bind="text: ko.toJSON(foo)"></span>
</div></code>```

Title: Component paramaters not updating

Body:
For some reason the parameters in my component doesn't seem to be changing. The problem can be solved if I subscribe to the observable but I feel like something else must be going wrong and I cant figure it out.

I have the template and viewModel in their own file.

Here is my view model:

function model(params){
    var viewModel = {};
    viewModel.foo = ko.observable();
    params.value.subscribe(function(data){
        viewModel.foo(data);
    });
    return viewModel;
}

Here is my template:

function template(){
    var template =`<div data-bind="text: foo></div>`;
    return template;
}

And here is where I register it.

ko.components.register('foo-template', {
    viewModel: { createViewModel: model },
    template: template()
});

Here is where I use it in the HTML. Foo would be a delcared observable in the main view model.

<foo-template params="value: foo"></foo-template>

Everything works fine if I subscribe to the params.value but I feel like I shouldn't need to use this.

Body:
I think the problem is that you're trying to bind the data to a div. Divs do not normally support writable text and the text binding doesn't work well with them. If you replace the div in your template with a standard input text box everything seems to work as expected.

ko.components.register('foo-template', {
    viewModel: { createViewModel: model },
    template: template()
});

function model(params){
    var viewModel = {};
    viewModel.foo = params.value;
    //viewModel.foo = ko.observable('internal value');
    return viewModel;
}

function template(){
    var template =`Internal foo: <input type="text" data-bind="textInput: foo"></input>`;
    return template;
}

ko.applyBindings({foo: ko.observable('test')});

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div>
  <foo-template params="value: foo"></foo-template>
  <br />
  External foo: <span data-bind="text: ko.toJSON(foo)"></span>
</div>