问:
Reading resource file inside jar dependency
Before I explain my problem - I've tried to find solution in already asked questions, but none of them worked ;)

I'm trying to read file inside jar, which is a dependency for another project. This file is located under path

```<code>/src/main/resources/driver
</code>```

Project is packaged into jar file. DRIVER from resources is included into jar using pom:

```<code>    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>*</include>
            </includes>
        </resource>
    </resources>
</code>```

Also, when I unpack jar, I can see that it's added to jar's root directory.

What I need to do, is copy this file from the inside of the jar, to a directory on a disk. It all works fine, as long as the project is added via IntelliJ as a dependent project. When I add it as a dependency in POM, I get a NullPointerException.

A code that I use to load this file look like this:

```<code>String sourceFilePath = this.getClass().getClassLoader().getResource(driverFileName).getPath();
</code>```

I also tried different approaches:

```<code>    String sourceFilePath = this.getClass().getResource("driver").getPath();
    String sourceFilePath = this.getClass().getResource("/driver").getPath();
    String sourceFilePath = this.getClass().getClassLoader().getResource("driver").getPath();
    String sourceFilePath = this.getClass().getClassLoader().getResource("/driver").getPath();
</code>```

But every try ends with the same result: NullPointerException when calling getPath().

I need solution for that, because the project that is attached as dependency is a framework for UI tests. Until now I was adding drivers to each new project that needed them, but it takes time, makes it more complicated for people who want to use this framework and makes a lot of trouble when new version of driver is released. I want to be able to simply add a maven dependency for this framework and be able to use drivers from the inside of this framework.
The problem here is that I need to set a system variable with path to that driver. So once the driver is needed, I'm trying to copy it (code for that is inside framework) to external location (some tmp directory).

Any idea how to solve it?

答:
Use target jar classloader like this</p>

```<code>ClassInOtherJar.class.getClassLoader().getResourceAsStream("filename.xml")
</code>```

Body:
Before I explain my problem - I've tried to find solution in already asked questions, but none of them worked ;)

I'm trying to read file inside jar, which is a dependency for another project. This file is located under path

/src/main/resources/driver

Project is packaged into jar file. DRIVER from resources is included into jar using pom:

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>*</include>
            </includes>
        </resource>
    </resources>

Also, when I unpack jar, I can see that it's added to jar's root directory.

What I need to do, is copy this file from the inside of the jar, to a directory on a disk. It all works fine, as long as the project is added via IntelliJ as a dependent project. When I add it as a dependency in POM, I get a NullPointerException.

A code that I use to load this file look like this:

String sourceFilePath = this.getClass().getClassLoader().getResource(driverFileName).getPath();

I also tried different approaches:

    String sourceFilePath = this.getClass().getResource("driver").getPath();
    String sourceFilePath = this.getClass().getResource("/driver").getPath();
    String sourceFilePath = this.getClass().getClassLoader().getResource("driver").getPath();
    String sourceFilePath = this.getClass().getClassLoader().getResource("/driver").getPath();

But every try ends with the same result: NullPointerException when calling getPath().

I need solution for that, because the project that is attached as dependency is a framework for UI tests. Until now I was adding drivers to each new project that needed them, but it takes time, makes it more complicated for people who want to use this framework and makes a lot of trouble when new version of driver is released. I want to be able to simply add a maven dependency for this framework and be able to use drivers from the inside of this framework.
The problem here is that I need to set a system variable with path to that driver. So once the driver is needed, I'm trying to copy it (code for that is inside framework) to external location (some tmp directory).

Any idea how to solve it?

Body:
Use target jar classloader like this

ClassInOtherJar.class.getClassLoader().getResourceAsStream("filename.xml")


来源: stackexchange

问:
How to apply combination fields validation using jquery
I my requirement form is generated dynamically. there are number of fields

```<code><tr>
    <td >Coding Guidelines</td>
    <td align="center">
     <select name="SELECT_TASK_1" id="SELECT_TASK_1">
       <option value="">Select</option>
       <option value="Y">Yes</option>
       <option value="N">No</option>
     </select>
   </td>
   <td align="center"><input type="text" size="10" name="COMP_DATE_1"></td>
  <td align="left"> <textarea name="COMMENT_TASK_1" id="COMMENT_TASK_1"
             cols="45" rows="4"></textarea><span id="COMMENT_ERROR_1" > </span>
   </td>
</tr>
</code>```

there are number of TR generated base on DB rows. I want apply jquery validation on the combination of select No value and Comment field.

That means if select is No then comment is mandatory field.

Please help how to apply validation using Jquery validation plugin

答:
Perhaps you can attach a handler to the submit form button:

```<code>$(#form-id).submit(function(){
var valid = true;
if($('#SELECT_TASK_1').val() == "N" && $('#COMMENT_TASK_1').val() == '')
valid = false;

return valid
});
</code>```

For selecting all selects:

