问:
Is there a reason we cannot name a non-static member function in an unevaluated context?
When reading [expr.prim.id], one will see that

An id-expression that denotes a non-static data member or non-static
  member function of a class can only be used:

if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

The fact that the bullet above applies only to data members is unclear to me. Intuitively I'd expect the following to be well formed:

```<code>#include <type_traits>

using func = int();

class bar {
  func foo; // This is valid, and not the subject of the question
};

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");
</code>```

But the decltype() is ill-formed even before the static assertion is checked.

Is there some ambiguity I'm missing?

答:
Is there some ambiguity I'm missing?

The fact there's a whole lot of type information that is added as part of that member function declaration.

While func may certainly be used to declare that member, the story doesn't end here. Once the member is declared, it's type is completed. That involves adding a couple of other things, like cv-qualifers and ref-qualifiers. In the case of foo, all the default implicit ones are determined, and they become part of bar::foo's type. As specified by [dcl.fct]/8:

The return type, the parameter-type-list, the ref-qualifier, the
  cv-qualifier-seq, and the exception specification, but not the default
  arguments, are part of the function type.

There's no way to specify them explicitly in the above declaration of foo (though they may be added to func), but they may be added in general:

```<code>class bar {
  int foo() const volatile &&;
};
</code>```

They are part of the function type, and decltype(bar::foo) should address them if they appear (and if I gather correctly, even if they don't).

Where does the const volatile && go when we attempt to evaluate decltype(bar::foo)?

Should it be ignored? That can be done. But losing type information is rarely a good thing.

Should we retain it, and the type decltype evaluates to be a pointer to a member function, instead?

That too would work, but now it's different from how data members would behave when named in an unevaluated context. We introduce a discrepancy.

Should it be retained, and the type resolved to something else? Perhaps something like int(foo const volatile&&) or int() const volatile && (another form of function type)? That breaks the symmetry one would expect to have, and is again a discrepancy to data members.

There is no easy or obvious way in which allowing it would always work well. So rather than complicate matters for a feature that would see limited use, it's better to regard it as ill-formed.

Body:
When reading [expr.prim.id], one will see that

An id-expression that denotes a non-static data member or non-static
  member function of a class can only be used:

if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

The fact that the bullet above applies only to data members is unclear to me. Intuitively I'd expect the following to be well formed:

#include <type_traits>

using func = int();

class bar {
  func foo; // This is valid, and not the subject of the question
};

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");

But the decltype() is ill-formed even before the static assertion is checked.

Is there some ambiguity I'm missing?

Body:
Is there some ambiguity I'm missing?

The fact there's a whole lot of type information that is added as part of that member function declaration.

While func may certainly be used to declare that member, the story doesn't end here. Once the member is declared, it's type is completed. That involves adding a couple of other things, like cv-qualifers and ref-qualifiers. In the case of foo, all the default implicit ones are determined, and they become part of bar::foo's type. As specified by [dcl.fct]/8:

The return type, the parameter-type-list, the ref-qualifier, the
  cv-qualifier-seq, and the exception specification, but not the default
  arguments, are part of the function type.

There's no way to specify them explicitly in the above declaration of foo (though they may be added to func), but they may be added in general:

class bar {
  int foo() const volatile &&;
};

They are part of the function type, and decltype(bar::foo) should address them if they appear (and if I gather correctly, even if they don't).

Where does the const volatile && go when we attempt to evaluate decltype(bar::foo)?

Should it be ignored? That can be done. But losing type information is rarely a good thing.

Should we retain it, and the type decltype evaluates to be a pointer to a member function, instead?

That too would work, but now it's different from how data members would behave when named in an unevaluated context. We introduce a discrepancy.

Should it be retained, and the type resolved to something else? Perhaps something like int(foo const volatile&&) or int() const volatile && (another form of function type)? That breaks the symmetry one would expect to have, and is again a discrepancy to data members.

There is no easy or obvious way in which allowing it would always work well. So rather than complicate matters for a feature that would see limited use, it's better to regard it as ill-formed.


来源: stackexchange

问:
Debug phoenix test with IEx
I know you can debug the webapp with IEx but is it possible to set a breakpoint inside a test?

For example in the following test I would like to check what's inside conn or check any other variable or macro.

```<code>defmodule HelloWeb.PageControllerTest do
  use HelloWeb.ConnCase
  require IEx
  test "GET /", %{conn: conn} do
    IEx.pry
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end
</code>```

In order to make it work with the webapp you must have phoenix.server running with iex -S mix phoenix.server

But in this case is a test not the webapp so it complains with:

```<code>Cannot pry #PID<0.406.0> at ... Is an IEx shell running?
</code>```

答:
ExUnit tests are in .exs files that mean interpreted code is written in it. So you can't set break point in it.

For more informations about .exs and .ex file. See  Elixir: When to use .ex and when .exs files

If you want to check any map simply write

```<code>    IO.inspect conn
</code>```

And for simple variable you can write

```<code>    IO.puts variable_name
</code>```

ContentLicense: CC BY-SA 3.0

Title: Debug phoenix test with IEx

Body:
I know you can debug the webapp with IEx but is it possible to set a breakpoint inside a test?

For example in the following test I would like to check what's inside conn or check any other variable or macro.

defmodule HelloWeb.PageControllerTest do
  use HelloWeb.ConnCase
  require IEx
  test "GET /", %{conn: conn} do
    IEx.pry
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end

In order to make it work with the webapp you must have phoenix.server running with iex -S mix phoenix.server

But in this case is a test not the webapp so it complains with:

Cannot pry #PID<0.406.0> at ... Is an IEx shell running?

Body:
ExUnit tests are in .exs files that mean interpreted code is written in it. So you can't set break point in it.

For more informations about .exs and .ex file. See  Elixir: When to use .ex and when .exs files

If you want to check any map simply write

    IO.inspect conn

And for simple variable you can write

    IO.puts variable_name


问:
disable home button for API 19
I am working on one app(KIOSK). in that for API 19 following code is not working

```<code> <activity android:name=".activity.HomeActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.MONKEY"/>
            </intent-filter>
        </activity>
</code>```

I want to set this app as launcher default app like home screen when user clicks on home button.
Please help

答:
Try to remove: <category android:name="android.intent.category.MONKEY"/>.

And you still need:

```<code><activity ...>
   <!-- Add this -->
    <intent-filter>
       <action android:name="android.intent.action.MAIN" />
       <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
    <!-- Your other filter -->
    </intent-filter>
</activity>
</code>```

Title: disable home button for API 19

Body:
I am working on one app(KIOSK). in that for API 19 following code is not working

 <activity android:name=".activity.HomeActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.MONKEY"/>
            </intent-filter>
        </activity>

I want to set this app as launcher default app like home screen when user clicks on home button.
Please help

Body:
Try to remove: <category android:name="android.intent.category.MONKEY"/>.

And you still need:

<activity ...>
   <!-- Add this -->
    <intent-filter>
       <action android:name="android.intent.action.MAIN" />
       <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
    <!-- Your other filter -->
    </intent-filter>
</activity>


问:
tensorflow: undefined symbol: cudnnSetRNNDescriptor_v6
when I finished installing tensorflow (GPU_support,linux 14.04,python3.4) with virtualenv environment,under the instructions of the official website, i validated the installation with the command :python; import tensorflow; but there is an error:

import tensorflow as tf
Traceback (most recent call last):
File "/home/fangfang/tensorflow/lib/python3.4/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/fangfang/tensorflow/lib/python3.4/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/fangfang/tensorflow/lib/python3.4/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/fangfang/tensorflow/lib/python3.4/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
***ImportError: /home/fangfang/tensorflow/lib/python3.4/site-packages/tensorflow/python/../libtensorflow_framework.so: undefined symbol: cudnnSetRNNDescriptor_v6***

答:
I had this same error, and so hopefully this solution will work for you...

What version of CuDNN are you using? I found that versions of tensorflow-gpu > 1.2 would fail to load while I had CuDNN v5.1.10 installed.

At the time I'm writing this, Tensorflow docs say you must have CuDNN v6. https://www.tensorflow.org/install/install_linux#nvidia_requirements_to_run_tensorflow_with_gpu_support

So I just removed the old CuDNN binaries and headers:

$ sudo rm /usr/local/cuda/include/cudnn.h

$ sudo rm /usr/local/cuda/lib64/libcudnn.so

$ sudo rm /usr/local/cuda/lib64/libcudnn.so.5.1.10

and any other remnants of v5.1.10. Then just download and copy the new v6 headers and binaries into those same locations.

This is a useful command to check your CuDNN version:

$ cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2


问:
Function sorting array of structures by passed structure member
here is my problem:
let's say I have a struct:

```<code>enum color{Black, Red, White};
struct car
{   int weight;
    int price;
    enum color my_color;
};
</code>```

I've initialized 10 element array:

```<code>struct car cars[10];

for (int i = 0; i < 10; i++)
    {
        cars[i].weight = (rand() % 1000); // do not mind the number values
        cars[i].price= (rand() % 1000);
        cars[i].my_color= (rand() % 2);
    }
</code>```

Now my job is to write a function which would return sorted array, and the passed argument should be either of struct members (weight, price, color). I know there are lot of sorting algorithms but I have no idea how to sort it using only one of the members. How would this sorting function look like?

答:
In C, there is no way to syntactically access a struct member as such in order to have some generic comparison on them. That being said, the usual approach would be to call the qsort library function, which is introduced here, to perform the sorting. It is designed to take a function pointer as an agrument; this would be used to implement and provide a function which does that actual comparison.

To solve the task in the question, It would be necessary to implement a comparison function for each member of the car type.

Body:
here is my problem:
let's say I have a struct:

enum color{Black, Red, White};
struct car
{   int weight;
    int price;
    enum color my_color;
};

I've initialized 10 element array:

struct car cars[10];

for (int i = 0; i < 10; i++)
    {
        cars[i].weight = (rand() % 1000); // do not mind the number values
        cars[i].price= (rand() % 1000);
        cars[i].my_color= (rand() % 2);
    }

Now my job is to write a function which would return sorted array, and the passed argument should be either of struct members (weight, price, color). I know there are lot of sorting algorithms but I have no idea how to sort it using only one of the members. How would this sorting function look like?


问:
what ratio should we keep between kafka broker and zookeeper?
I have read that if we have 4 kafka cluster why do we need 5 ZK than. This is said that it is the most optimistic way to make kafka clusters but I didn't get this point.

please explain me this. I have tried 3 brokers with 3 ZK so far.

答:
Kafka uses ZK for coordination of brokers, election of controller, etc. This post describes this in great details.  Usually, ZK is operated as cluster of instances with odd number of instances to be able to make decision based on quorum, so usual size is 3, 5, 7, ...

For that size of Kafka cluster, 3 ZKs should be enough, although it may depend on the load to ZK, and some other factors


问:
Bing custom search apis returning only limited results from one location and full result from different location
I am trying to use Bing Custom Search's API for documents from Cognitive Services. The strange thing is that when I run it from India, it gives me more than a thousand results, but when I run it from a US server, it returns only 25 (sometimes 50 results). Here is the sample code for that:

var totalCount = 0;
var filetypes = new List<string> { "pdf", "docx", "doc" };
foreach (var filetype in filetypes)
{
    var searchTerm = "microsoft%20.net%20resume+filetype%3a" + filetype;
    Console.WriteLine("Searching for : " + filetype);

    for (var i = 0; i < 40; i++)
    {
        var nextCount = 0;
        var url = "https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?" +
                  "q=" + searchTerm +
                  "&customconfig=" + customConfigId +
                  "&count=25" + "&offset=" + ((i * 25) + nextCount);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            var httpResponseMessage = client.GetAsync(url).Result;
            var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result;
            BingCustomSearchResponse response =
                JsonConvert.DeserializeObject<BingCustomSearchResponse>(responseContent);

            if (response.webPages == null || response.webPages.value.Length <= 0)
            {
                Console.WriteLine("response.webPages is null ");
                break;
            }

            foreach (var webPage in response.webPages.value)
            {
                Console.WriteLine("name: " + webPage.name);
                Console.WriteLine("url: " + webPage.url);
                Console.WriteLine("displayUrl: " + webPage.displayUrl);
                Console.WriteLine("snippet: " + webPage.snippet);
                Console.WriteLine("dateLastCrawled: " + webPage.dateLastCrawled);
                Console.WriteLine();
            }
            totalCount = totalCount + response.webPages.value.Length;
        }
    }
}
```

The subscription key I am using is a trial key.

答:
I got the reason of this behavior. Actually it had nothing to do with region/country/market.
After looking into the response i got this message.
"Rate limit is exceeded. Try again in 1 seconds"
It means for after each call in the loop i have to wait for 1 second to give next call. Now need to know is this limit for trial subscription or this is kept for all calls to prevent DDOS attack or something.
May be from India it was working because may one iteraction is already taking one or more second. </p>

Body:
I am trying to use Bing Custom Search's API for documents from Cognitive Services. The strange thing is that when I run it from India, it gives me more than a thousand results, but when I run it from a US server, it returns only 25 (sometimes 50 results). Here is the sample code for that:

var totalCount = 0;
var filetypes = new List<string> { "pdf", "docx", "doc" };
foreach (var filetype in filetypes)
{
    var searchTerm = "microsoft%20.net%20resume+filetype%3a" + filetype;
    Console.WriteLine("Searching for : " + filetype);

    for (var i = 0; i < 40; i++)
    {
        var nextCount = 0;
        var url = "https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?" +
                  "q=" + searchTerm +
                  "&customconfig=" + customConfigId +
                  "&count=25" + "&offset=" + ((i * 25) + nextCount);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            var httpResponseMessage = client.GetAsync(url).Result;
            var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result;
            BingCustomSearchResponse response =
                JsonConvert.DeserializeObject<BingCustomSearchResponse>(responseContent);

            if (response.webPages == null || response.webPages.value.Length <= 0)
            {
                Console.WriteLine("response.webPages is null ");
                break;
            }

            foreach (var webPage in response.webPages.value)
            {
                Console.WriteLine("name: " + webPage.name);
                Console.WriteLine("url: " + webPage.url);
                Console.WriteLine("displayUrl: " + webPage.displayUrl);
                Console.WriteLine("snippet: " + webPage.snippet);
                Console.WriteLine("dateLastCrawled: " + webPage.dateLastCrawled);
                Console.WriteLine();
            }
            totalCount = totalCount + response.webPages.value.Length;
        }
    }
}

The subscription key I am using is a trial key.


问:
Any openssl command line to verify ECDSA prime256v1 certificate and private key match?
I'm now testing the hyperledger/fabric/core/comm/testdata/certs/generate.go to get the ECDSA prime256v1 certificate(Org1-cert.pem) and private key(Org1-key.pem).
I want to use a openssl command line to test if the Org1-cert.pem mathes the Org1-key.pem, but don't know how? Any help appreciated.
I've used the command, but the results don't match the same.

```<code># openssl x509 -pubkey -in Org1-cert.pem -noout | openssl md5
</code>```

(stdin)= 4f8782bbec9d258553f0c0c7c6879fef

```<code># openssl pkey -pubout -in Org1-key.pem | openssl md5
</code>```

(stdin)= 98c3ec3c2971648f2721915ff7e80479

more info about Org1-cert.pem and Org1-key.pem below:

```<code># openssl x509 -in Org1-cert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            50:0a:7a:e4:31:6e:1b:57:68:48:26:d7:a0:c5:9c:da
    Signature Algorithm: ecdsa-with-SHA256
        Issuer: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Validity
            Not Before: Nov 13 09:09:06 2017 GMT
            Not After : Nov 11 09:09:06 2027 GMT
        Subject: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:ac:bb:17:91:91:1e:72:38:d2:aa:9a:2d:17:c8:
                    50:80:18:58:4a:a8:6a:40:0a:a8:2a:a8:58:33:46:
                    ae:2c:48:67:28:c7:af:59:09:92:01:68:15:cd:e5:
                    c0:84:d1:1e:3e:03:60:25:8b:55:89:3e:e9:e2:f1:
                    23:3e:e4:c4:c8
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment, Certificate Sign, CRL Sign
            X509v3 Extended Key Usage:
                Any Extended Key Usage
            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Subject Key Identifier:
                01:02:03:04
    Signature Algorithm: ecdsa-with-SHA256
         30:46:02:21:00:b4:81:76:75:fe:a1:1c:14:94:3e:d6:eb:b3:
         43:02:27:32:46:2e:c0:6d:b7:94:3b:9d:a9:05:ad:c9:10:29:
         34:02:21:00:80:31:3c:00:18:b3:c0:be:1d:73:dc:ab:9b:aa:
         28:75:86:bc:2a:97:64:9d:65:5f:6f:6f:a0:c8:38:aa:2c:35

    # more Org1-key.pem

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDgnuzTIxFYZorg/lKBQxwpyXWH7zREzuO8Gle9p8CzQoAoGCCqGSM49
AwEHoUQDQgAEsYeTGiApHX1SJAZ7HmroVR1YNBH6wc0WqiNWO/N3XG/aWxksYLA8
s2asE88Z5EOWs1qMLig2nyv3CL0H2VI0zg==
-----END EC PRIVATE KEY-----

    # more Org1-cert.pem

-----BEGIN CERTIFICATE-----
MIIB8jCCAZegAwIBAgIQUAp65DFuG1doSCbXoMWc2jAKBggqhkjOPQQDAjBYMQsw
CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
YW5jaXNjbzENMAsGA1UEChMET3JnMTENMAsGA1UEAxMET3JnMTAeFw0xNzExMTMw
OTA5MDZaFw0yNzExMTEwOTA5MDZaMFgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpD
YWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ0wCwYDVQQKEwRPcmcx
MQ0wCwYDVQQDEwRPcmcxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErLsXkZEe
cjjSqpotF8hQgBhYSqhqQAqoKqhYM0auLEhnKMevWQmSAWgVzeXAhNEePgNgJYtV
iT7p4vEjPuTEyKNDMEEwDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAw
DwYDVR0TAQH/BAUwAwEB/zANBgNVHQ4EBgQEAQIDBDAKBggqhkjOPQQDAgNJADBG
AiEAtIF2df6hHBSUPtbrs0MCJzJGLsBtt5Q7nakFrckQKTQCIQCAMTwAGLPAvh1z
3Kubqih1hrwql2SdZV9vb6DIOKosNQ==
-----END CERTIFICATE-----
</code>```

答:
What you need to do is read the certificate and private key and check if the public key of the certificate matches the public key in the private key.

```<code>openssl x509 -in signcerts/peer.pem -text -noout
</code>```

```<code>Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            04:45:70:b1:2c:74:4e:6a:9d:6f:33:70:95:e3:41:07:3a:08:4f:4c
    Signature Algorithm: ecdsa-with-SHA256
        Issuer: C=US, ST=California, L=San Francisco, O=Internet Widgets, Inc., OU=WWW, CN=example.com
        Validity
            Not Before: Nov 11 17:07:00 2016 GMT
            Not After : Nov 11 17:07:00 2017 GMT
        Subject: C=US, ST=North Carolina, L=Raleigh, O=Hyperledger Fabric, OU=COP
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:1c:1b:8a:b0:03:b8:de:1b:38:24:6a:45:7e:21:
                    8c:90:1f:f1:b0:82:d3:b0:eb:e6:37:65:a6:c2:9b:
                    0f:1d:93:4b:eb:0f:07:59:ed:f1:08:f4:2d:74:6f:
                    d7:24:9b:d9:f8:2e:f9:e8:a1:2c:50:13:37:cb:0e:
                    4f:4d:f9:2e:f2
                ASN1 OID: prime256v1
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Subject Key Identifier:
                E1:42:75:C5:19:E1:EB:37:96:D8:82:80:05:43:A3:22:DF:56:93:C8
            X509v3 Authority Key Identifier:
                keyid:17:67:42:3D:AA:9E:82:3F:C4:C5:1D:9F:5B:C3:99:D1:B5:9C:48:10

            X509v3 Subject Alternative Name:
                DNS:myhost.com, DNS:www.myhost.com
    Signature Algorithm: ecdsa-with-SHA256
         30:45:02:20:37:fd:1d:b9:78:c6:7d:f3:e0:4c:0d:2a:68:a5:
         33:d9:57:d8:5a:b8:8d:6a:40:69:15:41:f7:b3:a6:54:47:b2:
         02:21:00:db:96:83:3d:01:c6:1a:ad:80:be:12:93:d3:0b:ed:
         d3:c7:17:d4:64:c6:08:86:df:9a:e2:e9:33:02:90:8f:7f
</code>```

```<code>openssl ec -in keystore/key.pem -text -noout
</code>```

```<code>read EC key
Private-Key: (256 bit)
priv:
    0b:16:c0:5b:a7:13:3a:b3:d5:18:7a:9e:f0:f8:32:
    23:e4:28:2b:66:a3:1c:e1:de:34:ea:b8:6e:4c:49:
    b7:8b
pub:
    04:1c:1b:8a:b0:03:b8:de:1b:38:24:6a:45:7e:21:
    8c:90:1f:f1:b0:82:d3:b0:eb:e6:37:65:a6:c2:9b:
    0f:1d:93:4b:eb:0f:07:59:ed:f1:08:f4:2d:74:6f:
    d7:24:9b:d9:f8:2e:f9:e8:a1:2c:50:13:37:cb:0e:
    4f:4d:f9:2e:f2
ASN1 OID: prime256v1
</code>```

Body:
I'm now testing the hyperledger/fabric/core/comm/testdata/certs/generate.go to get the ECDSA prime256v1 certificate(Org1-cert.pem) and private key(Org1-key.pem).
I want to use a openssl command line to test if the Org1-cert.pem mathes the Org1-key.pem, but don't know how? Any help appreciated.
I've used the command, but the results don't match the same.

# openssl x509 -pubkey -in Org1-cert.pem -noout | openssl md5

(stdin)= 4f8782bbec9d258553f0c0c7c6879fef

# openssl pkey -pubout -in Org1-key.pem | openssl md5

(stdin)= 98c3ec3c2971648f2721915ff7e80479

more info about Org1-cert.pem and Org1-key.pem below:

# openssl x509 -in Org1-cert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            50:0a:7a:e4:31:6e:1b:57:68:48:26:d7:a0:c5:9c:da
    Signature Algorithm: ecdsa-with-SHA256
        Issuer: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Validity
            Not Before: Nov 13 09:09:06 2017 GMT
            Not After : Nov 11 09:09:06 2027 GMT
        Subject: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:ac:bb:17:91:91:1e:72:38:d2:aa:9a:2d:17:c8:
                    50:80:18:58:4a:a8:6a:40:0a:a8:2a:a8:58:33:46:
                    ae:2c:48:67:28:c7:af:59:09:92:01:68:15:cd:e5:
                    c0:84:d1:1e:3e:03:60:25:8b:55:89:3e:e9:e2:f1:
                    23:3e:e4:c4:c8
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment, Certificate Sign, CRL Sign
            X509v3 Extended Key Usage:
                Any Extended Key Usage
            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Subject Key Identifier:
                01:02:03:04
    Signature Algorithm: ecdsa-with-SHA256
         30:46:02:21:00:b4:81:76:75:fe:a1:1c:14:94:3e:d6:eb:b3:
         43:02:27:32:46:2e:c0:6d:b7:94:3b:9d:a9:05:ad:c9:10:29:
         34:02:21:00:80:31:3c:00:18:b3:c0:be:1d:73:dc:ab:9b:aa:
         28:75:86:bc:2a:97:64:9d:65:5f:6f:6f:a0:c8:38:aa:2c:35

    # more Org1-key.pem

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDgnuzTIxFYZorg/lKBQxwpyXWH7zREzuO8Gle9p8CzQoAoGCCqGSM49
AwEHoUQDQgAEsYeTGiApHX1SJAZ7HmroVR1YNBH6wc0WqiNWO/N3XG/aWxksYLA8
s2asE88Z5EOWs1qMLig2nyv3CL0H2VI0zg==
-----END EC PRIVATE KEY-----

    # more Org1-cert.pem

-----BEGIN CERTIFICATE-----
MIIB8jCCAZegAwIBAgIQUAp65DFuG1doSCbXoMWc2jAKBggqhkjOPQQDAjBYMQsw
CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
YW5jaXNjbzENMAsGA1UEChMET3JnMTENMAsGA1UEAxMET3JnMTAeFw0xNzExMTMw
OTA5MDZaFw0yNzExMTEwOTA5MDZaMFgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpD
YWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ0wCwYDVQQKEwRPcmcx
MQ0wCwYDVQQDEwRPcmcxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErLsXkZEe
cjjSqpotF8hQgBhYSqhqQAqoKqhYM0auLEhnKMevWQmSAWgVzeXAhNEePgNgJYtV
iT7p4vEjPuTEyKNDMEEwDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAw
DwYDVR0TAQH/BAUwAwEB/zANBgNVHQ4EBgQEAQIDBDAKBggqhkjOPQQDAgNJADBG
AiEAtIF2df6hHBSUPtbrs0MCJzJGLsBtt5Q7nakFrckQKTQCIQCAMTwAGLPAvh1z
3Kubqih1hrwql2SdZV9vb6DIOKosNQ==
-----END CERTIFICATE-----

Body:
What you need to do is read the certificate and private key and check if the public key of the certificate matches the public key in the private key.

openssl x509 -in signcerts/peer.pem -text -noout

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            04:45:70:b1:2c:74:4e:6a:9d:6f:33:70:95:e3:41:07:3a:08:4f:4c
    Signature Algorithm: ecdsa-with-SHA256
        Issuer: C=US, ST=California, L=San Francisco, O=Internet Widgets, Inc., OU=WWW, CN=example.com
        Validity
            Not Before: Nov 11 17:07:00 2016 GMT
            Not After : Nov 11 17:07:00 2017 GMT
        Subject: C=US, ST=North Carolina, L=Raleigh, O=Hyperledger Fabric, OU=COP
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:1c:1b:8a:b0:03:b8:de:1b:38:24:6a:45:7e:21:
                    8c:90:1f:f1:b0:82:d3:b0:eb:e6:37:65:a6:c2:9b:
                    0f:1d:93:4b:eb:0f:07:59:ed:f1:08:f4:2d:74:6f:
                    d7:24:9b:d9:f8:2e:f9:e8:a1:2c:50:13:37:cb:0e:
                    4f:4d:f9:2e:f2
                ASN1 OID: prime256v1
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Subject Key Identifier:
                E1:42:75:C5:19:E1:EB:37:96:D8:82:80:05:43:A3:22:DF:56:93:C8
            X509v3 Authority Key Identifier:
                keyid:17:67:42:3D:AA:9E:82:3F:C4:C5:1D:9F:5B:C3:99:D1:B5:9C:48:10

            X509v3 Subject Alternative Name:
                DNS:myhost.com, DNS:www.myhost.com
    Signature Algorithm: ecdsa-with-SHA256
         30:45:02:20:37:fd:1d:b9:78:c6:7d:f3:e0:4c:0d:2a:68:a5:
         33:d9:57:d8:5a:b8:8d:6a:40:69:15:41:f7:b3:a6:54:47:b2:
         02:21:00:db:96:83:3d:01:c6:1a:ad:80:be:12:93:d3:0b:ed:
         d3:c7:17:d4:64:c6:08:86:df:9a:e2:e9:33:02:90:8f:7f

openssl ec -in keystore/key.pem -text -noout

read EC key
Private-Key: (256 bit)
priv:
    0b:16:c0:5b:a7:13:3a:b3:d5:18:7a:9e:f0:f8:32:
    23:e4:28:2b:66:a3:1c:e1:de:34:ea:b8:6e:4c:49:
    b7:8b
pub:
    04:1c:1b:8a:b0:03:b8:de:1b:38:24:6a:45:7e:21:
    8c:90:1f:f1:b0:82:d3:b0:eb:e6:37:65:a6:c2:9b:
    0f:1d:93:4b:eb:0f:07:59:ed:f1:08:f4:2d:74:6f:
    d7:24:9b:d9:f8:2e:f9:e8:a1:2c:50:13:37:cb:0e:
    4f:4d:f9:2e:f2
ASN1 OID: prime256v1


问:
Stop Hibernate from updating collections when they have not changed
I have two entity beans defined as follows (unrelated stuff removed):

```<code>@Entity
@Table(...)
public class MasterItem implements java.io.Serializable {

  private Set<CriticalItems> criticalItemses = new HashSet<CriticalItems>(0);

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "masterItem", orphanRemoval = true,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public Set<CriticalItems> getCriticalItemses() {
        return this.criticalItemses;
    }
}
</code>```

CriticalItems is defined as follows:

```<code>@Entity
@Table(...)
public class CriticalItems implements java.io.Serializable {

    private MasterItem masterItem;

    @ManyToOne(fetch = FetchType.LAZY, optional = false,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE})
    @JoinColumn(name = "mi_item_id", nullable = false)
    public MasterItem getMasterItem() {
        return this.masterItem;
    }
}
</code>```

And in my DAO code - I have these methods:

```<code>public MasterItem load(int id) {
    MasterItem results = (MasterItem) getSessionFactory().getCurrentSession()
        .get("com.xxx.MasterItem", id);

}

