问:
Is it permissible in this case to compare invalid iterators?
Actually it never bothered me because the code compiles and runs without errors. But after reading the documentation for a while, I came across one paragraph (quote below). And so I decided to ask knowledgeable people.

Class member declaration:

```<code>QHash<QTcpSocket*, QTime> clients;
</code>```

The signal disconnected of each socket is connected to the lambda slot:

```<code>QObject::connect(socket, &QTcpSocket::disconnected,
    [this, socket]()
    {
      socket->disconnect();
      socket->deleteLater();

      this->clients.remove(socket); // <--- Removing
    });
</code>```

Checking the "sleeping" clients:

```<code>void check_timeouts()
{
  for (auto it = this->clients.cbegin(), end = this->clients.cend();
       !this->clients.empty();
       it = this->clients.cbegin(), end = this->clients.cend())
  {
    while (it != end)
    {
      if (it.value().elapsed() > this->client_timeout
          && it.key()->state() == QTcpSocket::ConnectedState)
      {
        it.key()->disconnectFromHost(); // <--- Emit disconnected inside
        break;
      }
      ++it;
    }
    if (it == end) // <--- Comparing
    {
      break;
    }
  }
}
</code>```

As you can see, if the client "sleeps" long enough it is disconnected by calling the disconnectFromHost() of the socket, which in turn entails the execution of the lambda body where the client is removed from the table. And at the time of comparison the iterators it and end are considered invalid.

From Qt documentation:

The Iterator Classes

Iterators provide a uniform means to access items in a container. Qt's
  container classes provide two types of iterators: Java-style iterators
  and STL-style iterators. Iterators of both types are invalidated when
  the data in the container is modified or detached from implicitly
  shared copies due to a call to a non-const member function.

But in this case does not attempt to access the data of the container. And given that immediately before calling the function disconnectFromHost the iterators it and end are definitely not equal, and immediately after the call they are compared, and since they are not equal and they are immediately reset to the correct values in for's iteration_expression.

So my question, is it possible to conditionally assume that specifically in this comparison the iterators are not invalid but, let's say are correct-but-outdated and this comparison is correct and not UB?

P.S. There is one thing that really confuses me. This is that the iterator comparison operation is an overload. It may happen that for some containers it turns out that the comparison of the iterators was implemented with access to the container relying on the data of these iterators. And then there will be problems. But these are only my guesses. Since, as I know, the usual iterators operate with pointers and they do not need access to the container (in theory).

P.P.S. Sorry for my english. It's not me, but online translators. ;-)

EDIT:

So, I found a similar question with the answer that completely suits me.
But I still want to accept the answer for a workaround that seems acceptable to me.

答:
No. It is clearly undefined behavior. The container has been modified while you hold an iterator. The iterator is invalidated by the modification and you can't use it anymore.

The workaround is simple: remove the object from the hash after you're done iterating. It's also not necessary to disconnect a socket before destroying it, and in any case it already is disconnected, since you're connecting to its disconnected signal! And for safety's sake, you should connect to this's object context if this points to a QObject:

```<code>QObject::connect(socket, &QTcpSocket::disconnected, this, [this, socket]{
  socket->deleteLater();
  connect(socket, &QObject::destroyed, this, [this, socket]{
    clients.remove(socket);
  });
});
</code>```

Otherwise, the class pointing to this must keep an object context:

```<code>class MyClass {
  QHash<QTcpSocket*, QTime> clients;
  QObject context; // must be declared after clients
  ...
  void do() {
    QObject::connect(socket, &QTcpSocket::disconnected, &context, [obj = &context, socket, this]{
      socket->deleteLater();
      connect(socket, &QObject::destroyed, obj, [socket, this]{
        clients.remove(socket);
      });
    });
  }
};
</code>```

This is to ensure that the connection will be automatically broken if MyClass outlives the socket, and you won't attempt to access this when it's a dangling pointer. The context acts as a sentinel whose existence guarantees that access to this->clients is allowed.

Body:
Actually it never bothered me because the code compiles and runs without errors. But after reading the documentation for a while, I came across one paragraph (quote below). And so I decided to ask knowledgeable people.

Class member declaration:

QHash<QTcpSocket*, QTime> clients;

The signal disconnected of each socket is connected to the lambda slot:

QObject::connect(socket, &QTcpSocket::disconnected,
    [this, socket]()
    {
      socket->disconnect();
      socket->deleteLater();

      this->clients.remove(socket); // <--- Removing
    });

Checking the "sleeping" clients:

void check_timeouts()
{
  for (auto it = this->clients.cbegin(), end = this->clients.cend();
       !this->clients.empty();
       it = this->clients.cbegin(), end = this->clients.cend())
  {
    while (it != end)
    {
      if (it.value().elapsed() > this->client_timeout
          && it.key()->state() == QTcpSocket::ConnectedState)
      {
        it.key()->disconnectFromHost(); // <--- Emit disconnected inside
        break;
      }
      ++it;
    }
    if (it == end) // <--- Comparing
    {
      break;
    }
  }
}

As you can see, if the client "sleeps" long enough it is disconnected by calling the disconnectFromHost() of the socket, which in turn entails the execution of the lambda body where the client is removed from the table. And at the time of comparison the iterators it and end are considered invalid.

From Qt documentation:

The Iterator Classes

Iterators provide a uniform means to access items in a container. Qt's
  container classes provide two types of iterators: Java-style iterators
  and STL-style iterators. Iterators of both types are invalidated when
  the data in the container is modified or detached from implicitly
  shared copies due to a call to a non-const member function.

But in this case does not attempt to access the data of the container. And given that immediately before calling the function disconnectFromHost the iterators it and end are definitely not equal, and immediately after the call they are compared, and since they are not equal and they are immediately reset to the correct values in for's iteration_expression.

So my question, is it possible to conditionally assume that specifically in this comparison the iterators are not invalid but, let's say are correct-but-outdated and this comparison is correct and not UB?

P.S. There is one thing that really confuses me. This is that the iterator comparison operation is an overload. It may happen that for some containers it turns out that the comparison of the iterators was implemented with access to the container relying on the data of these iterators. And then there will be problems. But these are only my guesses. Since, as I know, the usual iterators operate with pointers and they do not need access to the container (in theory).

P.P.S. Sorry for my english. It's not me, but online translators. ;-)

EDIT:

So, I found a similar question with the answer that completely suits me.
But I still want to accept the answer for a workaround that seems acceptable to me.

Body:
No. It is clearly undefined behavior. The container has been modified while you hold an iterator. The iterator is invalidated by the modification and you can't use it anymore.

The workaround is simple: remove the object from the hash after you're done iterating. It's also not necessary to disconnect a socket before destroying it, and in any case it already is disconnected, since you're connecting to its disconnected signal! And for safety's sake, you should connect to this's object context if this points to a QObject:

QObject::connect(socket, &QTcpSocket::disconnected, this, [this, socket]{
  socket->deleteLater();
  connect(socket, &QObject::destroyed, this, [this, socket]{
    clients.remove(socket);
  });
});

Otherwise, the class pointing to this must keep an object context:

class MyClass {
  QHash<QTcpSocket*, QTime> clients;
  QObject context; // must be declared after clients
  ...
  void do() {
    QObject::connect(socket, &QTcpSocket::disconnected, &context, [obj = &context, socket, this]{
      socket->deleteLater();
      connect(socket, &QObject::destroyed, obj, [socket, this]{
        clients.remove(socket);
      });
    });
  }
};

This is to ensure that the connection will be automatically broken if MyClass outlives the socket, and you won't attempt to access this when it's a dangling pointer. The context acts as a sentinel whose existence guarantees that access to this->clients is allowed.


来源: stackexchange

问:
Creating a grid of squares (patches) in matplotlib
I'm trying to generate a grid of squares with a small offset between each and thought I would use my superior matplotlib skills. Unfortunately the output only shows one square, so I suspect that the matplotlib isn't getting the message to plot all the patch objects I am initializing, but despite much trawling of stackoverflow I cannot fix this issue.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.collections as coll

wid = 1
hei = 1
nrows = 5
ncols = 7
inbetween = 0.1

xx = np.arange(0, ncols, (wid+inbetween))
yy = np.arange(0, nrows, (hei+inbetween))

fig = plt.figure()
ax = plt.subplot(111, aspect='equal')

pat = []
for xi in xx:
    for yi in yy:
        sq = patches.Rectangle((xi, yi), wid, hei, fill=True)
        ax.add_patch(sq)

pc = coll.PatchCollection(pat)
ax.add_collection(pc)

plt.axis('off')
plt.show()
plt.savefig('test.png', dpi=90)
</code>```

Any ideas as to what is going wrong?

答:
There are two issues here. First, you only see (part of) one patch here, because the axes go from 0 to 1 and not up to ncols and nrows.

This can be counteracted by relimiting the axes

```<code>ax.relim()
ax.autoscale_view()
</code>```

or by setting the limis manually, e.g. ax.axis([0,ncols+1,0,nrows+1]).

Second, the PatchCollection is not doing anything, because an empty list (pat=[]) is added to it. Either delete the two lines

```<code>pc = coll.PatchCollection(pat)
ax.add_collection(pc)
</code>```

or replace  ax.add_patch(sq) by pat.append(sq). Note that relim() does not work when using the PatchCollection and manually relimitting the axes would be required.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to generate a grid of squares with a small offset between each and thought I would use my superior matplotlib skills. Unfortunately the output only shows one square, so I suspect that the matplotlib isn't getting the message to plot all the patch objects I am initializing, but despite much trawling of stackoverflow I cannot fix this issue.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.collections as coll

wid = 1
hei = 1
nrows = 5
ncols = 7
inbetween = 0.1

xx = np.arange(0, ncols, (wid+inbetween))
yy = np.arange(0, nrows, (hei+inbetween))

fig = plt.figure()
ax = plt.subplot(111, aspect='equal')

pat = []
for xi in xx:
    for yi in yy:
        sq = patches.Rectangle((xi, yi), wid, hei, fill=True)
        ax.add_patch(sq)

pc = coll.PatchCollection(pat)
ax.add_collection(pc)

plt.axis('off')
plt.show()
plt.savefig('test.png', dpi=90)

Any ideas as to what is going wrong?

Body:
There are two issues here. First, you only see (part of) one patch here, because the axes go from 0 to 1 and not up to ncols and nrows.

This can be counteracted by relimiting the axes

ax.relim()
ax.autoscale_view()

or by setting the limis manually, e.g. ax.axis([0,ncols+1,0,nrows+1]).

Second, the PatchCollection is not doing anything, because an empty list (pat=[]) is added to it. Either delete the two lines

pc = coll.PatchCollection(pat)
ax.add_collection(pc)

or replace  ax.add_patch(sq) by pat.append(sq). Note that relim() does not work when using the PatchCollection and manually relimitting the axes would be required.


问:
Typescript force Check property in object when treated as associative array
Better explain with example let's say I have :

```<code>class Model{
    property1: number;
    property2: number;
}

let model= new Model;
</code>```

When I do

model["property1"]="sdaef"  // Good ! typescript checks and know it should be number and give error

var test = model.nonExistingProp // throws error since the property does not exist which is good

Now the problem

```<code>    var test = model["nonExistingProp"]; // NO ERRORS ??
</code>```

I'm wondering since it is smart enough to know the properties from strings (associative array) and their types why does not throw error like previous example and say nonExistingProp, is there a way to force this kind of type checking on associative array since it already knows the properties and did the check for the type like first example ??

Thanks

答:
TypeScript is smart enough, but this is a legacy feature for when indexing into an object was used as a form of getting around the type-checker.

However, if you use --noImplicitAny (in addition to the other --strict flags), you'll get safer checking and TypeScript will give an error on that expression.

For the record, flags the team has placed under the --strict flag are things that the team believes will give you a much better experience in editing & error checking.

Body:
Better explain with example let's say I have :

class Model{
    property1: number;
    property2: number;
}

let model= new Model;

When I do

model["property1"]="sdaef"  // Good ! typescript checks and know it should be number and give error

var test = model.nonExistingProp // throws error since the property does not exist which is good

Now the problem

    var test = model["nonExistingProp"]; // NO ERRORS ??

I'm wondering since it is smart enough to know the properties from strings (associative array) and their types why does not throw error like previous example and say nonExistingProp, is there a way to force this kind of type checking on associative array since it already knows the properties and did the check for the type like first example ??

Thanks


问:
ruby-on-rails - Problem with Nested Resources
I have a Problem with Nested Resources.

2 Models

```<code>User => has_many :stuffs

Stuff => belongs_to :user
</code>```

routes.rb

```<code>map.resources :stuffs

map.resources :users, :has_many => [:stuffs]
</code>```

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

```<code>MySQL Query from Server
SELECT * FROM `stuffs`
</code>```

rake routes

```<code>stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}
</code>```

gem list

```<code>actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)
</code>```

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

答:
Rails controllers will not filter your results by default. As above, since you're probably calling Stuff.all in your StuffsController, it will always return all Stuff objects.

I use inherited_resources for the default behaviour on my sites. It handles these relationships automatically and lets you override it when you want different behaviour:

https://github.com/josevalim/inherited_resources

ContentLicense: CC BY-SA 2.5

Body:
I have a Problem with Nested Resources.

2 Models

User => has_many :stuffs

Stuff => belongs_to :user

routes.rb

map.resources :stuffs

map.resources :users, :has_many => [:stuffs]

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

MySQL Query from Server
SELECT * FROM `stuffs`

rake routes

stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}

gem list

actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help


问:
Spring boot logback not logging to file
I am using the spring-boot-start-web dependency in my web mvc application and making use of logback. I have a logback-spring.xml file located in my static resources directory with the following config

```<code><property name="MY_LOG_FILE" value="C:\mylog.log" />

<appender name="MY_APPENDER"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <file>${MY_LOG_FILE}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>${MY_LOG_FILE}.%i</fileNamePattern>
    </rollingPolicy>
    <triggeringPolicy
        class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <MaxFileSize>10MB</MaxFileSize>
    </triggeringPolicy>