```<code>var selects = $('#form-id').find('select');
for(var i = 0; i < selects.length; i++){
  if(selects[i].val() == 'N'){
     if(area is empty)
      valid = false;
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I my requirement form is generated dynamically. there are number of fields

    Coding Guidelines

     <select name="SELECT_TASK_1" id="SELECT_TASK_1">
       <option value="">Select</option>
       <option value="Y">Yes</option>
       <option value="N">No</option>
     </select>

   <input type="text" size="10" name="COMP_DATE_1">
   <textarea name="COMMENT_TASK_1" id="COMMENT_TASK_1"
             cols="45" rows="4"></textarea>

there are number of TR generated base on DB rows. I want apply jquery validation on the combination of select No value and Comment field.

That means if select is No then comment is mandatory field.

Please help how to apply validation using Jquery validation plugin

Body:
Perhaps you can attach a handler to the submit form button:

$(#form-id).submit(function(){
var valid = true;
if($('#SELECT_TASK_1').val() == "N" && $('#COMMENT_TASK_1').val() == '')
valid = false;

return valid
});

For selecting all selects:

var selects = $('#form-id').find('select');
for(var i = 0; i < selects.length; i++){
  if(selects[i].val() == 'N'){
     if(area is empty)
      valid = false;
  }
}

ContentLicense: CC BY-SA 3.0


问:
Converting Dword into Bit array in C#
I am working in an app that connects to a Siemens PLC using LibnoDave library. I am getting a Dword value that I convert it into an INT value, but now I need to convert this INT value into a BIT array. For example, I get as a INT value the number 62000 that in binary is 1111001000110000. I need that value. How can this be done?</p>

答:
If you want to represent uint in binary, try using Convert class:

```<code>  uint source = 62000;

  string result = Convert.ToString(source, 2);

  Console.WriteLine(result);
</code>```

Outcome

```<code>  1111001000110000
</code>```

If you want System.Collections.BitArray instance:

```<code>  using System.Collections;
  using System.Linq;

  ...

  uint source = 62000;

  BitArray array = new BitArray(BitConverter.IsLittleEndian
    ? BitConverter.GetBytes(source)
    : BitConverter.GetBytes(source).Reverse().ToArray());

  // Test
  string result = string
    .Concat(array
       .OfType<bool>()
       .Reverse()
       .Select(item => item ? 1 : 0))
    .TrimStart('0');

  Console.WriteLine(result);
</code>```

Outcome

```<code>  1111001000110000
</code>```

Title: Converting Dword into Bit array in C#

Body:
If you want to represent uint in binary, try using Convert class:

  uint source = 62000;

  string result = Convert.ToString(source, 2);

  Console.WriteLine(result);

Outcome

  1111001000110000

If you want System.Collections.BitArray instance:

  using System.Collections;
  using System.Linq;

  ...

  uint source = 62000;

  BitArray array = new BitArray(BitConverter.IsLittleEndian
    ? BitConverter.GetBytes(source)
    : BitConverter.GetBytes(source).Reverse().ToArray());

  // Test
  string result = string
    .Concat(array
       .OfType<bool>()
       .Reverse()
       .Select(item => item ? 1 : 0))
    .TrimStart('0');

  Console.WriteLine(result);

Outcome

  1111001000110000


问:
Providing mocked object to another mock object constructor?
First time unit testing, and using Mockito. I'm not sure if I'm thinking about testing this correctly. Here is the situation:

In my Android app, I am using Model-View-Presenter. I am trying to test a method in my presenter class called validateCredential(serviceManager: ServiceManager, email: String, password: String) to see if the service manager I pass to it will eventually call a callback (this method is called by the view) by verifying it with mockito.

```<code>// method in presenter class
override fun validateCredential(serviceManager: ServiceManager, email: String, password: String) {
    loginModel = LoginModel(email, password)
    serviceManager.getParent(email, password)
    serviceManager.execute()
}