public void save(MasterItem master) {
    // master has been changed by the UI since it
    getSessionFactory().getCurrentSession().saveOrUpdate(master);
}
</code>```

When I load a MasterItem, it loads correctly, and also loads the CriticalItems Set with data, as directed.  Then, I send this data to my UI, and get an updated copy back, which I then try to persist.   The user updates fields in the MasterItem object, but does not touch the CriticalItems Set or anything in it - it remains unmodified.

When my save() method is invoked, Hibernate is insisting on sending SQL updates for each item in the Set of CriticalItems, even though none of them have changed in any way.

After some digging, here's what I think is happening.  When I do a saveOrUpdate(), Hibernate sees my MasterItem object is in a detached state, so it tries to reload it from disk.  However, when doing so, it appears to be using a prepared statement (which was auto-created by Hibernate at start-up) and this prepared statement does not attempt to join to the CriticalItems data.

So Hibernate has my updated MasterItem object with a full Set of CriticalItems, but uses a MasterItem without collections as its "previousState" object.  Thus, all CriticalItems get updated via SQL (not inserted, which is interesting in itself).

Did I do something in my annotations that caused this behavior?  I know I can use an Interceptor to find out of the item has really changed, or changed the dirty flag to override Hibernate's default algorithm - but this seems to be something that Hibernate should just handle on its own without my intervention.

Any insight would be appreciated.

UPDATE:
Based on comments, I think I understand the difference between saveOrUpdate() and merge().  I realize that saveOrUpdate() will result in either an SQL INSERT or an SQL UPDATE in all cases, and that merge, in theory, will only issue updates if the object has changed from it's persistent state, but in order to determine that, Hibernate has to reload the object first via SQL SELECT.

So, I thought I could just go back into my code and change saveOrUpdate() to merge() and it would work, but that wasn't quite the case.

When I used merge(), I was getting

```<code>org.springframework.orm.hibernate3.HibernateSystemException: could not initialize proxy - no Session; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session
</code>```

but it worked fine if I changed back to saveOrUpdate().

I finally found out why - I didn't include CascadeType.MERGE in my @Cascade annotation (ugh).  Once I fixed that, the exception went away.

答:
That's the semantical difference between update() and merge().

From Christian Bauer and Gavin King's Java Persistence with Hibernate (I can't find clear explanation of this behaviour in the Hibernate docs):

The update() method forces an update to the persistent state of the object in
  the database, always scheduling an SQL UPDATE.

  ...

  It doesn’t matter if the item object is modified before or after it’s passed to
  update().

  ...

  Hibernate
  always treats the object as dirty and schedules an SQL UPDATE., which will be executed
  during flush.

On the other hand, merge() queries the database first, and doesn't perform update if state haven't changed.

So, if you want Hibernate to query the database first, you need to use merge() (though default behaviour of update() can be overriden by specifing @org.hibernate.annotations.Entity(selectBeforeUpdate = true) on your entities).

Body:
I have two entity beans defined as follows (unrelated stuff removed):

@Entity
@Table(...)
public class MasterItem implements java.io.Serializable {

  private Set<CriticalItems> criticalItemses = new HashSet<CriticalItems>(0);

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "masterItem", orphanRemoval = true,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public Set<CriticalItems> getCriticalItemses() {
        return this.criticalItemses;
    }
}

CriticalItems is defined as follows:

@Entity
@Table(...)
public class CriticalItems implements java.io.Serializable {

    private MasterItem masterItem;

    @ManyToOne(fetch = FetchType.LAZY, optional = false,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE})
    @JoinColumn(name = "mi_item_id", nullable = false)
    public MasterItem getMasterItem() {
        return this.masterItem;
    }
}

And in my DAO code - I have these methods:

public MasterItem load(int id) {
    MasterItem results = (MasterItem) getSessionFactory().getCurrentSession()
        .get("com.xxx.MasterItem", id);

}

public void save(MasterItem master) {
    // master has been changed by the UI since it
    getSessionFactory().getCurrentSession().saveOrUpdate(master);
}

When I load a MasterItem, it loads correctly, and also loads the CriticalItems Set with data, as directed.  Then, I send this data to my UI, and get an updated copy back, which I then try to persist.   The user updates fields in the MasterItem object, but does not touch the CriticalItems Set or anything in it - it remains unmodified.

When my save() method is invoked, Hibernate is insisting on sending SQL updates for each item in the Set of CriticalItems, even though none of them have changed in any way.

After some digging, here's what I think is happening.  When I do a saveOrUpdate(), Hibernate sees my MasterItem object is in a detached state, so it tries to reload it from disk.  However, when doing so, it appears to be using a prepared statement (which was auto-created by Hibernate at start-up) and this prepared statement does not attempt to join to the CriticalItems data.

So Hibernate has my updated MasterItem object with a full Set of CriticalItems, but uses a MasterItem without collections as its "previousState" object.  Thus, all CriticalItems get updated via SQL (not inserted, which is interesting in itself).

Did I do something in my annotations that caused this behavior?  I know I can use an Interceptor to find out of the item has really changed, or changed the dirty flag to override Hibernate's default algorithm - but this seems to be something that Hibernate should just handle on its own without my intervention.

Any insight would be appreciated.

UPDATE:
Based on comments, I think I understand the difference between saveOrUpdate() and merge().  I realize that saveOrUpdate() will result in either an SQL INSERT or an SQL UPDATE in all cases, and that merge, in theory, will only issue updates if the object has changed from it's persistent state, but in order to determine that, Hibernate has to reload the object first via SQL SELECT.

So, I thought I could just go back into my code and change saveOrUpdate() to merge() and it would work, but that wasn't quite the case.

When I used merge(), I was getting

org.springframework.orm.hibernate3.HibernateSystemException: could not initialize proxy - no Session; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session

but it worked fine if I changed back to saveOrUpdate().

I finally found out why - I didn't include CascadeType.MERGE in my @Cascade annotation (ugh).  Once I fixed that, the exception went away.

ContentLicense: CC BY-SA 2.5


问:
how bind correctly in react-native?
I'm try to update the state from a function, but I don't find the correct form to bind the scope. My code (I am working with native-base components):</p>
```<code>export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  _renderRow() {
    return (
      <ListItem avatar onPress={() =>
         ActionSheet.show(
           {options: BUTTONS
           }, buttonIndex => { setState({ clicked:  BUTTONS[buttonIndex]})}
         )}
       >
      </ListItem>
    );
  }

  render() {
    return (
         <SectionList
          sections={[...]}
          renderItem={this._renderRow}
        />
    );
  }