</code>```

```<code><logger name="com.mydomain.myapp" level="INFO" additivity="false">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="MY_APPENDER" />
</logger>
</code>```

When I use the logger in my controllers it correctly logs to the console output, but the file is nowhere to be found. As far as what I can find online it looks like i'm setting it up correctly, but obviously I am not.

EDIT: It ended up being resolved by performing a Maven Update Project on the parent project, this project was part of a larger system of modules.

答:
Put the  logback-spring.xml in your resources directory,not static directory.

Build your project with maven,then Check if your target/classes directory has the logback-spring.xml

By default,If you put a logback.xml in the root of your classpath it will be picked up from there (or logback-spring.xml to take advantage of the templating features provided by Boot)

Title: Spring boot logback not logging to file

Body:
I am using the spring-boot-start-web dependency in my web mvc application and making use of logback. I have a logback-spring.xml file located in my static resources directory with the following config

<property name="MY_LOG_FILE" value="C:\mylog.log" />

<appender name="MY_APPENDER"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <file>${MY_LOG_FILE}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>${MY_LOG_FILE}.%i</fileNamePattern>
    </rollingPolicy>
    <triggeringPolicy
        class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <MaxFileSize>10MB</MaxFileSize>
    </triggeringPolicy>

<logger name="com.mydomain.myapp" level="INFO" additivity="false">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="MY_APPENDER" />
</logger>

When I use the logger in my controllers it correctly logs to the console output, but the file is nowhere to be found. As far as what I can find online it looks like i'm setting it up correctly, but obviously I am not.

EDIT: It ended up being resolved by performing a Maven Update Project on the parent project, this project was part of a larger system of modules.


问:
ICU init failed: U_FILE_ACCESS_ERROR - when running swirl
I Keep getting this error whenever I library(swirl):

Error in inDL(x, as.logical(local), as.logical(now), ...) :    ICU
  init failed: U_FILE_ACCESS_ERROR Error: package or namespace load
  failed for ‘swirl’

I have reinstalled multiple versions of R multiple times.

Reinstalled RTools multiple times

Reset path and registry to what they were a week before when swirl was still working

Reinstalled Visual Studio and R Studio and still the same effect

Would be awesome to know what more I can do to eliminate this error. I am getting this error in all R environments (R Interactive, Visual Studio, R Studio); It was working properly till a week ago (not sure why it is not working now)

答: When I had this issue, loading the Plyr R package resolved it for me.</p>


问:
Encrypt using Triple DES in C#, decrypt in perl
I am trying to encrypt a string of text in C# using triple des. The text eventually needs to be decrypted using perl. The text coming out the other end still looks like gobblygyk. Am I missing a flag on the cipher?

C# encrypt:

```<code>    public static string EncryptString(string str)
    {
        using (var provider = new TripleDESCryptoServiceProvider())
        {
            provider.Mode = CipherMode.CBC;

            provider.Key = Encoding.ASCII.GetBytes("THISIS24BYTESWORTHOFTEXT");
            provider.IV = Encoding.ASCII.GetBytes("01234567");
            provider.Padding = PaddingMode.PKCS7;

            var hashBytes = EncryptStringToBytes(str, provider);

            return Convert.ToBase64String(hashBytes);
        }
    }

    private static byte[] EncryptStringToBytes(string txt, TripleDESCryptoServiceProvider desAlg)
    {

        var encryptor = desAlg.CreateEncryptor(desAlg.Key, desAlg.IV);

        using (var msEncrypt = new MemoryStream())
        {
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(txt);
                }
            }
            return msEncrypt.ToArray();
        }
    }
}
</code>```

perl decrypt:

```<code>sub DecryptString {
my ($dbh, $args) = @_;

my $inargs = $args->{INPUT};
my $key="THISIS24BYTESWORTHOFTEXT";
my $iv = "01234567";

my $cipher = Crypt::CBC->new(
        -cipher => 'DES_EDE3',
        -key => $key,
        -literal_key => 1,
        -iv => $iv,
        -add_header => 0,
        -keysize => 24,
);

return $cipher->decrypt($inargs);
}
</code>```

答:
Needed to decode before decrypting. As per the comment below, I changed the call to

$inargs = decode_base64($inargs);

right before call to decrypt.

Body:
I am trying to encrypt a string of text in C# using triple des. The text eventually needs to be decrypted using perl. The text coming out the other end still looks like gobblygyk. Am I missing a flag on the cipher?

C# encrypt:

    public static string EncryptString(string str)
    {
        using (var provider = new TripleDESCryptoServiceProvider())
        {
            provider.Mode = CipherMode.CBC;

            provider.Key = Encoding.ASCII.GetBytes("THISIS24BYTESWORTHOFTEXT");
            provider.IV = Encoding.ASCII.GetBytes("01234567");
            provider.Padding = PaddingMode.PKCS7;

            var hashBytes = EncryptStringToBytes(str, provider);

            return Convert.ToBase64String(hashBytes);
        }
    }

    private static byte[] EncryptStringToBytes(string txt, TripleDESCryptoServiceProvider desAlg)
    {

        var encryptor = desAlg.CreateEncryptor(desAlg.Key, desAlg.IV);

        using (var msEncrypt = new MemoryStream())
        {
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(txt);
                }
            }
            return msEncrypt.ToArray();
        }
    }
}

perl decrypt:

sub DecryptString {
my ($dbh, $args) = @_;

my $inargs = $args->{INPUT};
my $key="THISIS24BYTESWORTHOFTEXT";
my $iv = "01234567";

my $cipher = Crypt::CBC->new(
        -cipher => 'DES_EDE3',
        -key => $key,
        -literal_key => 1,
        -iv => $iv,
        -add_header => 0,
        -keysize => 24,
);

return $cipher->decrypt($inargs);
}


问:
How to optimize this Javascript code for a Paint App?
I'm working on a Paint App using Processing.js. Basically, when the mouse is dragged, mouseX and mouseY are saved in an array of objects called data[]. Afterwards the paint() function will run a loop that accesses every object of the data[] array and draws a line of color(data[i].R,data[i].G,data[i].B) and thickness data[i].T between the corresponding data[i].mouseX and data[i].mouseY coordinates. The problem is that the array keeps getting bigger the more you draw and in my case, when the length of the data[] array reaches ~800 elements it will start to lag, and keeps getting worse the more I keep drawing. Is there any tweak that will fix the lag or do I have to completely rethink the program?

<!DOCTYPE HTML>

        <canvas id="targetcanvas"width="649" height="600" " style="border: 3px solid black; margin-top=100px;"></canvas>

```

答:
Is this Processing.js or P5.js? Either way, the answer is the same.

You basically have a spectrum of options:

No data structures, no undo: Instead of storing your shapes and whatnot in data structures, just draw them directly to the canvas whenever the user does something. You can use a PGraphics canvas, or you can just draw directly to the screen, if you get rid of the call to background(). Then you don't need any data structures. The downside of this is you won't be able to remove shapes once they're drawn.

Some data structures, some undo: If you needed to be able to undo some of the shapes, but not all of them, you could do a mix of the above approach and your current approach. Instead of storing everything in data structures, you would only store the last 1-10 or so shapes. The rest of the shapes would be drawn directly to the PGraphics buffer.