// callback implemented by presenter class
private fun handleLoginResult(result: ServiceManager.RequestResult, data: ByteArray, responseCode: Int, optionalParam: String) {
    ...
    mView.startHomeScreen()
}
</code>```

The presenter class also implements a callback interface (IServiceAsyncTaskCallback) that is provided to the serviceManager's constructor. What I want in this specific unit test is to verify that mView.startHomeScreen() is called.

The problem:

Android unit testing seems to require that ServiceManager be mocked (ServiceManager extends abstract class AsyncTask) because when I call execute(), the Android unit testing lib will throw an exception if it is not mocked.

However, if I mock the ServiceManager, I can't provide it with two necessary parameters to the constructor, which SHOULD be mocked, if I'm understanding unit testing correctly. The two parameters to the constructor are an interface callback (which is the presenter class), and a class object that is responsible for sending JSON through http. Both of these should be mocked, correct? Because in a unit test you don't want these dependencies to actually make HTTP calls or call callbacks, right?

It seems I'm overthinking this. What I really want is to see if my view object which is passed to presenter, calls startHomeScreen(), so I should really just forget testing the validateCredentialMethod() and just call handleLoginResult(...) directly. Is this better than the above route?

However, another problem is that even if I call handleLoginResult(...) directly to test if the mock view that is passed to presenter is called, that method code contains a call to JSONObject which is Android related code, and since it belongs to the android.jar file, it will throw an exception because it is not mocked! Am I supposed to provide an injection for that too?!

I'm lost as how to test this. What's the correct way to verify that the mock view has called startHomeScreen()?

答:
The problem is that you are trying to test two separate classes in one unit test, which makes it not a unit test.

With your current setup, it seems like you want to have 3 different test cases, in 2 different classes (making up names, trying to be as explicit as possible about their content):

PresenterTest

testThatServiceManagerIsExcecutedOnValidateCredential

testThatStartHomeScreenIsCalledWhenHandlingLoginResult

ServiceManagerTest

testCallbackIsCalledOnExcecuted

Body:
First time unit testing, and using Mockito. I'm not sure if I'm thinking about testing this correctly. Here is the situation:

In my Android app, I am using Model-View-Presenter. I am trying to test a method in my presenter class called validateCredential(serviceManager: ServiceManager, email: String, password: String) to see if the service manager I pass to it will eventually call a callback (this method is called by the view) by verifying it with mockito.

// method in presenter class
override fun validateCredential(serviceManager: ServiceManager, email: String, password: String) {
    loginModel = LoginModel(email, password)
    serviceManager.getParent(email, password)
    serviceManager.execute()
}

// callback implemented by presenter class
private fun handleLoginResult(result: ServiceManager.RequestResult, data: ByteArray, responseCode: Int, optionalParam: String) {
    ...
    mView.startHomeScreen()
}

The presenter class also implements a callback interface (IServiceAsyncTaskCallback) that is provided to the serviceManager's constructor. What I want in this specific unit test is to verify that mView.startHomeScreen() is called.

The problem:

Android unit testing seems to require that ServiceManager be mocked (ServiceManager extends abstract class AsyncTask) because when I call execute(), the Android unit testing lib will throw an exception if it is not mocked.

However, if I mock the ServiceManager, I can't provide it with two necessary parameters to the constructor, which SHOULD be mocked, if I'm understanding unit testing correctly. The two parameters to the constructor are an interface callback (which is the presenter class), and a class object that is responsible for sending JSON through http. Both of these should be mocked, correct? Because in a unit test you don't want these dependencies to actually make HTTP calls or call callbacks, right?

It seems I'm overthinking this. What I really want is to see if my view object which is passed to presenter, calls startHomeScreen(), so I should really just forget testing the validateCredentialMethod() and just call handleLoginResult(...) directly. Is this better than the above route?

However, another problem is that even if I call handleLoginResult(...) directly to test if the mock view that is passed to presenter is called, that method code contains a call to JSONObject which is Android related code, and since it belongs to the android.jar file, it will throw an exception because it is not mocked! Am I supposed to provide an injection for that too?!

I'm lost as how to test this. What's the correct way to verify that the mock view has called startHomeScreen()?


问:
Hosting 2 django project inside one VPS server
I am trying to run 2 django project in one single VPS server in 2 different domain. I am using gunicorn as my project server.
I have created 2 virtual env, 2 supervisor and 2 separate file in sites-available and enable-folder.
My project is running well but the problem is in one time only one project is running in both the domain. Though in my nginx sites-avaible files are given different domain as server_name still one django project is running both of the domain
Can any oone help.

/etc/nginx/sites-avaiable/VaidText

```<code>upstream sample_project_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).
  server unix:/home/example/test.example.com/TestEnv/run/gunicorn.sock fail_timeout=0;
}
server {
listen   80;
server_name test.example.com;

client_max_body_size 4G;
access_log /home/example/test.example.com/logs/nginx-access.log;
error_log /home/example/test.example.com/logs/nginx-error.log;

location /static/ {
    alias   /home/ubuntu/static/;
}

location /media/ {
    alias   /home/ubuntu/media/;
}

location / {

    # an HTTP header important enough to have its own Wikipedia entry:
    #   http://en.wikipedia.org/wiki/X-Forwarded-For
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # enable this if and only if you use HTTPS, this helps Rack
    # set the proper protocol for doing redirects:
    # proxy_set_header X-Forwarded-Proto https;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # set "proxy_buffering off" *only* for Rainbows! when doing
    # Comet/long-poll stuff.  It's also safe to set if you're
    # using only serving fast clients with Unicorn + nginx.
    # Otherwise you _want_ nginx to buffer responses to slow
    # clients, really.
    # proxy_buffering off;

    # Try to serve static files from nginx, no point in making an
    # *application* server like Unicorn/Rainbows! serve static files.
    if (!-f $request_filename) {
        proxy_pass http://sample_project_server;
        break;
    }
}

# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
    root /home/ubuntu/static/;
}
</code>```

}

/etc/nginx/sites-avaiable/SheikhText

```<code>  upstream sample_project_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).
  server

unix:/home/example/sheikhnoman.example.com/SheikhEnv/run/gunicorn.sock fail_timeout=0;
}