</code>```

答:
self mental note, "Bind is dummy if I not use the context of the function"</p>

```<code>export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    **this._renderRow = this._renderRow.bind(this);**
    }

  _renderRow() {
    return (
      <ListItem avatar onPress={() =>
         ActionSheet.show(
           {options: BUTTONS
           }, buttonIndex => { **this.**setState({ clicked:  BUTTONS[buttonIndex]})}
         )}
       >
      </ListItem>
    );
  }

  render() {
    return (
         <SectionList
          sections={[...]}
          renderItem={this._renderRow}
        />
    );
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: how bind correctly in react-native?

Body:
I'm try to update the state from a function, but I don't find the correct form to bind the scope. My code (I am working with native-base components):

export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  _renderRow() {
    return (
      <ListItem avatar onPress={() =>
         ActionSheet.show(
           {options: BUTTONS
           }, buttonIndex => { setState({ clicked:  BUTTONS[buttonIndex]})}
         )}
       >
      </ListItem>
    );
  }

  render() {
    return (
         <SectionList
          sections={[...]}
          renderItem={this._renderRow}
        />
    );
  }

Body:
self mental note, "Bind is dummy if I not use the context of the function"

export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    **this._renderRow = this._renderRow.bind(this);**
    }

  _renderRow() {
    return (
      <ListItem avatar onPress={() =>
         ActionSheet.show(
           {options: BUTTONS
           }, buttonIndex => { **this.**setState({ clicked:  BUTTONS[buttonIndex]})}
         )}
       >
      </ListItem>
    );
  }

  render() {
    return (
         <SectionList
          sections={[...]}
          renderItem={this._renderRow}
        />
    );
  }