Lots of data structure, lots of undo: If you really needed to be able to undo all of the shapes, then you could still use the PGraphics approach, but only redraw all of the shapes when something was removed.


问:
Direct child selection in jQuery

$(document).ready(function () {
    $("#one > li").text("fruits");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="one">
        <li>Apple</li>
        <li>
            <ul id="two">
                <li>Mango</li>
                <li>Grapes</li>
            </ul>
        </li>
        <li id="kela">Banana</li>
        <li class="sanatara">Orange</li>
    </ul></code>```

When I run this javascript on the above HTML then the output changes all the list items to "fruits" including the ones with id="two". Since direct selector (>) should only select the direct child of ul element with id="one" then why is this happening?

答:
Actually, the selector you're using is telling "Pick ALL the li that are direct children of element with #one id".

If yout want to change the text of the first item only you can use the ":first-child" pseudo-class.

```<code>$("#one > li:first-child").text("My Text");
</code>```

Take a look to this page for more info on css pseudo-classes.

Title: Direct child selection in jQuery

Body:
$(document).ready(function () {
    $("#one > li").text("fruits");
})

Apple

Mango

Grapes

Banana

Orange

When I run this javascript on the above HTML then the output changes all the list items to "fruits" including the ones with id="two". Since direct selector (>) should only select the direct child of ul element with id="one" then why is this happening?

Body:
Actually, the selector you're using is telling "Pick ALL the li that are direct children of element with #one id".

If yout want to change the text of the first item only you can use the ":first-child" pseudo-class.

$("#one > li:first-child").text("My Text");

Take a look to this page for more info on css pseudo-classes.


问:
Linux Users adding to Directory
I have to create a shared folder under a directory, after that I have to create 2 users with their equally named home directories. It is required that the user can use the sudo command and both users should be able to edit each other's documents in the shared folder.

Can someone help me out with this? or give me the code, I tried adding users to the directory and stuff but I am stuck and also don't really understand the full exercise.

thank you

答:
Creating the shared directory and common group

```<code>$ sudo mkdir -p /var/test
$ sudo groupadd test
</code>```

Add the two user to the group

```<code>$ sudo usermod -a -G test user1
$ sudo usermod -a -G test user2
</code>```

Set the permission to directory

```<code>$ sudo chgrp -R project /var/test/
$ sudo chmod -R 2775 /var/test/
</code>```

Title: Linux Users adding to Directory

Body:
Creating the shared directory and common group

$ sudo mkdir -p /var/test
$ sudo groupadd test

Add the two user to the group

$ sudo usermod -a -G test user1
$ sudo usermod -a -G test user2

Set the permission to directory

$ sudo chgrp -R project /var/test/
$ sudo chmod -R 2775 /var/test/


问:
Spring Data Neo4j 4 limitations?
I am evaluating if I should use Spring Data Neo4j 4 or directly use the native APIs that Neo4j has. Is it possible to get the full potential of Neo4j when using Spring Data Neo4j 4 or will it limit my future usage of Neo4j?

I see the benefit with that POJO simplifies the storage of objects in the database.

答:
The recently updated content on https://graphaware.com/spring-data-neo4j may provide you with additional information to consider.

In my view, yes, SDN allows you to make use of the full potential of Neo4j. That said, for use cases where needed you can also sidestep SDN and make direct use of the underlying OGM and/or Cypher directly. In other words, when making use of SDN you also have the freedom and flexibility to use alternate options of what best suits your needs, so your usage does not need to be an "all SDN" or "no SDN" approach; you can mix and match as needed.

Title: Spring Data Neo4j 4 limitations?


问:
paintComponent not being called at the right time
I'm trying to write an app that goes something like this:

- Display a dialog

- When user clicks OK, close dialog, go to main app

Here are the relevant code snippets:

```<code>public class Owari extends JPanel implements ActionListener, MouseListener, Runnable {

// FIELDS
JFrame frame;
JTextField IP;
String IPAddress;

static final int SERVER_MODE = 0;
static final int CLIENT_MODE = 1;
int mode;

OwariBoard board;

  public static void main( String[] args ) {
    SwingUtilities.invokeLater( new Owari() );
  }

  Owari() {
    setPreferredSize( new Dimension( WIDTH, HEIGHT ) );
    board = new OwariBoard();
  }

  void main() {
    this.addMouseListener( this );
    frame.dispose();
    frame = new JFrame( "Owari" );
    frame.setContentPane( this );
    frame.pack();
    frame.setVisible(true);
    if ( mode == SERVER_MODE ) {
      server();
    }
    if ( mode == CLIENT_MODE ) {
      client();
    }
  }

  public void run() {
    frame = new JFrame( "Owari" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    JPanel init = new JPanel( new GridBagLayout() );
    frame.setContentPane( init );

    add some components to the init panel including a button with
    this as its actionListener and OK as its command.
    frame.pack();
    frame.setVisible( true );
  }

  public void actionPerformed( ActionEvent e ) {
    if ( e.getActionCommand().equals( "Client" ) ) {
      mode = CLIENT_MODE;
      IP.setVisible( true );
    }
    else if ( e.getActionCommand().equals( "Server" ) ) {
      mode = SERVER_MODE;
      IP.setVisible( false );
    }
    else {
      IPAddress = IP.getText();
      main();
    }
  }

  public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    System.out.println( "painting" );
    do some paintin
  }

  void server() {
    frame.setTitle( "Owari Server" );
    try {
    server = new ServerSocket( 666 );
    socket = server.accept();
    initIO();
    } catch ( IOException e ) {}
    yourTurn = true;
    System.out.println( "Got to end of server()" ); // At this point, the window
                                                       DOES get painted
</code>```

What happens is the following:

The initial dialog displays:

I click the OK button.
The main window gets resized to the preferred size of the main app but it doesn't get painted, it's just transparent (shown here with this page as the background, heh):

http://imgur.com/6Ssij.jpg

I can tell the paintComponent method hasn't been called because "painting" isn't printed to the console.
However, "got to this point in the program" DOES get printed, so the program isn't hanging, it's just not calling paintComponent.
Then when I launch a client and connect, the app finally gets painted, and "painting" and "got a client" get printed to the console.
Also later on in the app, calls to repaint() are delayed (ie paintComponent is actually called later in the program than when the call to repaint() is made).

I also tried replacing the initial dialog using sthing along the lines of

```<code>public void main
  frame.getRootPane.removeAll()
  frame.setContentPane(this)
  frame.getRootPane().revalidate()
  frame.pack()
</code>```

Exact same result.

tl;dr paintcomponent isn't being called when i want it to, what do?

Bumping for some more info: the call to repaint() is done before the call to sever.accept() So why does it not repaint() before hanging at the server.accept() call?

答:
your code seems to work so, maybe you should try to invoke the repaint() methode of you frame after resizing this frame.

Anhuin

Body:
I'm trying to write an app that goes something like this:

- Display a dialog

- When user clicks OK, close dialog, go to main app

Here are the relevant code snippets:

public class Owari extends JPanel implements ActionListener, MouseListener, Runnable {

// FIELDS
JFrame frame;
JTextField IP;
String IPAddress;

static final int SERVER_MODE = 0;
static final int CLIENT_MODE = 1;
int mode;

OwariBoard board;

  public static void main( String[] args ) {
    SwingUtilities.invokeLater( new Owari() );
  }

  Owari() {
    setPreferredSize( new Dimension( WIDTH, HEIGHT ) );
    board = new OwariBoard();
  }

  void main() {
    this.addMouseListener( this );
    frame.dispose();
    frame = new JFrame( "Owari" );
    frame.setContentPane( this );
    frame.pack();
    frame.setVisible(true);
    if ( mode == SERVER_MODE ) {
      server();
    }
    if ( mode == CLIENT_MODE ) {
      client();
    }
  }

  public void run() {
    frame = new JFrame( "Owari" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    JPanel init = new JPanel( new GridBagLayout() );
    frame.setContentPane( init );

    add some components to the init panel including a button with
    this as its actionListener and OK as its command.
    frame.pack();
    frame.setVisible( true );
  }

  public void actionPerformed( ActionEvent e ) {
    if ( e.getActionCommand().equals( "Client" ) ) {
      mode = CLIENT_MODE;
      IP.setVisible( true );
    }
    else if ( e.getActionCommand().equals( "Server" ) ) {
      mode = SERVER_MODE;
      IP.setVisible( false );
    }
    else {
      IPAddress = IP.getText();
      main();
    }
  }

  public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    System.out.println( "painting" );
    do some paintin
  }

  void server() {
    frame.setTitle( "Owari Server" );
    try {
    server = new ServerSocket( 666 );
    socket = server.accept();
    initIO();
    } catch ( IOException e ) {}
    yourTurn = true;
    System.out.println( "Got to end of server()" ); // At this point, the window
                                                       DOES get painted

What happens is the following:

The initial dialog displays:

I click the OK button.
The main window gets resized to the preferred size of the main app but it doesn't get painted, it's just transparent (shown here with this page as the background, heh):

http://imgur.com/6Ssij.jpg

I can tell the paintComponent method hasn't been called because "painting" isn't printed to the console.
However, "got to this point in the program" DOES get printed, so the program isn't hanging, it's just not calling paintComponent.
Then when I launch a client and connect, the app finally gets painted, and "painting" and "got a client" get printed to the console.
Also later on in the app, calls to repaint() are delayed (ie paintComponent is actually called later in the program than when the call to repaint() is made).

I also tried replacing the initial dialog using sthing along the lines of

public void main
  frame.getRootPane.removeAll()
  frame.setContentPane(this)
  frame.getRootPane().revalidate()
  frame.pack()

Exact same result.

tl;dr paintcomponent isn't being called when i want it to, what do?

Bumping for some more info: the call to repaint() is done before the call to sever.accept() So why does it not repaint() before hanging at the server.accept() call?


问:
Try/try catch function in R
How can i use the try/try catch function in R to proceed to next loop and do sys.sleep for 60 seconds if the trycatch/try function returns an error. ANy help would be appreciated, thanks.</p>

答:
try this :</p>

```<code>for (x in list(1,2,"a",4,5)){
  print(x)
  y <- try( x+1) # maybe you want try(x+1,silent=TRUE)
  if(inherits(y, "try-error")) Sys.sleep(5)
}
</code>```

Title: Try/try catch function in R

Body:
try this :

for (x in list(1,2,"a",4,5)){
  print(x)
  y <- try( x+1) # maybe you want try(x+1,silent=TRUE)
  if(inherits(y, "try-error")) Sys.sleep(5)
}


问:
Why does Double.TryParse() return false for a string containing double.MaxValue or double.MinValue?
I have static method that takes a string for input and returns the original input string if the string represents a number.  If the string does not represent a number the the input string is processed and a transformed string is returned.  I'm writing test cases.  I'm trying to verify that an input string containing either double.MinValue or double.MaxValue is returned unchanged.  I've read through a number of forums, including StackOverflow, and have come up with the following logic:

```<code>string doubleMax = double.MaxValue.ToString();
double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d))
{
    Console.WriteLine("parsed");
}
else
{
    Console.WriteLine("couldn't parse");
}
</code>```

Problem is the Double.TryParse() always returns false.  I've called TryParse() in a bunch of different ways, but the result is always the same, false.

This logic works if I use decimal.MinValue(), int.MinValue(), or float.MinValue().

Can someone tell me why my logic isn't working for double.MinValue?

答:
There's nothing wrong with your logic, it's just a limitation i the Double.TryParse API.  From the documentation

Ordinarily, if you pass the Double.TryParse method a string that is created by calling the Double.ToString method, the original Double value is returned. However, because of a loss of precision, the values may not be equal. In addition, attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the following example illustrates.

The documentation appears to be taken from the Parse method and applied to TryParse since TryParse does not throw.  But the sample code following the pargraph uses TryParse and expects it to fail for MaxValue and MinValue

Body:
I have static method that takes a string for input and returns the original input string if the string represents a number.  If the string does not represent a number the the input string is processed and a transformed string is returned.  I'm writing test cases.  I'm trying to verify that an input string containing either double.MinValue or double.MaxValue is returned unchanged.  I've read through a number of forums, including StackOverflow, and have come up with the following logic:

string doubleMax = double.MaxValue.ToString();
double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d))
{
    Console.WriteLine("parsed");
}
else
{
    Console.WriteLine("couldn't parse");
}

Problem is the Double.TryParse() always returns false.  I've called TryParse() in a bunch of different ways, but the result is always the same, false.

This logic works if I use decimal.MinValue(), int.MinValue(), or float.MinValue().

Can someone tell me why my logic isn't working for double.MinValue?


问:
MS Excel how to create a macro to find duplicates and highlight them?
How can I create a macro in MS excel to find duplicates in a spreadsheet and highlight it</p>

答:
Ross Larson answered this question here: Finding duplicate rows in excel

Quoting from his answer, "The absolute fastest and easiest way. Conditional formatting, highlight duplicates (on the ID column). Then filter the column (presumably in a table) by the coloring (above the check boxes)."

Yesterday, I personally tried this out and it worked great. No need to write a macro or fancy VBA script. Just use the Excel out-of-the-box functionality.

The answer Paul Rayner gave in 2010 has a broken link. The Ross Larson link is still working - at least for now.


问:
Where to place line of code in html for ReactDOM.render?
I have the following code which is in a saved format of .html (index.html).

I am learning React right now and when I execute this html file in the browser, nothing happens.

I am wondering where the two lines of code are suppose to go or how to call them (execute the rendering).

Where would I find the files in ./lib if I am using a mac?

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Introduction | Learning React</title>
    <link rel="stylesheet" href="lib/style.css" />
  </head>
  <body>
    <section id="entry-point"></section>

    <!-- Wifi might be spotty, so we've downloaded these to `./lib` -->
    <script src="lib/react.js"></script>
    <script src="lib/react-dom.js"></script>

    <script type="text/javascript">
      // Intentionally blank. Your walk-through code will go here
      var hello = React.createElement('p', null, 'Hello, World!');

      // Checkout what this does by opening your HTML file in the browser
      ReactDOM.render(hello, document.getElementById('entry-point'));
    </script>
  </body>
</html>
</code>```

答:
It works as long as you include the proper libraries:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Introduction | Learning React</title>
    <link rel="stylesheet" href="lib/style.css" />

```
</div>
</div>
</p>

<p>Using the correct setup (JSX compiler, e.g. Babel), you could simplify the above <code>createElement</code> to:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>ReactDOM.render(
  <p>Hello, World!</p>,
  document.getElementById('entry-point')
);</code>```

```

Body:
I have the following code which is in a saved format of .html (index.html).

I am learning React right now and when I execute this html file in the browser, nothing happens.

I am wondering where the two lines of code are suppose to go or how to call them (execute the rendering).

Where would I find the files in ./lib if I am using a mac?

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Introduction | Learning React</title>
    <link rel="stylesheet" href="lib/style.css" />

Body:
It works as long as you include the proper libraries:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Introduction | Learning React</title>
    <link rel="stylesheet" href="lib/style.css" />
  </head>
  <body>
    <section id="entry-point"></section>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    <script type="text/javascript">
      // Intentionally blank. Your walk-through code will go here
      var hello = React.createElement('p', null, 'Hello, World!');

      // Checkout what this does by opening your HTML file in the browser
      ReactDOM.render(hello, document.getElementById('entry-point'));
    </script>
  </body>
</html>

Using the correct setup (JSX compiler, e.g. Babel), you could simplify the above createElement to:

ReactDOM.render(
  <p>Hello, World!</p>,
  document.getElementById('entry-point')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="entry-point"></div>


问:
Not able to get transparent QRubberband
I am trying to draw a rectangle using QRubberBand. I need the rectangle border to be opaque and its inside to be transparent. But, I am able to do it only other way around, with the border to be transparent and its filling in opaque. Here is the code I am using,

```<code>class roiFrame : public QRubberBand
{
public:
    roiFrame(Shape s, QWidget * p = 0):QRubberBand(s, p){}
    ~roiFrame(){}

protected:
    void paintEvent(QPaintEvent *pe)
    {
        Q_UNUSED(pe);

        QStyleOptionRubberBand opt;
        QStylePainter painter(this);
        painter.setOpacity(0.8); // from aamer4yu
        opt.initFrom(this);
        //  opt.opcatiy = false; //This one also makes the border to be transparent .
        painter.drawControl(QStyle::CE_FocusFrame, opt);
    }
};
</code>```

As an alternative, I tried to draw a rectangle using QPainter::drawRect:

```<code>myWindow::myWindow(QWidget *parent): QFrame(parent)
{
    ui.setupUi(this);
}

myWindow::~myWindow()
{
}

void myWindow::mouseReleaseEvent(QMouseEvent * event)
{
    releaseX = event->x();
    releaseY = event->y();
}

void myWindow::mousePressEvent(QMouseEvent * event)
{
    pressX = event->x();
    pressY = event->y();
}

void myWindow::paintEvent(QPaintEvent *event)
{
    QFrame::paintEvent(event);
    QRectF rectangle(pressX,pressY,releaseX,releaseY);
    QPainter painter(this);
    painter.setOpacity(0.8);
    painter.drawRect(rectangle);
    painter.end();
}
</code>```

答:
The problem with drawRect is that you do not specify how the rectangle should look like, i.e. the properties of the border and its inside:

You can specify the border style using QPainter::setPen (or one of its overloads)

You can specify how the rectangle is filled using QPainter::setBrush (or one of its overloads)

In your case, only the border should be drawn. So, you should use something like this:

```<code>painter.setPen(Qt::red);
</code>```

Remarks

Note that it may be necessary to call QWidget::update to force a repaint event.

Note that the third and fourth constructor parameter of QRectF are the width and height and not the bottom right coordinates. As an alternative, you may use the following constructor overload: QRectF rectangle(QPointF(pressX,pressY),QPointF(releaseX,releaseY));

Title: Not able to get transparent QRubberband

Body:
I am trying to draw a rectangle using QRubberBand. I need the rectangle border to be opaque and its inside to be transparent. But, I am able to do it only other way around, with the border to be transparent and its filling in opaque. Here is the code I am using,

class roiFrame : public QRubberBand
{
public:
    roiFrame(Shape s, QWidget * p = 0):QRubberBand(s, p){}
    ~roiFrame(){}

protected:
    void paintEvent(QPaintEvent *pe)
    {
        Q_UNUSED(pe);

        QStyleOptionRubberBand opt;
        QStylePainter painter(this);
        painter.setOpacity(0.8); // from aamer4yu
        opt.initFrom(this);
        //  opt.opcatiy = false; //This one also makes the border to be transparent .
        painter.drawControl(QStyle::CE_FocusFrame, opt);
    }
};

As an alternative, I tried to draw a rectangle using QPainter::drawRect:

myWindow::myWindow(QWidget *parent): QFrame(parent)
{
    ui.setupUi(this);
}

myWindow::~myWindow()
{
}

void myWindow::mouseReleaseEvent(QMouseEvent * event)
{
    releaseX = event->x();
    releaseY = event->y();
}

void myWindow::mousePressEvent(QMouseEvent * event)
{
    pressX = event->x();
    pressY = event->y();
}

void myWindow::paintEvent(QPaintEvent *event)
{
    QFrame::paintEvent(event);
    QRectF rectangle(pressX,pressY,releaseX,releaseY);
    QPainter painter(this);
    painter.setOpacity(0.8);
    painter.drawRect(rectangle);
    painter.end();
}

Body:
The problem with drawRect is that you do not specify how the rectangle should look like, i.e. the properties of the border and its inside:

You can specify the border style using QPainter::setPen (or one of its overloads)

You can specify how the rectangle is filled using QPainter::setBrush (or one of its overloads)

In your case, only the border should be drawn. So, you should use something like this:

painter.setPen(Qt::red);

Remarks

Note that it may be necessary to call QWidget::update to force a repaint event.

Note that the third and fourth constructor parameter of QRectF are the width and height and not the bottom right coordinates. As an alternative, you may use the following constructor overload: QRectF rectangle(QPointF(pressX,pressY),QPointF(releaseX,releaseY));


问:
what is the proper way to publish a React component module in NPM without external dependencies inside?
I'm trying to publish in NPM a component library made with React.

I don't want that it have external dependencies, even React modules, to have smallest possible file size and because the user will add this dependencies in the app.

I'm using npm and webpack to manage the dependencies.

This is my package.json dependencies:

```<code>"devDependencies": {
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1",
    "webpack-merge": "^0.13.0",
    "babel-core": "^6.9.1",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-hmre": "^1.1.1",
    "react": "^15.0.2",
    "react-dom": "^15.0.2"
  },
 "peerDependencies": {
   "react": "^15.0.2",
   "react-dom": "^15.0.2"
 }
</code>```

In my webpack.config.js file I have entry point as 'component.jsx' and output as 'lib.js' file

```<code>// Source code entry
entry: {
  lib: './src/components/component.jsx'
},

// Code Output
output: {
  path: PATHS.build,
  filename: 'lib.js'
},
</code>```

I also included the "externals" attribute with the react modules to avoid webpack including it in the 'lib.js' output.

```<code>externals: {
  'react': 'React',
  'react-dom' : 'ReactDOM'
}
</code>```

Finally this is the simple React component that i want to publish:

```<code>import React from 'react';

export default class Component extends React.Component {

  constructor() {
    super();
  }

  render() {
    return (
      <h1>MY COMPONENT</h1>
    );
  }
}
</code>```

I published it to NPM and installed it in another project. When I tried to use it after import React statement, it gives me an error saying that React is not defined (bundle.js:28448 Uncaught ReferenceError: React is not defined)

My code to probe the component:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Component from 'component';
import $ from 'jquery';

ReactDOM.render(
   <Component />,
   $("#app")
);
</code>```

Am I missing anything in the dependencies config?

Thanks

答:
I wrote a full Medium story because I had the same issue as you and there is no information about it.
Check it out: https://medium.com/@BrodaNoel/how-to-create-a-react-component-and-publish-it-in-npm-668ad7d363ce

The main fix is to add the external 'react': 'commonjs react' in the webpack.config.js file

Body:
I'm trying to publish in NPM a component library made with React.

I don't want that it have external dependencies, even React modules, to have smallest possible file size and because the user will add this dependencies in the app.

I'm using npm and webpack to manage the dependencies.

This is my package.json dependencies:

"devDependencies": {
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1",
    "webpack-merge": "^0.13.0",
    "babel-core": "^6.9.1",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-hmre": "^1.1.1",
    "react": "^15.0.2",
    "react-dom": "^15.0.2"
  },
 "peerDependencies": {
   "react": "^15.0.2",
   "react-dom": "^15.0.2"
 }

In my webpack.config.js file I have entry point as 'component.jsx' and output as 'lib.js' file

// Source code entry
entry: {
  lib: './src/components/component.jsx'
},

// Code Output
output: {
  path: PATHS.build,
  filename: 'lib.js'
},

I also included the "externals" attribute with the react modules to avoid webpack including it in the 'lib.js' output.

externals: {
  'react': 'React',
  'react-dom' : 'ReactDOM'
}

Finally this is the simple React component that i want to publish:

import React from 'react';

export default class Component extends React.Component {

  constructor() {
    super();
  }

  render() {
    return (

MY COMPONENT

    );
  }
}

I published it to NPM and installed it in another project. When I tried to use it after import React statement, it gives me an error saying that React is not defined (bundle.js:28448 Uncaught ReferenceError: React is not defined)

My code to probe the component:

import React from 'react';
import ReactDOM from 'react-dom';
import Component from 'component';
import $ from 'jquery';

ReactDOM.render(
   <Component />,
   $("#app")
);

Am I missing anything in the dependencies config?

Thanks


问:
Vertx RxJava webclient client
I am trying to consume a REST API using vertx and rx java, below is my code

```<code>import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.ext.web.client.HttpResponse;
import rx.Single;

public Single<HttpResponse<Buffer>> getLanguages() {
            WebClientOptions options = new WebClientOptions().setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.82 Safari/537.36");
            WebClient client = WebClient.create(Vertx.vertx(), options);
            Single<HttpResponse<Buffer>> single = client
                    .get("time.jsontest.com", "/")
                    .rxSend();
            return single;
        }
</code>```

And my subscriber code in the main class is

```<code>public static void main(String[] args) {
        Single<HttpResponse<Buffer>> single = new ITAPILanguagesImpl().getLanguages();
        single.subscribe(response -> {
            System.out.println("Received 1st response with status code" + response.statusCode());
        }, error -> {
            System.out.println("Something went wrong " + error.getMessage());
        });
    }
</code>```

When I run the main method I get the following error

```<code>Jun 06, 2017 9:48:32 PM io.netty.resolver.dns.DnsNameResolver trySuccess
Something went wrong Network is unreachable: no further information: time.jsontest.com/2404:6800:4007:807:0:0:0:2013:80
WARNING: Failed to notify success (time.jsontest.com/2404:6800:4007:807:0:0:0:2013) to a promise: DefaultPromise@5dcb32d8(success: time.jsontest.com/2404:6800:4007:807:0:0:0:2013)
</code>```

I checked the url and it is working fine, only when I connect to this url using vertx webclient I get this error, what am I missing?
I have added the following artifacts as dependencies in the pom file.

```<code><dependency>
    <groupId>io.reactivex.rxjava2</groupId>
    <artifactId>rxjava</artifactId>
    <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-web-client</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-rx-java</artifactId>
    <version>3.4.1</version>
</dependency>
</code>```

Thanks!

答:
It looks like a DNS problem in your environment.

Try switching to the JVM built-in resolver by adding this system property on the command line:

```<code>-Dvertx.disableDnsResolver=true
</code>```

By the way, creating a Vert.x instance and a Web Client anytime you invoke your method is a bad practice. You should reuse a single instance of both.

Title: Vertx RxJava webclient client

Body:
I am trying to consume a REST API using vertx and rx java, below is my code

import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.ext.web.client.HttpResponse;
import rx.Single;

public Single<HttpResponse<Buffer>> getLanguages() {
            WebClientOptions options = new WebClientOptions().setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.82 Safari/537.36");
            WebClient client = WebClient.create(Vertx.vertx(), options);
            Single<HttpResponse<Buffer>> single = client
                    .get("time.jsontest.com", "/")
                    .rxSend();
            return single;
        }

And my subscriber code in the main class is

public static void main(String[] args) {
        Single<HttpResponse<Buffer>> single = new ITAPILanguagesImpl().getLanguages();
        single.subscribe(response -> {
            System.out.println("Received 1st response with status code" + response.statusCode());
        }, error -> {
            System.out.println("Something went wrong " + error.getMessage());
        });
    }

When I run the main method I get the following error

Jun 06, 2017 9:48:32 PM io.netty.resolver.dns.DnsNameResolver trySuccess
Something went wrong Network is unreachable: no further information: time.jsontest.com/2404:6800:4007:807:0:0:0:2013:80
WARNING: Failed to notify success (time.jsontest.com/2404:6800:4007:807:0:0:0:2013) to a promise: DefaultPromise@5dcb32d8(success: time.jsontest.com/2404:6800:4007:807:0:0:0:2013)

I checked the url and it is working fine, only when I connect to this url using vertx webclient I get this error, what am I missing?
I have added the following artifacts as dependencies in the pom file.

<dependency>
    <groupId>io.reactivex.rxjava2</groupId>
    <artifactId>rxjava</artifactId>
    <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-web-client</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-rx-java</artifactId>
    <version>3.4.1</version>
</dependency>

Thanks!

Body:
It looks like a DNS problem in your environment.

Try switching to the JVM built-in resolver by adding this system property on the command line:

-Dvertx.disableDnsResolver=true

By the way, creating a Vert.x instance and a Web Client anytime you invoke your method is a bad practice. You should reuse a single instance of both.


问:
Relational tables: a 3rd table with relations
I'm building a php page that will show an specific banner when the user enters his/her phone number in a form field.

So here's my logic for the database:

Table phones with fields: id, name of user and phone number.
Table banners with fields: id, banner's name/title and banner (path to the image).
Table relation with fields: here's where the phone number should be related to a banner and where I need your help :)

And here's my logic for the php page:

-form gets the phone number
-I query the data base
-I show the banner related to the phone number entered in the form.

Below is the code for the table creation so far .. as you'll see don't know how to advance.

Thanks a million

```<code>    CREATE TABLE phones(

id_phone INT NOT NULL AUTO_INCREMENT,

nombre VARCHAR(30),

number INT (9),

PRIMARY KEY (id_phone)

) TYPE = INNODB;

CREATE TABLE banners (

id_banners INT NOT NULL AUTO_INCREMENT,

id_phone INT NOT NULL,

name VARCHAR(250),

banner VARCHAR(250),

PRIMARY KEY(id_phone),

INDEX (id_phone),

FOREIGN KEY (id_phone) REFERENCES clientes(id_phone)

) TYPE = INNODB;
</code>```

答:
First of all what's the question?
What can I mention at this step is, does the relation between this entities is one to one? If so, you'd better put all this data into one single table.

++

```<code>CREATE TABLE phones(
phone_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30),
number INT (9),
PRIMARY KEY (id_phone)
) TYPE = INNODB;

CREATE TABLE banners (
banner_id INT NOT NULL AUTO_INCREMENT,
phone_id INT NOT NULL,
name VARCHAR(250),
banner VARCHAR(250),
PRIMARY KEY(id_phone),
INDEX (id_phone),
FOREIGN KEY (phone_id) REFERENCES clientes(phone_id)
) TYPE = INNODB;
</code>```

and the query would be:

```<code>$query = "SELECT * FROM clients LEFT JOIN banners USING(phone_id) WHERE clients.number='.$number.'";
</code>```

Body:
I'm building a php page that will show an specific banner when the user enters his/her phone number in a form field.

So here's my logic for the database:

Table phones with fields: id, name of user and phone number.
Table banners with fields: id, banner's name/title and banner (path to the image).
Table relation with fields: here's where the phone number should be related to a banner and where I need your help :)

And here's my logic for the php page:

-form gets the phone number
-I query the data base
-I show the banner related to the phone number entered in the form.

Below is the code for the table creation so far .. as you'll see don't know how to advance.

Thanks a million

    CREATE TABLE phones(

id_phone INT NOT NULL AUTO_INCREMENT,

nombre VARCHAR(30),

number INT (9),

PRIMARY KEY (id_phone)

) TYPE = INNODB;

CREATE TABLE banners (

id_banners INT NOT NULL AUTO_INCREMENT,

id_phone INT NOT NULL,

name VARCHAR(250),

banner VARCHAR(250),

PRIMARY KEY(id_phone),

INDEX (id_phone),

FOREIGN KEY (id_phone) REFERENCES clientes(id_phone)

) TYPE = INNODB;

Body:
First of all what's the question?
What can I mention at this step is, does the relation between this entities is one to one? If so, you'd better put all this data into one single table.

++

CREATE TABLE phones(
phone_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30),
number INT (9),
PRIMARY KEY (id_phone)
) TYPE = INNODB;

CREATE TABLE banners (
banner_id INT NOT NULL AUTO_INCREMENT,
phone_id INT NOT NULL,
name VARCHAR(250),
banner VARCHAR(250),
PRIMARY KEY(id_phone),
INDEX (id_phone),
FOREIGN KEY (phone_id) REFERENCES clientes(phone_id)
) TYPE = INNODB;

and the query would be:

$query = "SELECT * FROM clients LEFT JOIN banners USING(phone_id) WHERE clients.number='.$number.'";


问:
Jackson Serialize to Template List
I have a class like this:

```<code>public class Garage<T> {
    private List<T> vehicles;

    public Garage() {
    }

    public Garage(List<T> vehicles) {
        this.vehicles = Collections.unmodifiableList(vehicles);
    }

    public List<T> getVehicles() {
        return vehicles;
    }
}

public class Car {
    private Type type;
    private Make make;
    private Model model;
    private String name;
}

public class Boat {
    private double weight;
    private Make make;
    private Model model;
    private String name;
}
</code>```

And a Spring API endpoint like this:

```<code>@RestController
public class CarController {
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<List<Vehicles>> addCar(@RequestBody Garage<Car> cars) {
        //logic
    }
}
</code>```

When I try to pass in a JSON input that looks like this:

```<code>{
   "vehicles":[
      {
         "type":SEDAN,
         "make":HONDA,
         "model":ACCORD,
         "name":"My Awesome Car"
      },
      {
         "type":SUV,
         "make":HONDA,
         "model":CRV,
         "name":"My Awesome Car 2"
      }
   ]
}
</code>```

I get the error:

```<code>org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:292) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:380) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1193) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.processHandlerException(TestDispatcherServlet.java:112) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1030) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at net.api.controllers.CarControllerTest.test(CarControllerTest.java:46) [test-classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:284) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1110) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1135) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:69) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:32) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1429) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:951) ~[jackson-databind-2.8.8.jar:2.8.8]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:285) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 67 common frames omitted
</code>```

But if I change the api endpoint @RequestBody to @RequestBody Garage cars then Jackson deserializes just fine but the Garage object contains a list of HashMap instances rather than Car instances.

How do you fix this?

答: CHange your @RequestBody to Garage and Implements Serializable in your classes</p>

Title: Jackson Serialize to Template List

Body:
I have a class like this:

public class Garage<T> {
    private List<T> vehicles;

    public Garage() {
    }

    public Garage(List<T> vehicles) {
        this.vehicles = Collections.unmodifiableList(vehicles);
    }

    public List<T> getVehicles() {
        return vehicles;
    }
}

public class Car {
    private Type type;
    private Make make;
    private Model model;
    private String name;
}

public class Boat {
    private double weight;
    private Make make;
    private Model model;
    private String name;
}

And a Spring API endpoint like this:

@RestController
public class CarController {
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<List<Vehicles>> addCar(@RequestBody Garage<Car> cars) {
        //logic
    }
}

When I try to pass in a JSON input that looks like this:

{
   "vehicles":[
      {
         "type":SEDAN,
         "make":HONDA,
         "model":ACCORD,
         "name":"My Awesome Car"
      },
      {
         "type":SUV,
         "make":HONDA,
         "model":CRV,
         "name":"My Awesome Car 2"
      }
   ]
}

I get the error:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:292) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:380) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1193) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.processHandlerException(TestDispatcherServlet.java:112) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1030) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at net.api.controllers.CarControllerTest.test(CarControllerTest.java:46) [test-classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:284) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1110) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1135) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:69) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:32) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1429) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:951) ~[jackson-databind-2.8.8.jar:2.8.8]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:285) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 67 common frames omitted

But if I change the api endpoint @RequestBody to @RequestBody Garage cars then Jackson deserializes just fine but the Garage object contains a list of HashMap instances rather than Car instances.

How do you fix this?


问:
Select date in datapicker with calabach
In Calabash Automation testing on Android. I need to select a date from a date picker. Please guide me with a ruby step definition.

I want something like

Then I scroll datepicker to date "20-05-2017"

答:
According to calabash-android GitHub repository, you can use these calabash canned-steps:

https://github.com/calabash/calabash-android/blob/master/ruby-gem/lib/calabash-android/steps/date_picker_steps.rb

Title: Select date in datapicker with calabach