server {

listen   80;
server_name sheikhnoman.example.com;

client_max_body_size 4G;
access_log /home/example/sheikhnoman.example.com/logs/nginx-access.log;
error_log /home/example/sheikhnoman.example.com/logs/nginx-error.log;

location /static/ {
    alias   /home/ubuntu/sheikhnoman/static/;
}

location /media/ {
    alias   /home/ubuntu/sheikhnoman/media/;
}

location / {

    # an HTTP header important enough to have its own Wikipedia entry:
    #   http://en.wikipedia.org/wiki/X-Forwarded-For
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # enable this if and only if you use HTTPS, this helps Rack
    # set the proper protocol for doing redirects:
    # proxy_set_header X-Forwarded-Proto https;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # set "proxy_buffering off" *only* for Rainbows! when doing
    # Comet/long-poll stuff.  It's also safe to set if you're
    # using only serving fast clients with Unicorn + nginx.
    # Otherwise you _want_ nginx to buffer responses to slow
    # clients, really.
    # proxy_buffering off;

    # Try to serve static files from nginx, no point in making an
    # *application* server like Unicorn/Rainbows! serve static files.
    if (!-f $request_filename) {
        proxy_pass http://sample_project_server;
        break;
    }
}

# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
    root /home/ubuntu/sheikhnoman/static/;
}
}
</code>```

答: Your two ngnix config files contains the same "sample_project_server" upstream name. Try to set a different upsteam name for each of your files.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run 2 django project in one single VPS server in 2 different domain. I am using gunicorn as my project server.
I have created 2 virtual env, 2 supervisor and 2 separate file in sites-available and enable-folder.
My project is running well but the problem is in one time only one project is running in both the domain. Though in my nginx sites-avaible files are given different domain as server_name still one django project is running both of the domain
Can any oone help.

/etc/nginx/sites-avaiable/VaidText

upstream sample_project_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).
  server unix:/home/example/test.example.com/TestEnv/run/gunicorn.sock fail_timeout=0;
}
server {
listen   80;
server_name test.example.com;

client_max_body_size 4G;
access_log /home/example/test.example.com/logs/nginx-access.log;
error_log /home/example/test.example.com/logs/nginx-error.log;

location /static/ {
    alias   /home/ubuntu/static/;
}

location /media/ {
    alias   /home/ubuntu/media/;
}

location / {

    # an HTTP header important enough to have its own Wikipedia entry:
    #   http://en.wikipedia.org/wiki/X-Forwarded-For
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # enable this if and only if you use HTTPS, this helps Rack
    # set the proper protocol for doing redirects:
    # proxy_set_header X-Forwarded-Proto https;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # set "proxy_buffering off" *only* for Rainbows! when doing
    # Comet/long-poll stuff.  It's also safe to set if you're
    # using only serving fast clients with Unicorn + nginx.
    # Otherwise you _want_ nginx to buffer responses to slow
    # clients, really.
    # proxy_buffering off;

    # Try to serve static files from nginx, no point in making an
    # *application* server like Unicorn/Rainbows! serve static files.
    if (!-f $request_filename) {
        proxy_pass http://sample_project_server;
        break;
    }
}

# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
    root /home/ubuntu/static/;
}

}

/etc/nginx/sites-avaiable/SheikhText

  upstream sample_project_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).
  server

unix:/home/example/sheikhnoman.example.com/SheikhEnv/run/gunicorn.sock fail_timeout=0;
}

server {

listen   80;
server_name sheikhnoman.example.com;

client_max_body_size 4G;
access_log /home/example/sheikhnoman.example.com/logs/nginx-access.log;
error_log /home/example/sheikhnoman.example.com/logs/nginx-error.log;

location /static/ {
    alias   /home/ubuntu/sheikhnoman/static/;
}

location /media/ {
    alias   /home/ubuntu/sheikhnoman/media/;
}

location / {

    # an HTTP header important enough to have its own Wikipedia entry:
    #   http://en.wikipedia.org/wiki/X-Forwarded-For
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # enable this if and only if you use HTTPS, this helps Rack
    # set the proper protocol for doing redirects:
    # proxy_set_header X-Forwarded-Proto https;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # set "proxy_buffering off" *only* for Rainbows! when doing
    # Comet/long-poll stuff.  It's also safe to set if you're
    # using only serving fast clients with Unicorn + nginx.
    # Otherwise you _want_ nginx to buffer responses to slow
    # clients, really.
    # proxy_buffering off;

    # Try to serve static files from nginx, no point in making an
    # *application* server like Unicorn/Rainbows! serve static files.
    if (!-f $request_filename) {
        proxy_pass http://sample_project_server;
        break;
    }
}

# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
    root /home/ubuntu/sheikhnoman/static/;
}
}


问:
IE9 text-overflow: ellipsis; not working with text-align: center;

As you can see the first . gets over the last 6 and only on IE9.

Any workarounds?

NOTE:

```<code><div class="truncate">666</div>