问:
vb.net selectedindex.text empty while it's not
I have a form with combo boxes that show strings that were retrieved with a query from the database.

When I click on one of the combo boxes I invoke the ComboBox.Click event which goes out and does a query and shows all possible values one can choose from.

Here is were it starts acting strange. I put a statement in the code like:

```<code>Dim ac As ComboBox = DirectCast(sender, ComboBox)
MsgBox("selected text " & ac.SelectedText)
</code>```

This shows an empty messagebox, but when I put a breakpoint right after this code and check the contents it has a value.

And it is happening only on the first combobox on the form and only when i click in the combobox. If I click on the dropdown arrow it gives the correct string in the messagebox.
If I first click another combobox and then this combobox it works correct.

Anyway, what I am trying to do is that when a user clicks in the combobox the index that is shown does not change. What I noticed is that the selectedindex is always -1 on the first instance. So that's why I want to save the text value to look it up in the list of values and set the index to the correct position.

If anyone has a better alternative I am happy to hear it.

答: Never mind. I changed the combobox click event into a combobox gotfocus event instead. This seems to work for both clicking in the combobox and clicking on the combobox dropdown arrow.</p>

Body:
I have a form with combo boxes that show strings that were retrieved with a query from the database.

When I click on one of the combo boxes I invoke the ComboBox.Click event which goes out and does a query and shows all possible values one can choose from.

Here is were it starts acting strange. I put a statement in the code like:

Dim ac As ComboBox = DirectCast(sender, ComboBox)
MsgBox("selected text " & ac.SelectedText)

This shows an empty messagebox, but when I put a breakpoint right after this code and check the contents it has a value.