div { text-align: center; /* NOTE: The text should be on center. */ }
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
</code>```

http://jsfiddle.net/MvaGe/4/

答: If you have set word-wrap: bread-word, please change it to word:wrap: normal. It works for me.

Body:
As you can see the first . gets over the last 6 and only on IE9.

Any workarounds?

NOTE:

666

div { text-align: center; /* NOTE: The text should be on center. */ }
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

http://jsfiddle.net/MvaGe/4/


问:
How to get the homescreen behaviour of drag to bin, in my own application?
On the Android homescreen it's possible to delete the items by dragging them to the bin.

I would like to have similar functionality in my own application, where I have a view with custom view items that I want to be user drag-and-droppable.

Is there a easy way to implement this functionality? Or could somebody give me pointers that can guide me on the possibly difficult way to achieving this?

答:
I assume you have a homescreen like application, at least a view with items that you want to drag and drop.

Like Austyn Mahoney says in his comment you can refere to the android open source homescreen code. But since drag and drop is a easy to implement feature you can handle it on your own, too.

You need your items to be stored in e.g. an array. Then go through the event types.

On every ACTION_DOWN you need to check if an item was hit by the user. E.g. if we have circles as items we need to capture the current ACTION_DOWN coordinates so we can check for them to be within the item and obtain the ID of the item that the user is about to drag according to the ACTION_DOWN coordinates.

On ACTION_MOVE you just need to pass the current x and y coordinates to the item to redraw it on the new position.

Well this is just the drag and drop feature. Now you need to test for the item to be in a specific sector you call bin. So you define a rectangle on your screen. in ACTION_MOVE your test the item to be within this area, thats all.

Just some example code for drag and drop:

```<code>public boolean onTouchEvent(MotionEvent event){
    int itemID = 0;
    int X = (int)event.getX();
    int Y = (int)event.getY();

        switch(event.getAction()){
             case MotionEvent.ACTION_DOWN:
                for(Items item : dragable_item){

                    //center coords of the item
                    int centerX = item.getX() + 25;
                    int centerY = item.getY() + 25;

                    //calculate the distance (radius) from touch to item

                    //get item to drag
                    if(distance < 20){
                        itemId = item.getID(); break;
                    }
                }
             break;
             case MotionEvent.ACTION_MOVE:
                 if(itemID > 0){
                     Items[itemID-1].setX(X-25);
                     Items[itemID-1].setY(X-25);
                 }
             break;
        }
    }
    invalidate(); return true;
}
</code>```

If you wand to dig more into the code have a look at anddev.org - drag and drop.

Body:
I assume you have a homescreen like application, at least a view with items that you want to drag and drop.

Like Austyn Mahoney says in his comment you can refere to the android open source homescreen code. But since drag and drop is a easy to implement feature you can handle it on your own, too.

You need your items to be stored in e.g. an array. Then go through the event types.

On every ACTION_DOWN you need to check if an item was hit by the user. E.g. if we have circles as items we need to capture the current ACTION_DOWN coordinates so we can check for them to be within the item and obtain the ID of the item that the user is about to drag according to the ACTION_DOWN coordinates.

On ACTION_MOVE you just need to pass the current x and y coordinates to the item to redraw it on the new position.

Well this is just the drag and drop feature. Now you need to test for the item to be in a specific sector you call bin. So you define a rectangle on your screen. in ACTION_MOVE your test the item to be within this area, thats all.

Just some example code for drag and drop:

public boolean onTouchEvent(MotionEvent event){
    int itemID = 0;
    int X = (int)event.getX();
    int Y = (int)event.getY();

        switch(event.getAction()){
             case MotionEvent.ACTION_DOWN:
                for(Items item : dragable_item){

                    //center coords of the item
                    int centerX = item.getX() + 25;
                    int centerY = item.getY() + 25;

                    //calculate the distance (radius) from touch to item

                    //get item to drag
                    if(distance < 20){
                        itemId = item.getID(); break;
                    }
                }
             break;
             case MotionEvent.ACTION_MOVE:
                 if(itemID > 0){
                     Items[itemID-1].setX(X-25);
                     Items[itemID-1].setY(X-25);
                 }
             break;
        }
    }
    invalidate(); return true;
}

If you wand to dig more into the code have a look at anddev.org - drag and drop.


问:
Cancel an AsyncTask Class in Android
I have a class name is GetData that extends from AsyncTask. In other class I have an object from GetData and with this codes I use that:

```<code>GetData getData = new GetData();
getData().execute();
</code>```

I want to stop this thread when a button clicked. I do this with:

```<code>getData().cancel(true);
</code>```

I want to know if I canceled thread while it is in doInBackground, it stopped or it goes to onPostExecute and then stop?

答:
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

For further details visit:

https://developer.android.com/reference/android/os/AsyncTask.html

Just like:

```<code>onPostExecute(Result result)
{
}
</code>```

you can override a method for cancel to update your UI accordingly when your asyncTask is cancelled as follows:

```<code>onCancelled(Result result)
{
    // here you can handle situation according to your requirements
}
</code>```

So point of your interest here is that whenever you cancel your task before it enters into onPostExecute it will not go into onPostExecute but will jump to onCancelled. You can also call task.cancel(true); in postExecute according to your condition by applying required checks.

Title: Cancel an AsyncTask Class in Android

Body:
I have a class name is GetData that extends from AsyncTask. In other class I have an object from GetData and with this codes I use that:

GetData getData = new GetData();
getData().execute();

I want to stop this thread when a button clicked. I do this with:

getData().cancel(true);

I want to know if I canceled thread while it is in doInBackground, it stopped or it goes to onPostExecute and then stop?

Body:
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

For further details visit:

https://developer.android.com/reference/android/os/AsyncTask.html

Just like:

onPostExecute(Result result)
{
}

you can override a method for cancel to update your UI accordingly when your asyncTask is cancelled as follows:

onCancelled(Result result)
{
    // here you can handle situation according to your requirements
}

So point of your interest here is that whenever you cancel your task before it enters into onPostExecute it will not go into onPostExecute but will jump to onCancelled. You can also call task.cancel(true); in postExecute according to your condition by applying required checks.


问:
Recover of slave in MySQL Master-Master Replication
How can we recover slaves in case one master goes down in master-master replication while slaves are pointed to the master which got failed ?</p>

答:
Here we have Master-Master Replication in MySQL and 3 slaves under one master and 1 slave under another master. Now what needs to be done if M1 goes down and we have to bring 3 slaves under M2.

M1--S1,S2,S3
M2--S4

M1 : Master1
M2 : Master2

S1,S2 and S3: Slaves configured under M1

Scenario : M1 goes down (Server is not accessible) and traffic is being served by M2 now we have to bring S1,S2 and S3 under M2

On M2
a. show slave status (note down the positions)
b. Parse current binlog and check what is last command logged with server id of M1 after that all commands must be logged using M2 server id
c. Note down the position just after the last command logged by M1 server id

Check all slaves S1,S2,S3 should be having same show slave status status as M2 if not try making them read relay logs if available by starting SQL thread

Once all slaves are at the same position start all of the using position obtained in step 1(c.)

Now all three slaves are under M2 without any data loss

Note : In this case if M1 is not in sync with M2 and even relay logs on M2 is not available there would be data loss and slaves may throw some errors as well


问:
Error: No provider for Store! when trying @ngrx/store with Angular 4.0
Problem:
Error: No provider for Store!

I'm bootstraping store module in main.ts:

```<code>platformBrowserDynamic().bootstrapModule(AppModule,[
  provideStore({
    characters,
    vehicles
  })
]);
</code>```

And injecting in to vehicle.component.ts:

```<code>constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _vehicleService: VehicleService,
    private _store: Store<any>
  ) {}
</code>```

Full source code is here: GitHub,
last version running on GitHub Pages

PS. Adding Store to providers leads to another error:
Can't resolve all parameters for Store: (?, ?, ?).

答:
I had this error because, in my component auto-import imported Store from
import { Store } from '@ngrx/store/src/store' instead of
import { Store } from '@ngrx/store'; . Anyway, this was in Angular 5

Body:
Problem:
Error: No provider for Store!

I'm bootstraping store module in main.ts:

platformBrowserDynamic().bootstrapModule(AppModule,[
  provideStore({
    characters,
    vehicles
  })
]);

And injecting in to vehicle.component.ts:

constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _vehicleService: VehicleService,
    private _store: Store<any>
  ) {}

Full source code is here: GitHub,
last version running on GitHub Pages

PS. Adding Store to providers leads to another error:
Can't resolve all parameters for Store: (?, ?, ?).


问:
Angular double interpolation in template
Having a collection that you iterate through, is there a way to use a property of
the elements from the collection and use it as a key to take some else, from another stream (like a double interpolation) ? Just from the template alone.

Something like:

```<code>    <tr *ngFor="let book of (books$ | async)">
     <td> {{ (text$ | async)[{{ book.title }}] }}</td>
    </tr>
</code>```

Where I could use book.title to take something from text.

答: I've made a pipe which take the book.title as parameter and searches for the text in the app store.</p>

Body:
Having a collection that you iterate through, is there a way to use a property of
the elements from the collection and use it as a key to take some else, from another stream (like a double interpolation) ? Just from the template alone.

Something like:

      {{ (text$ | async)[{{ book.title }}] }}

Where I could use book.title to take something from text.


问:
Array Doesn't Push Elements Node.js
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

```<code>    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }
</code>```

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.

答:
try use JQuery and then "$('#userEntry').val()"
and a the button (/element) </p>

```<code>$('#button').click(() => {
    list.push($('#userEntry').val());
})"
</code>```

Title: Array Doesn't Push Elements Node.js

Body:
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.

Body:
try use JQuery and then "$('#userEntry').val()"
and a the button (/element)

$('#button').click(() => {
    list.push($('#userEntry').val());
})"


问:
Recycleview's onClick and put extra
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

```<code>public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}
</code>```

ShowSingleRecordActivity.java (Receiving ID)

```<code>public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_single_record);

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}
</code>```

and Searching.java

```<code>public class searching extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searching);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}
</code>```

答:
hopefully this will work .. but what exactly is your problem ? is it detecting the clicked value or passing ID to new Activity?</p>

```<code>@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.setTag(current);   //<--added
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

    ((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
                DataFish clickedData = (DataFish) v.getTag();   //<-- pull data from tag
                Intent intent = new Intent(context, ShowSingleRecordActivity.class);
                intent.putExtra("ID", clickedData.id);
                context.startActivity(intent);
            }
        });
}
</code>```

Title: Recycleview's onClick and put extra

Body:
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}

ShowSingleRecordActivity.java (Receiving ID)

public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_single_record);

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}

and Searching.java

public class searching extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searching);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

Body:
hopefully this will work .. but what exactly is your problem ? is it detecting the clicked value or passing ID to new Activity?

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.setTag(current);   //<--added
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

    ((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
                DataFish clickedData = (DataFish) v.getTag();   //<-- pull data from tag
                Intent intent = new Intent(context, ShowSingleRecordActivity.class);
                intent.putExtra("ID", clickedData.id);
                context.startActivity(intent);
            }
        });
}


问:
Why Jenkins says "Server rejected the 1 private key(s)" while launching the agent?
I am successfully able to connect to remote machine using SSH but when I am launching the agent from Jenkins it throws the following error:

```<code>ERROR: Server rejected the 1 private key(s) for user1 (credentialId:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/method:publickey)
[01/19/17 05:35:15] [SSH] Authentication failed.
hudson.AbortException: Authentication failed.
    at hudson.plugins.sshslaves.SSHLauncher.openConnection(SSHLauncher.java:1219)
    at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:714)
    at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:709)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