And it is happening only on the first combobox on the form and only when i click in the combobox. If I click on the dropdown arrow it gives the correct string in the messagebox.
If I first click another combobox and then this combobox it works correct.

Anyway, what I am trying to do is that when a user clicks in the combobox the index that is shown does not change. What I noticed is that the selectedindex is always -1 on the first instance. So that's why I want to save the text value to look it up in the list of values and set the index to the correct position.

If anyone has a better alternative I am happy to hear it.


问:
Map throw error on duplicate insertion
I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

```<code>Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
</code>```

Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality?

答:
Check containsKey method.

```<code>Map<Integer, String> map = new LinkedHashMap<>();

    map.put(1, "Value");
    if (map.containsKey(1)) {
        throw new Exception("Map already contains key 1");
    }
</code>```

For your question, you can create your own implementation like:

```<code>public class MyCustomMap extends HashMap {

        @Override
        public Object put(Object key, Object value) {
            if (this.containsKey(key)) {
                System.out.println("Do whatevery you want when key exists.");
                return null;
            } else {
                return super.put(key, value);
            }
        }
    }
</code>```

And then use it:

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

        Map<Integer, String> map = new MyCustomMap();

        map.put(1, "Value");

        map.put(1, "Another value");

    }
</code>```

Note: This is example, without null checking etc.

But please, always try to check JavaDoc or basic data structure use cases before asking here, I believe that on Google is a ton of examples ;)

Title: Map throw error on duplicate insertion

Body:
I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");

Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality?

Body:
Check containsKey method.

Map<Integer, String> map = new LinkedHashMap<>();

    map.put(1, "Value");
    if (map.containsKey(1)) {
        throw new Exception("Map already contains key 1");
    }

For your question, you can create your own implementation like:

public class MyCustomMap extends HashMap {

        @Override
        public Object put(Object key, Object value) {
            if (this.containsKey(key)) {
                System.out.println("Do whatevery you want when key exists.");
                return null;
            } else {
                return super.put(key, value);
            }
        }
    }

And then use it:

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

        Map<Integer, String> map = new MyCustomMap();

        map.put(1, "Value");

        map.put(1, "Another value");

    }

Note: This is example, without null checking etc.

But please, always try to check JavaDoc or basic data structure use cases before asking here, I believe that on Google is a ton of examples ;)


问:
How to estimate the size of JPEG image which will be scaled down
For example, I have an 1024*768 JPEG image. I want to estimate the size of the image which will be scaled down to 800*600 or 640*480. Is there any algorithm to calculate the size without generating the scaled image?

I took a look in the resize dialog in Photoshop. The size they show is basically (width pixels * height pixels * bit/pixel) which shows a huge gap between the actual file size.

I have mobile image browser application which allow user to send image through email with options to scale down the image. We provide check boxes for the user to choose down-scale resolution with the estimate size. For large image (> 10MB), we have 3 down scale size to choose from. If we generate a cached image for each option, it may hurt the memory. We are trying to find the best solution which avoid memory consumption.

答:
I have successfully estimated the scaled size based on the DQT - the quality factor.

I conducted some experiments and find out if we use the same quality factor as in the original JPEG image, the scaled image will have size roughly equal to (scale factor * scale factor) proportion of the original image size. The quality factor can be estimate based on the DQT defined in the every JPEG image. Algorithm has be defined to estimate the quality factor based on the standard quantization table shown in Annex K in JPEG spec.

Although other factors like color subsampling, different compression algorithm and the image itself will contribute to error, the estimation is pretty accurate.

P.S. By examining JPEGSnoop and it source code, it helps me a lot :-)

Cheers!


问:
error while running ionic ios build --prod --release
After installing Themeable browser plugin I am getting this error when I run :

```<code>ionic cordova build ios --prod --release
</code>```

I was able to build ios --prod --release without any error. Thanks :D

```<code>    Mac-Pro-de-chaker-2:cleantoufoulakids chakerkalai$ ionic cordova build ios --prod --realise
Running app-scripts build: --prod --platform ios --target cordova
[18:22:05]  build prod started ...
[18:22:07]  clean started ...
[18:22:07]  clean finished in 2 ms
[18:22:07]  copy started ...
[18:22:07]  ngc started ...
Error: Metadata version mismatch for module /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic-native/core/decorators.d.ts, found version 4, expected 3
    at StaticSymbolResolver.getModuleMetadata (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24474:34)
    at StaticSymbolResolver._createSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24260:46)
    at StaticSymbolResolver.getSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24241:14)
    at /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23023:30
    at Array.forEach (native)
    at extractProgramSymbols (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23022:79)
    at AotCompiler.compileAll (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:22720:47)
    at CodeGenerator.codegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/codegen.js:30:14)
    at Function.NgTools_InternalApi_NG_2.codeGen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/ngtools_api.js:61:30)
    at Object.doCodegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic/app-scripts/dist/aot/codegen.js:6:51)
[18:22:47]  copy finished in 40.10 s
</code>```

答:
I guess this is due to a ngc version mismatch, setting @angular/* to 5.0.1 should fix the issue:

```<code>"@angular/common": "5.0.1",
"@angular/compiler": "5.0.1",
"@angular/compiler-cli": "5.0.1",
"@angular/core": "5.0.1",
"@angular/forms": "5.0.1",
"@angular/http": "5.0.1",
"@angular/platform-browser": "5.0.1",
"@angular/platform-browser-dynamic": "5.0.1",
</code>```

Body:
After installing Themeable browser plugin I am getting this error when I run :

ionic cordova build ios --prod --release

I was able to build ios --prod --release without any error. Thanks :D

    Mac-Pro-de-chaker-2:cleantoufoulakids chakerkalai$ ionic cordova build ios --prod --realise
Running app-scripts build: --prod --platform ios --target cordova
[18:22:05]  build prod started ...
[18:22:07]  clean started ...
[18:22:07]  clean finished in 2 ms
[18:22:07]  copy started ...
[18:22:07]  ngc started ...
Error: Metadata version mismatch for module /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic-native/core/decorators.d.ts, found version 4, expected 3
    at StaticSymbolResolver.getModuleMetadata (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24474:34)
    at StaticSymbolResolver._createSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24260:46)
    at StaticSymbolResolver.getSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24241:14)
    at /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23023:30
    at Array.forEach (native)
    at extractProgramSymbols (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23022:79)
    at AotCompiler.compileAll (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:22720:47)
    at CodeGenerator.codegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/codegen.js:30:14)
    at Function.NgTools_InternalApi_NG_2.codeGen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/ngtools_api.js:61:30)
    at Object.doCodegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic/app-scripts/dist/aot/codegen.js:6:51)
[18:22:47]  copy finished in 40.10 s

Body:
I guess this is due to a ngc version mismatch, setting @angular/* to 5.0.1 should fix the issue:

"@angular/common": "5.0.1",
"@angular/compiler": "5.0.1",
"@angular/compiler-cli": "5.0.1",
"@angular/core": "5.0.1",
"@angular/forms": "5.0.1",
"@angular/http": "5.0.1",
"@angular/platform-browser": "5.0.1",
"@angular/platform-browser-dynamic": "5.0.1",


问:
"Not enough information to infer parameter T" with Kotlin and Android
I'm trying to replicate the following ListView in my Android app using Kotlin: https://github.com/bidrohi/KotlinListView.

Unfortunately I'm getting an error I'm unable to resolve myself.
Here's my code:

```<code>MainActivity.kt:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val listView = findViewById(R.id.list) as ListView
    listView.adapter = ListExampleAdapter(this)
}

private class ListExampleAdapter(context: Context) : BaseAdapter() {
    internal var sList = arrayOf("Eins", "Zwei", "Drei")
    private  val mInflator: LayoutInflater

    init {
        this.mInflator = LayoutInflater.from(context)
    }

    override fun getCount(): Int {
        return sList.size
    }

    override fun getItem(position: Int): Any {
        return sList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val vh: ListRowHolder

        if(convertView == null) {
            view = this.mInflator.inflate(R.layout.list_row, parent, false)
            vh = ListRowHolder(view)
            view.tag = vh
        } else {
            view = convertView
            vh = view.tag as ListRowHolder
        }

        vh.label.text = sList[position]
        return view
    }
}

private class ListRowHolder(row: View?) {
    public val label: TextView

    init {
        this.label = row?.findViewById(R.id.label) as TextView
    }
}
}
</code>```

The layouts are exactly as here: https://github.com/bidrohi/KotlinListView/tree/master/app/src/main/res/layout

The full error message I'm getting is this:
Error:(92, 31) Type inference failed: Not enough information to infer parameter T in fun  findViewById(p0: Int): T!
Please specify it explicitly.

I'd appreciate any help I can get.

答:
Its Working

API Level 25 or below use this

```<code>    var et_user_name = findViewById(R.id.et_user_name) as EditText
</code>```

API Level 26 or Above use this

```<code>    val et_user_name: EditText = findViewById(R.id.et_user_name)
</code>```

Happy Coding !

Body:
I'm trying to replicate the following ListView in my Android app using Kotlin: https://github.com/bidrohi/KotlinListView.

Unfortunately I'm getting an error I'm unable to resolve myself.
Here's my code:

MainActivity.kt:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val listView = findViewById(R.id.list) as ListView
    listView.adapter = ListExampleAdapter(this)
}

private class ListExampleAdapter(context: Context) : BaseAdapter() {
    internal var sList = arrayOf("Eins", "Zwei", "Drei")
    private  val mInflator: LayoutInflater

    init {
        this.mInflator = LayoutInflater.from(context)
    }

    override fun getCount(): Int {
        return sList.size
    }

    override fun getItem(position: Int): Any {
        return sList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val vh: ListRowHolder

        if(convertView == null) {
            view = this.mInflator.inflate(R.layout.list_row, parent, false)
            vh = ListRowHolder(view)
            view.tag = vh
        } else {
            view = convertView
            vh = view.tag as ListRowHolder
        }

        vh.label.text = sList[position]
        return view
    }
}

private class ListRowHolder(row: View?) {
    public val label: TextView

    init {
        this.label = row?.findViewById(R.id.label) as TextView
    }
}
}

The layouts are exactly as here: https://github.com/bidrohi/KotlinListView/tree/master/app/src/main/res/layout

The full error message I'm getting is this:
Error:(92, 31) Type inference failed: Not enough information to infer parameter T in fun  findViewById(p0: Int): T!
Please specify it explicitly.

I'd appreciate any help I can get.

Body:
Its Working

API Level 25 or below use this

    var et_user_name = findViewById(R.id.et_user_name) as EditText

API Level 26 or Above use this

    val et_user_name: EditText = findViewById(R.id.et_user_name)

Happy Coding !


问:
PHP/HTML - Same size of column containing columns
I need some help to be able to match the same size between the first column and the group of four other columns. Yet I tried with solution MatchHeight and row-eq-height. i tried also with a table. The main problem is that it brake the responsive tool.

I'm using bootstrap 3.3.6

Here is the sample I'm working with:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-6 bg-success">
      <div class="small-box">
        <div class="row">
          <div class="col-lg-12 col-xs-12">
            <h3>Colonne 1</h3>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices massa ligula, a faucibus nisi scelerisque sit amet. Sed cursus, urna eu suscipit egestas, dui dui luctus purus, malesuada pellentesque dolor dolor ac augue. Duis ac rutrum massa,
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xs-6 bg-warning">
      <div class="small-box">
        <div class="row">
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 2</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 3</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 4</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 5</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

One of the constraint is to have two rows on the right. I can't just make one unique row.

A real thank to who would like to help and to those who are able to.

答:
Yes, it's not an easy deal.

You can use "Flex-Box" (check that : https://codepen.io/imohkay/pen/gpard) if the "accessibility" of your projet can permit it (not good for IE9 etc. : https://caniuse.com/#search=flexbox). But I guess it's already what "row-eq-height" is doing...

Then, you can do it easily with jQuery.

Try something like :

```<code>var autoHeightResize = function (selector) {
    // Not on responsive
    if($(window).width() < 1024) return false;

    var maxheight = 0;
    var items = $(selector);
    // Whats is the max height ?
    for (var i = 0; i < items.length; i++) {
        maxheight = Math.max(maxheight, $(items[i]).height());
    }
    // Resize block with max-height
    items.height(maxheight);
}

$(document).ready(function () {
    // Init '#mypage .columns' auto-height resize
   var selectorAutoHeightBlocs = '#mypage .columns';
   autoHeightResize(selectorAutoHeightBlocs);
   // update columns height on resize page
   $(window).resize(function() {
        autoHeightResize(selectorAutoHeightBlocs);
   });
});
</code>```

In your case, you should give a same class name to your div "col-xs-6 bg-success" and "col-xs-6 bg-warning" (ex: class="my-same-height-column" ).

And then, use it in 'selectorAutoHeightBlocs' in the code above.

Body:
I need some help to be able to match the same size between the first column and the group of four other columns. Yet I tried with solution MatchHeight and row-eq-height. i tried also with a table. The main problem is that it brake the responsive tool.

I'm using bootstrap 3.3.6

Here is the sample I'm working with:

Colonne 1

              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices massa ligula, a faucibus nisi scelerisque sit amet. Sed cursus, urna eu suscipit egestas, dui dui luctus purus, malesuada pellentesque dolor dolor ac augue. Duis ac rutrum massa,

Colonne 2

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 3

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 4

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 5

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

One of the constraint is to have two rows on the right. I can't just make one unique row.

A real thank to who would like to help and to those who are able to.

Body:
Yes, it's not an easy deal.

You can use "Flex-Box" (check that : https://codepen.io/imohkay/pen/gpard) if the "accessibility" of your projet can permit it (not good for IE9 etc. : https://caniuse.com/#search=flexbox). But I guess it's already what "row-eq-height" is doing...

Then, you can do it easily with jQuery.

Try something like :

var autoHeightResize = function (selector) {
    // Not on responsive
    if($(window).width() < 1024) return false;

    var maxheight = 0;
    var items = $(selector);
    // Whats is the max height ?
    for (var i = 0; i < items.length; i++) {
        maxheight = Math.max(maxheight, $(items[i]).height());
    }
    // Resize block with max-height
    items.height(maxheight);
}

$(document).ready(function () {
    // Init '#mypage .columns' auto-height resize
   var selectorAutoHeightBlocs = '#mypage .columns';
   autoHeightResize(selectorAutoHeightBlocs);
   // update columns height on resize page
   $(window).resize(function() {
        autoHeightResize(selectorAutoHeightBlocs);
   });
});

In your case, you should give a same class name to your div "col-xs-6 bg-success" and "col-xs-6 bg-warning" (ex: class="my-same-height-column" ).

And then, use it in 'selectorAutoHeightBlocs' in the code above.


问:
javascript if else statement with timer
I have an 'if else' statement that works. But I'd like to add another condition to it. The statement is below:

```<code>function showDateContent(){
 var d=new Date();
  if(d.getDate()>=11&& d.getMonth()+1 == 11){
   //show something
 }else{
   //show something else
    }
  }

showDateContent();
</code>```

The conditional statement that I am trying to write is like this (below), but it doesn't seem to work. Notice I am trying to get something to happen when the date is between two numbers in the 1st statement, and then I have two more conditional statements similar to my first example.

```<code>function showDateContent(){
 var d=new Date();
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   //show something when the date is between 11 and 13
} else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   //show something when the date is equal or past the date of the 14th
  }else{
   //show something else when the date is before the 11th
    }
  }
}

showDateContent();
</code>```

答:
try using console.log() to print date and month which your browser is having and then use if and else statements based on it..

because here in India it is 13-11-2017 and you haven't handled anything for date = 13 so it is going in last else part when I am trying your code which is

```<code>function showDateContent(){
 var d=new Date();
console.log(d.getDate(), d.getMonth());   // prints 13   10
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   console.log("show something when the date is between 11 and 13");
  } else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   console.log("show something when the date is equal or past the date of the 14th");
  } else {
   console.log("how something else when the date is before the 11th");
   }
}