[01/19/17 05:35:15] Launch failed - cleaning up connection
[01/19/17 05:35:15] [SSH] Connection closed.
</code>```

I can establish SSH connection from master machine to the node machine using user1, however when I am trying to launch the agent using user1 from jenkins it is rejecting the private key. Is there any solution to overcome this issue?

答:
My Solution was:

```<code>$ user add -d /var/lib/jenkins jenkins
$ sudo su
$ passwd jenkins
$ chown -R jenkins /var/lib/jenkins/.ssh/*
$ chmod 700 .ssh
</code>```

It worked after tampering around for 2 hours...

Body:
I am successfully able to connect to remote machine using SSH but when I am launching the agent from Jenkins it throws the following error:

ERROR: Server rejected the 1 private key(s) for user1 (credentialId:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/method:publickey)
[01/19/17 05:35:15] [SSH] Authentication failed.
hudson.AbortException: Authentication failed.
    at hudson.plugins.sshslaves.SSHLauncher.openConnection(SSHLauncher.java:1219)
    at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:714)
    at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:709)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
[01/19/17 05:35:15] Launch failed - cleaning up connection
[01/19/17 05:35:15] [SSH] Connection closed.

I can establish SSH connection from master machine to the node machine using user1, however when I am trying to launch the agent using user1 from jenkins it is rejecting the private key. Is there any solution to overcome this issue?

Body:
My Solution was:

$ user add -d /var/lib/jenkins jenkins
$ sudo su
$ passwd jenkins
$ chown -R jenkins /var/lib/jenkins/.ssh/*
$ chmod 700 .ssh

It worked after tampering around for 2 hours...


问:
'>' is not recognising as a command line Argument ? How to Pass this as a command Line Argument?
Python Program:

```<code>import sys

print(len(sys.argv))
</code>```

Command Line:

Without '>' Operator

```<code>>>> python sample.py 1 2 3
</code>```

Output:

```<code>4
</code>```

With '>' Operator

```<code>>>> python sample.py > 1 2
</code>```

Output:

Not Showing Anything

How to make it as a Command Line Argument, Without Using Any Quotes.
I need it because I am implementing Cat command with python.

答:
Since by using >, you can print your Terminal or CMD output to a file, u need to use it with double quotations around
You need to use it like: python sample.py ">" 1 2

Body:
Python Program:

import sys

print(len(sys.argv))

Command Line:

Without '>' Operator

>>> python sample.py 1 2 3

Output:

4

With '>' Operator

>>> python sample.py > 1 2

Output:

Not Showing Anything

How to make it as a Command Line Argument, Without Using Any Quotes.
I need it because I am implementing Cat command with python.


问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答:
I think the earlier solutions are all valid, and it is more of a coding preference in terms of which layout managers to use. Based on your requirement, here is a working one with standard layout managers only (Grid, GridBag and Border). Have fun, - MS.

import java.awt.;
import javax.swing.;
import javax.swing.border.*;

public class GeneDialog extends JDialog {

```<code>private String[]    plusMinus = {"+","-"}, tfNames = {
                "Symbol", "Chromosome", "Start position", "Stop position"},
            listData = {"Gene01", "Gene02", "Gene03", "Gene04", "Gene05", "Gene06",
                "Gene07", "Gene08", "Gene09", "Gene10", "Gene11", "Gene12"};
private JTextField[]    gtField= new JTextField[tfNames.length];
private JList       list = new JList (new DefaultListModel());

    public GeneDialog (Frame f, String title) {
    super (f, title, true);
    Container cp = getContentPane();
    cp.setLayout (new GridLayout(1,2));
    JScrollPane listScrollPane = new JScrollPane (list);
    listScrollPane.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createTitledBorder("Genes"),
                    BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    DefaultListModel lm = (DefaultListModel) list.getModel();
    for (int k = 0 ; k < listData.length ; k++)
        lm.addElement (listData[k]);
    cp.add (listScrollPane);
    cp.add (controlPanel());
    pack();
    }

private GridBagConstraints makeGBC (int inset) {
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets (inset, inset, inset, inset);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;
    return gbc;
}

private JPanel controlPanel() {
    JPanel cp = new JPanel (new BorderLayout()),
           bp = new JPanel (new GridBagLayout()),
           tp = new JPanel (new GridBagLayout());

    GridBagConstraints gbc = makeGBC (10);
    for (int i = 0 ; i < tfNames.length ; i++) {
        JLabel label = new JLabel (tfNames[i], JLabel.TRAILING);
        tp.add (label, gbc);
    }
    gbc.gridx++; gbc.weightx = 1.0f;
    for (int i = 0 ; i < tfNames.length ; i++) {
        gtField[i] = new JTextField(12);
        tp.add (gtField[i], gbc);
    }

    gbc = makeGBC (10);
    for (int i = 0 ; i < plusMinus.length ; i++) {
        JButton b = new JButton (plusMinus[i]);
        bp.add (b, gbc);
        gbc.gridx++;
    }

    cp.add (tp, "Center");
    cp.add (bp, "South");
    return cp;
}

public static void main (String[] args) {
    new GeneDialog (null, "Genes").setVisible (true);
</code>```

}}

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();

Body:
I think the earlier solutions are all valid, and it is more of a coding preference in terms of which layout managers to use. Based on your requirement, here is a working one with standard layout managers only (Grid, GridBag and Border). Have fun, - MS.

import java.awt.;
import javax.swing.;
import javax.swing.border.*;

public class GeneDialog extends JDialog {

private String[]    plusMinus = {"+","-"}, tfNames = {
                "Symbol", "Chromosome", "Start position", "Stop position"},
            listData = {"Gene01", "Gene02", "Gene03", "Gene04", "Gene05", "Gene06",
                "Gene07", "Gene08", "Gene09", "Gene10", "Gene11", "Gene12"};
private JTextField[]    gtField= new JTextField[tfNames.length];
private JList       list = new JList (new DefaultListModel());

    public GeneDialog (Frame f, String title) {
    super (f, title, true);
    Container cp = getContentPane();
    cp.setLayout (new GridLayout(1,2));
    JScrollPane listScrollPane = new JScrollPane (list);
    listScrollPane.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createTitledBorder("Genes"),
                    BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    DefaultListModel lm = (DefaultListModel) list.getModel();
    for (int k = 0 ; k < listData.length ; k++)
        lm.addElement (listData[k]);
    cp.add (listScrollPane);
    cp.add (controlPanel());
    pack();
    }

private GridBagConstraints makeGBC (int inset) {
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets (inset, inset, inset, inset);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;
    return gbc;
}

private JPanel controlPanel() {
    JPanel cp = new JPanel (new BorderLayout()),
           bp = new JPanel (new GridBagLayout()),
           tp = new JPanel (new GridBagLayout());

    GridBagConstraints gbc = makeGBC (10);
    for (int i = 0 ; i < tfNames.length ; i++) {
        JLabel label = new JLabel (tfNames[i], JLabel.TRAILING);
        tp.add (label, gbc);
    }
    gbc.gridx++; gbc.weightx = 1.0f;
    for (int i = 0 ; i < tfNames.length ; i++) {
        gtField[i] = new JTextField(12);
        tp.add (gtField[i], gbc);
    }

    gbc = makeGBC (10);
    for (int i = 0 ; i < plusMinus.length ; i++) {
        JButton b = new JButton (plusMinus[i]);
        bp.add (b, gbc);
        gbc.gridx++;
    }

    cp.add (tp, "Center");
    cp.add (bp, "South");
    return cp;
}

public static void main (String[] args) {
    new GeneDialog (null, "Genes").setVisible (true);

}}


问:
How can I put a link on the right side?
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download
</p></code>```

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

答:
This is easy with flexbox!

html :

```<code><div class="container">
    <span>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor deleniti labore voluptatem eum, delectus aperiam, qui culpa voluptate adipisci ipsum. Doloribus labore facilis id inventore omnis reprehenderit perferendis unde aspernatur.
    </span>
    <a href="#">Download</a>
</div>
</code>```

css :

```<code>.container{
  display:flex;
}
.container >p{
  flex:1;
}
.container >a{
  flex:1;
}
</code>```

https://jsfiddle.net/tfyrf630/

Title: How can I put a link on the right side?

Body:
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}

some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

Body:
This is easy with flexbox!

html :

<div class="container">
    <span>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor deleniti labore voluptatem eum, delectus aperiam, qui culpa voluptate adipisci ipsum. Doloribus labore facilis id inventore omnis reprehenderit perferendis unde aspernatur.
    </span>
    <a href="#">Download</a>
</div>

css :

.container{
  display:flex;
}
.container >p{
  flex:1;
}
.container >a{
  flex:1;
}

https://jsfiddle.net/tfyrf630/