showDateContent();
</code>```

but when I do d.getDate()<= 13  so it goes in given if which is in below code

```<code>if(d.getDate()> 11 && d.getDate()<= 13 && d.getMonth()+1 == 11){
 console.log("show something when the date is between 11 and 13");
}
</code>```

also there was an extra "}" bracket in last of your code which wasn't required.

Title: javascript if else statement with timer

Body:
I have an 'if else' statement that works. But I'd like to add another condition to it. The statement is below:

function showDateContent(){
 var d=new Date();
  if(d.getDate()>=11&& d.getMonth()+1 == 11){
   //show something
 }else{
   //show something else
    }
  }

showDateContent();

The conditional statement that I am trying to write is like this (below), but it doesn't seem to work. Notice I am trying to get something to happen when the date is between two numbers in the 1st statement, and then I have two more conditional statements similar to my first example.

function showDateContent(){
 var d=new Date();
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   //show something when the date is between 11 and 13
} else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   //show something when the date is equal or past the date of the 14th
  }else{
   //show something else when the date is before the 11th
    }
  }
}

showDateContent();

Body:
try using console.log() to print date and month which your browser is having and then use if and else statements based on it..

because here in India it is 13-11-2017 and you haven't handled anything for date = 13 so it is going in last else part when I am trying your code which is

function showDateContent(){
 var d=new Date();
console.log(d.getDate(), d.getMonth());   // prints 13   10
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   console.log("show something when the date is between 11 and 13");
  } else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   console.log("show something when the date is equal or past the date of the 14th");
  } else {
   console.log("how something else when the date is before the 11th");
   }
}

showDateContent();

but when I do d.getDate()<= 13  so it goes in given if which is in below code

if(d.getDate()> 11 && d.getDate()<= 13 && d.getMonth()+1 == 11){
 console.log("show something when the date is between 11 and 13");
}

also there was an extra "}" bracket in last of your code which wasn't required.


问:
How to get index of Escape Character in a String?
How to get index of Escape Character  in a String?

```<code>String test="1234\567890";
System.out.println("Result : "+test.lastIndexOf("\\"));
</code>```

Result i get:
  -1

Result i need: 4

答:
Your original String doesn't contain \. Which means you are searching something which does not exist. Inorder to add \ to your string. You have to escape while adding

```<code>String test="1234\\567890";
System.out.println("Result : "+test.lastIndexOf("\\"));
</code>```

Should work.

In your case look at the last line in the table.

Body:
How to get index of Escape Character  in a String?

String test="1234\567890";
System.out.println("Result : "+test.lastIndexOf("\\"));

Result i get:
  -1

Result i need: 4

Body:
Your original String doesn't contain \. Which means you are searching something which does not exist. Inorder to add \ to your string. You have to escape while adding

String test="1234\\567890";
System.out.println("Result : "+test.lastIndexOf("\\"));

Should work.

In your case look at the last line in the table.


问:
Add the time variable to a filter (Swift)
I'm working with google places API and in the VC where I want to show the nearby places, I created a filter for the places I'm going to download

```<code>if response.status == "OK" {
                if let placesDownloaded = response.places {
                    var number = numberPlaces / (categories?.count)!
                    number = number == 0 ? 1 : number

                    let firstPlace = placesDownloaded.prefix(1)

                    var isRestaurant = false

                    for place in firstPlace {
                        for type in place.types! {
                            if (type.lowercased() == "restaurant") {
                                isRestaurant = true
                            }
                        }
                    }
                        if(isRestaurant) {
                                number = 1
                            }

                            places.append(contentsOf: placesDownloaded.prefix(number))
                        }
</code>```

Now I would like to add the "time" variable to this filter (for example if (type.lowercased() == "restaurant" && the time on user position is 12.00 o'clock){} etc.) but I really don't know how can I do, can someone make me an example of how can I add the time var and use it in this filter?

答:
You can achieve it by using NSDateformatter as given below,</p>

```<code>let dateFormatter = NSDateFormatter()
dateFormatter.timezone = TimeZone.current
dateFormatter.dateFormat = "hh:mm"
print(dateFormatter.stringFromDate(NSDate()))
</code>```

Body:
I'm working with google places API and in the VC where I want to show the nearby places, I created a filter for the places I'm going to download

if response.status == "OK" {
                if let placesDownloaded = response.places {
                    var number = numberPlaces / (categories?.count)!
                    number = number == 0 ? 1 : number

                    let firstPlace = placesDownloaded.prefix(1)

                    var isRestaurant = false

                    for place in firstPlace {
                        for type in place.types! {
                            if (type.lowercased() == "restaurant") {
                                isRestaurant = true
                            }
                        }
                    }
                        if(isRestaurant) {
                                number = 1
                            }

                            places.append(contentsOf: placesDownloaded.prefix(number))
                        }

Now I would like to add the "time" variable to this filter (for example if (type.lowercased() == "restaurant" && the time on user position is 12.00 o'clock){} etc.) but I really don't know how can I do, can someone make me an example of how can I add the time var and use it in this filter?

Body:
You can achieve it by using NSDateformatter as given below,

let dateFormatter = NSDateFormatter()
dateFormatter.timezone = TimeZone.current
dateFormatter.dateFormat = "hh:mm"
print(dateFormatter.stringFromDate(NSDate()))


问:
Can I restrict a protocol to one type of class?
I am writing some transitioning protocols, and I would like them to only be available to UIView classes:

```<code>public protocol TransitioningView where Self: UIView
{
    func transitionDelay(pushFrom: UIView?) -> TimeInterval?
    func transitionDuration(popTo: UIView?) -> TimeInterval
    func transitionDuration(pushFrom: UIView?) -> TimeInterval
    func animateTransition(popTo: UIView?   , finished: ((Bool) -> Void)?)
    func animateTransition(pushFrom: UIView?, finished: ((Bool) -> Void)?)
}
</code>```

But this doesn't seem quite right. The compiler does not consider a UIView that has been cast to a TransitioningView as being a UIView.

example:

```<code>let x = myController.view as? TransitioningView
x.animateTransition(popTo: nil, finished: nil) // OK
x.backgroundColor = .clear // NOPE
</code>```

This is a bit annoying because sometimes I want to pass around a view that I have confirmed to be a TransitioningView. Is there a better pattern?

答:
In your example, public protocol TransitioningView where Self: UIView, you are defining that the TransitioningView requires an inheritance from UIView, but i can't see any implementation of TransitioningView into UIView.

I'll give you two examples on how you can do this.

First you can create a default implementation of the protocol:

```<code>extension TransitioningView {

    public func transitionDelay(pushFrom: UIView?) -> TimeInterval? {
        return 1
    }

    public func transitionDuration(popTo: UIView?) -> TimeInterval {
        return 1
    }

    public func transitionDuration(pushFrom: UIView?) -> TimeInterval {
        return 1
    }

    public func animateTransition(popTo: UIView?, finished: ((Bool) -> Void)?) {

    }

    public func animateTransition(pushFrom: UIView?, finished: ((Bool) -> Void)?) {

    }
}
</code>```

This example will make every object that inherits from UIView conform to TransitioningView, this might be a over-kill depending on how much you utilize the TransitioningView functionality:

```<code>extension UIView: TransitioningView {}
</code>```

The last example will implement TransitioningView directly in the custom class:

```<code>class MyCustomView: UIView, TransitioningView {}
class MyCustomLabel: UILabel, TransitioningView {}
</code>```

Independent of how you implement it they both use the same default implementation in the extension TransitioningView. This behavior can be "overridden" in the either an extension or in the class itself.

```<code>extension TransitioningView where Self: UITextField {

    public func animateTransition(pushFrom: UIView?, finished: ((Bool) -> Void)?) {
        // Some custom transition
    }
}
</code>```

or

```<code>class MyCustomView: UIView, TransitioningView {

    func transitionDuration(popTo: UIView?) -> TimeInterval {
        return 2
    }
}
</code>```

For further reference:

Extensions - The Swift Programming Language (Swift 4)

Protocols - The Swift Programming Language (Swift 4)

Body:
I am writing some transitioning protocols, and I would like them to only be available to UIView classes:

public protocol TransitioningView where Self: UIView
{
    func transitionDelay(pushFrom: UIView?) -> TimeInterval?
    func transitionDuration(popTo: UIView?) -> TimeInterval
    func transitionDuration(pushFrom: UIView?) -> TimeInterval
    func animateTransition(popTo: UIView?   , finished: ((Bool) -> Void)?)
    func animateTransition(pushFrom: UIView?, finished: ((Bool) -> Void)?)
}

But this doesn't seem quite right. The compiler does not consider a UIView that has been cast to a TransitioningView as being a UIView.

example:

let x = myController.view as? TransitioningView
x.animateTransition(popTo: nil, finished: nil) // OK
x.backgroundColor = .clear // NOPE

This is a bit annoying because sometimes I want to pass around a view that I have confirmed to be a TransitioningView. Is there a better pattern?

Body:
In your example, public protocol TransitioningView where Self: UIView, you are defining that the TransitioningView requires an inheritance from UIView, but i can't see any implementation of TransitioningView into UIView.

I'll give you two examples on how you can do this.

First you can create a default implementation of the protocol:

extension TransitioningView {

    public func transitionDelay(pushFrom: UIView?) -> TimeInterval? {
        return 1
    }

    public func transitionDuration(popTo: UIView?) -> TimeInterval {
        return 1
    }

    public func transitionDuration(pushFrom: UIView?) -> TimeInterval {
        return 1
    }

    public func animateTransition(popTo: UIView?, finished: ((Bool) -> Void)?) {

    }

    public func animateTransition(pushFrom: UIView?, finished: ((Bool) -> Void)?) {

    }
}

This example will make every object that inherits from UIView conform to TransitioningView, this might be a over-kill depending on how much you utilize the TransitioningView functionality:

extension UIView: TransitioningView {}

The last example will implement TransitioningView directly in the custom class:

class MyCustomView: UIView, TransitioningView {}
class MyCustomLabel: UILabel, TransitioningView {}

Independent of how you implement it they both use the same default implementation in the extension TransitioningView. This behavior can be "overridden" in the either an extension or in the class itself.

extension TransitioningView where Self: UITextField {

    public func animateTransition(pushFrom: UIView?, finished: ((Bool) -> Void)?) {
        // Some custom transition
    }
}

or

class MyCustomView: UIView, TransitioningView {

    func transitionDuration(popTo: UIView?) -> TimeInterval {
        return 2
    }
}

For further reference:

Extensions - The Swift Programming Language (Swift 4)

Protocols - The Swift Programming Language (Swift 4)


问:
keras backend theano/tensorflow
I have an issue using keras backend. I set up tensorflow as the backend. I check the ./keras/keras.json, the activate.d and activate.sh to have tensorflow as backend. I also tried to force the envs variable to tensorflow.

The first time a run keras on the jupyter, it works fine. I can also import tensorflow without any bugs.

However when I use jupyter notebook now, the backend is theano.

I try to import keras on ipython and the backend is tensorflow.

I install keras, tensorflow and theano with conda.

python version : 3.6

keras : 2.0.6

tensorflow : 1.3.0

theano : 0.9

OS : win10

I try different ways to change the backend to tensorflow for jupyter notebook but it does not seem to work.

答:
Usually, with conda, we create specific environments that are (theoretically) independent from the others.

I suggest you create a tensorflow environment using conda. Using the command prompt:

```<code>conda create -n myTensorflowEnv python=3.5
</code>```

And then you activate this environment:

```<code>activate myTensorflowEnv
</code>```

The name of your environment should then appear in between parentheses at the beginning of the command prompt. (In case this doesn't work, you may need to setup some vars: How to activate an Anaconda environment)

Inside this environment, you install everything you need: Tensorflow, keras and other dependencies. This process will depend on what you want, though, cpu, gpu, compilations, etc.

You should probably install jupyter in this environment as well. (And perhaps -- only if you have the terrible bug I mentioned in my comment -- uninstall the other jupyters first).

If everything goes well, you will be able to use tensorflow in this environment if you run jupyter from this environment.

Title: keras backend theano/tensorflow

Body:
Usually, with conda, we create specific environments that are (theoretically) independent from the others.

I suggest you create a tensorflow environment using conda. Using the command prompt:

conda create -n myTensorflowEnv python=3.5

And then you activate this environment:

activate myTensorflowEnv

The name of your environment should then appear in between parentheses at the beginning of the command prompt. (In case this doesn't work, you may need to setup some vars: How to activate an Anaconda environment)

Inside this environment, you install everything you need: Tensorflow, keras and other dependencies. This process will depend on what you want, though, cpu, gpu, compilations, etc.

You should probably install jupyter in this environment as well. (And perhaps -- only if you have the terrible bug I mentioned in my comment -- uninstall the other jupyters first).

If everything goes well, you will be able to use tensorflow in this environment if you run jupyter from this environment.


问:
Javascript Submit only working with id
So i have this problem. This form has a date type input that goes to another php function that i didn't posted because it works fine, there's only one thing that doesn't work. You can see dateform is an id so when i choose a date it only goes throw all the process with the first row (it's inside a while loop). I know the problem, dateform has to be class but if i change id for class it doesn't work.

The following code is the one it works (only in first row). I changed it for $(".dateform") and class="dateform" but still.

Javascript

```<code><script type="text/javascript">
    $(".dateinput").change(function(){
        console.log("Submiting form");
        $("#dateform").submit();
    });
</script>
</code>```

html

```<code><form id="dateform" action="' . date($connection) . '" method="POST">
    <input type="hidden" name="order" value="' . $row['order'] . '">
    <input type="hidden" name="a_date" value="' . $a['id'] . '">
    <input class="dateinput" type="date" name="rDate" value="' . $row['r_view'] . '">
    </form>
</code>```

答:
You can't use a global selector to find the form associated with the specific input you are dealing with.

"Search the document for the element with the (unique) id blah" will always give you the same result.

If you did change the id to a class, then you would get all the forms and you still wouldn't know which one was relevant.

You need to start from something associated with the event (i.e. this … the select element which triggered the event) and then find a relationship from it to the element you are trying to find.

In this case you are looking for the form associated with the form control, and there is a standard property for that.

```<code>$(this.form).submit();
</code>```

Title: Javascript Submit only working with id

Body:
So i have this problem. This form has a date type input that goes to another php function that i didn't posted because it works fine, there's only one thing that doesn't work. You can see dateform is an id so when i choose a date it only goes throw all the process with the first row (it's inside a while loop). I know the problem, dateform has to be class but if i change id for class it doesn't work.

The following code is the one it works (only in first row). I changed it for $(".dateform") and class="dateform" but still.

Javascript

html

<form id="dateform" action="' . date($connection) . '" method="POST">
    <input type="hidden" name="order" value="' . $row['order'] . '">
    <input type="hidden" name="a_date" value="' . $a['id'] . '">
    <input class="dateinput" type="date" name="rDate" value="' . $row['r_view'] . '">
    </form>

Body:
You can't use a global selector to find the form associated with the specific input you are dealing with.

"Search the document for the element with the (unique) id blah" will always give you the same result.

If you did change the id to a class, then you would get all the forms and you still wouldn't know which one was relevant.

You need to start from something associated with the event (i.e. this … the select element which triggered the event) and then find a relationship from it to the element you are trying to find.

In this case you are looking for the form associated with the form control, and there is a standard property for that.

$(this.form).submit();


问:
Line contains null byte error while reading csv file
I have tried reading a csv file using the following format of code.

```<code>def csv_dict_reader(file_obj):
    reader = csv.reader(file_obj, delimiter=',')
    for row in reader:
        # some operation

file = open("data.csv", "r")
csv_dict_reader(file)
</code>```

I have referred the solutions given here, but none of them seem to work. What could be the most probable reason for this.

The error:

```<code>    for row in reader:
_csv.Error: line contains NULL byte
</code>```

答:
The file contains one or more NULL bytes which is not compatible with the CSV reader. As a workaround, you could read the file a line at time and if a NULL byte is detected, replace it will a space character. The resulting line could then by parsed by a CSV reader by converting the resulting string into a file like object. Note, the delimiter by default is , so it does not need to be specified. By adding enumerate(), you could then display which lines in your file contain the NULL bytes.

As you are using a DictReader(), an extra step is needed to first extract the header from your file using a normal csv.reader(). This row can be used to manually specify the fieldnames parameter to your DictReader.

```<code>import csv
import StringIO

with open('data.csv', 'rb') as f_input:
    # Use a normal CSV reader to get the header line
    header = next(csv.reader(f_input))

    for line_number, raw_line in enumerate(f_input, start=1):
        if '\x00' in raw_line:
            print "Line {} - NULL found".format(line_number)
            raw_line = raw_line.replace('\x00', ' ')

        row = next(csv.DictReader(StringIO.StringIO(raw_line), fieldnames=header))
        print row
</code>```

Lastly, when using a csv.reader(), you should open the file in binary mode e.g. rb.

Body:
I have tried reading a csv file using the following format of code.

def csv_dict_reader(file_obj):
    reader = csv.reader(file_obj, delimiter=',')
    for row in reader:
        # some operation

file = open("data.csv", "r")
csv_dict_reader(file)

I have referred the solutions given here, but none of them seem to work. What could be the most probable reason for this.

The error:

    for row in reader:
_csv.Error: line contains NULL byte

Body:
The file contains one or more NULL bytes which is not compatible with the CSV reader. As a workaround, you could read the file a line at time and if a NULL byte is detected, replace it will a space character. The resulting line could then by parsed by a CSV reader by converting the resulting string into a file like object. Note, the delimiter by default is , so it does not need to be specified. By adding enumerate(), you could then display which lines in your file contain the NULL bytes.

As you are using a DictReader(), an extra step is needed to first extract the header from your file using a normal csv.reader(). This row can be used to manually specify the fieldnames parameter to your DictReader.

import csv
import StringIO

with open('data.csv', 'rb') as f_input:
    # Use a normal CSV reader to get the header line
    header = next(csv.reader(f_input))

    for line_number, raw_line in enumerate(f_input, start=1):
        if '\x00' in raw_line:
            print "Line {} - NULL found".format(line_number)
            raw_line = raw_line.replace('\x00', ' ')

        row = next(csv.DictReader(StringIO.StringIO(raw_line), fieldnames=header))
        print row

Lastly, when using a csv.reader(), you should open the file in binary mode e.g. rb.


问:
Maintain proportion of a sprite in Unity
I added a sprite with a PNG image to a 16:9 scene in Unity. When I view the scene on the iPad (4:3 aspect ratio) it appears distorted. How can I make the sprite maintain it's proportion?

The image on the iPad:

On the computer (in Unity):

Here are my settings.

I tried using this script for the camera but it didn't work it just enlarges the character and it was still distorted. (source):

using UnityEngine;

public class PixelPerfectCamera : MonoBehaviour {

    public float pixelsToUnits = 100;
    private Camera camera;

    void Awake () {
        camera = Camera.main;
    }

    void Update () {
        camera.orthographicSize = Screen.height / pixelsToUnits / 2;
    }
}
```

I am using the sprite in a 2D scene using Unity 5.

答: You can use preserve aspect option of the image.

Body:
I added a sprite with a PNG image to a 16:9 scene in Unity. When I view the scene on the iPad (4:3 aspect ratio) it appears distorted. How can I make the sprite maintain it's proportion?

The image on the iPad:

On the computer (in Unity):

Here are my settings.

I tried using this script for the camera but it didn't work it just enlarges the character and it was still distorted. (source):

using UnityEngine;

public class PixelPerfectCamera : MonoBehaviour {

    public float pixelsToUnits = 100;
    private Camera camera;

    void Awake () {
        camera = Camera.main;
    }

    void Update () {
        camera.orthographicSize = Screen.height / pixelsToUnits / 2;
    }
}

I am using the sprite in a 2D scene using Unity 5.


问:
Add images into string? Translate word into image
I want to create a program that let you input a sentence such as:
I am happy.
And outputs: I am  (happy emoji, in my case an image I've created myself).

So far I am able to replace happy by another word but I need to replace it with an image.
Can I add images to a string?
If so, how?

UPDATE: My code finally works, this is the html and javascript I've used:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>
     <style>
      .inline-img {
          height: 40px;
        }
    </style>
     </head>
      <body>
        <font size="+3" face="Helvetica">
       <p id="output"></p>
     </font>
         <script>
         document.addEventListener('DOMContentLoaded', function() {
         function word_replace(replacements, str) {
           var result = str;
            for (var [x, url] of replacements) {
             result = result.replace(x, '<img src="' + url + '" alt="emoji" class="inline-img" />');
                    }
          return result;
          }
            var input = prompt('Input your sentence');
            var output = word_replace([

            [/(happy)/ig, 'https://c1.staticflickr.com/5/4521/38517798662_418a72e9d9_b.jpg'],
            [/(sad|depressed)/ig, 'https://c1.staticflickr.com/5/4553/38517797352_6c8fba1a3d_o.png'],
            [/(confused)/ig, "https://c1.staticflickr.com/5/4519/37833334134_109952bda2_b.jpg"],
            [/(afraid)/ig, 'https://c1.staticflickr.com/5/4516/37833334324_c43f01a30d_b.jpg'],
            [/(angry)/ig, 'https://c1.staticflickr.com/5/4532/26773555349_63894fa4be_b.jpg'],
            [/(determined)/ig, 'https://c1.staticflickr.com/5/4537/37833333874_ff92cb8647_b.jpg'],
            [/(love)/ig, 'https://c1.staticflickr.com/5/4530/37833331724_8a90312ddb_b.jpg'],
            [/(indifferent)/ig, 'https://c1.staticflickr.com/5/4543/37833333744_59da46444d_b.jpg']

          ], input);

          var outputElement = document.getElementById("output");
          outputElement.innerHTML = output;
      });

    </script>
  </body>
</html>
</code>```

答:
How about using https://afeld.github.io/emoji-css/

Code example:

function mreplace(replacements, str) {
  for (let [x, y] of replacements) {
    str = str.replace(x, s => `<i class="em em-${y}"></i>`);
  }
  return str;
}
let output = document.querySelector('#output');
let input = 'I want to be always happy, but never confused!';
let result = mreplace([
  [/happy/ig, 'blush'],
  [/confused/ig, "confused"]
], input);

output.innerHTML = result;
console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

<p id="output"></p></code>```

Body:
I want to create a program that let you input a sentence such as:
I am happy.
And outputs: I am  (happy emoji, in my case an image I've created myself).

So far I am able to replace happy by another word but I need to replace it with an image.
Can I add images to a string?
If so, how?

UPDATE: My code finally works, this is the html and javascript I've used:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>

Body:
How about using https://afeld.github.io/emoji-css/

Code example:

function mreplace(replacements, str) {
  for (let [x, y] of replacements) {
    str = str.replace(x, s => `<i class="em em-${y}"></i>`);
  }
  return str;
}
let output = document.querySelector('#output');
let input = 'I want to be always happy, but never confused!';
let result = mreplace([
  [/happy/ig, 'blush'],
  [/confused/ig, "confused"]
], input);

output.innerHTML = result;
console.log(result);

<link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

<p id="output"></p>