问:
Why the Thread Executer itself is still in memory after being shutdown?
Using Java and App Server I deploy application that has a thread executer.

During un-deploy I request the executer to shutdown. This successfully cancels all the tasks. However via VisualVM I can still see a thread that represents the executer itself and it is in the wait sate. I don't keep any references to the executer as the whole application get undeployed. So if i repeat the deployment-undeployment cycle multiple times I can see how the threads number grows.

How do I get rid of them?

UPDATE:

code example

here is the code:

```<code>public void startScheduler()
{
    if (scheduledExecutor == null)
    {
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("My ScheduledExecutor"));
        processFuture = scheduledExecutor.scheduleAtFixedRate(new Runnable()
            {
                @Override
                public void run()
                {
                    startProcessor();
                }
            }, 0, 84600, TimeUnit.SECONDS);
    }
}

public void stopScheduler()
{

    if (processFuture != null)
    {
        processFuture.cancel(true);
        processFuture = null;
    }

    if (scheduledExecutor != null)
    {
        try
        {
            scheduledExecutor.shutdownNow();
            scheduledExecutor.awaitTermination(10, TimeUnit.SECONDS);
        }
        catch (InterruptedException ignored)
        {}
        finally
        {
            scheduledExecutor = null;
        }
    }

}
</code>```

答:
The Executor needs to be stopped explicitly, using the method shutdown, otherwise it will hang around like you have found out. You can see from the javadoc for Executors.newSingleThreadExecutor that it includes a worker thread.

The javadoc for shutdownNow says:

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so if any tasks mask or fail to respond to interrupts, they may never terminate.

If the task being executed doesn't respond to interrupts (swallows InterruptedExceptions without ever exiting), then that would cause your executor to never get shutdown. Any non-daemon threads that don't get shutdown explicitly will hang around and keep the JVM from exiting. That can be a fun one to debug.

Body:
Using Java and App Server I deploy application that has a thread executer.

During un-deploy I request the executer to shutdown. This successfully cancels all the tasks. However via VisualVM I can still see a thread that represents the executer itself and it is in the wait sate. I don't keep any references to the executer as the whole application get undeployed. So if i repeat the deployment-undeployment cycle multiple times I can see how the threads number grows.

How do I get rid of them?

UPDATE:

code example

here is the code:

public void startScheduler()
{
    if (scheduledExecutor == null)
    {
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("My ScheduledExecutor"));
        processFuture = scheduledExecutor.scheduleAtFixedRate(new Runnable()
            {
                @Override
                public void run()
                {
                    startProcessor();
                }
            }, 0, 84600, TimeUnit.SECONDS);
    }
}

public void stopScheduler()
{

    if (processFuture != null)
    {
        processFuture.cancel(true);
        processFuture = null;
    }

    if (scheduledExecutor != null)
    {
        try
        {
            scheduledExecutor.shutdownNow();
            scheduledExecutor.awaitTermination(10, TimeUnit.SECONDS);
        }
        catch (InterruptedException ignored)
        {}
        finally
        {
            scheduledExecutor = null;
        }
    }

}


来源: stackexchange

问:
Modal memory leak as more modals added
I am developing an Angular 4 application using ngx-bootstrap modals heavily. I am currently using the template + modalService way of opening up modals. During a click event, this line of code is called:

```<code>@ViewChild() worklistTemplate;
// ...
this.modalRef = this.modalService.show(this.worklistTemplate, this.config);
</code>```

And the worklist template looks like this:

```<code><ng-template #worklistTemplate>
  <app-action-view
    [leftButtons]="leftButtons"
    [labelHeader]="modalHeader"
    [labelIcon]="modalIcon"
    [modalRef]="modalRef">
    <div class="row modal-info-panel">
      <div class="col-xs-4 modal-user-info">
        <fa name="mars" class="gender-icon"></fa>
        <div class="field-panel">
          <input type="text"
            [ngModel]="rowInfo.lastName"
            [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
            [disabled]="!modalFieldsEditable">
          <input type="text"
            [ngModel]="rowInfo.firstName"
            [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
            [disabled]="!modalFieldsEditable">
          <div>
            <label for="modal-mrn">MRN --</label>
            <input id="modal-mrn" type="text"
              [ngModel]="rowInfo.mrn"
              [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
              [disabled]="!modalFieldsEditable">
          </div>
          <div>
            <label for="modal-dob">DOB --</label>
            <input id="modal-dob" type="text"
              [ngModel]="rowInfo.birthDate"
              [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
              [disabled]="!modalFieldsEditable">
          </div>
          <div class="edit-panel">
            <fa *ngIf=modalFieldsEditable class="worklist-edit-buttons green-hover link" name="floppy-o" tooltip="Save" (click)=saveChanges()></fa>
            <fa *ngIf=modalFieldsEditable class="worklist-edit-buttons red-hover link" name="times" tooltip="Cancel" (click)=toggleModalFields()></fa>
          </div>
        </div>
      </div>
      <div class="col-xs-8 modal-id-info">
        Associated ID
        <div class="full-width">
          <div class="row" *ngFor="let i of rowInfo.associatedIDs">
            <div class="col-xs-6 cell">{{i.id}}</div><div class="col-xs-6 cell">{{i.source}}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="row" id="modal-table">
      <app-table-view
            [columns]="objDetailsCols"
            [tableData]="objDetailsData"
            [expandTemplate]="rowImageContainer"
            [expandColStyle]="expandColStyle">
      </app-table-view>
    </div>
    <div *ngIf="resolvePanelVisible" class="resolve-panel"
      [@slideRight]>
      <div class="resolve-label">
        <fa class="lt-icon" name="wrench"></fa>
        Resolve QA Issue
      </div>
      <div class="resolve-body">
        Hello, World!
      </div>
      <div class="resolve-footer">
        <a>Validate</a>
        <a>Resolve</a>
        <a>Reload</a>
        <a (click)="toggleResolvePanel()">Close</a>
      </div>
    </div>
  </app-action-view>
</ng-template>
</code>```

The modal can be closed by clicking outside of the modal boundaries or there is a button inside the ActionViewComponent that calls modalRef.hide().

Memory usage increases drastically as more and more modals are opened. In fact, if I open the modal around 5 times, the application becomes sluggish and almost unusable. This is especially apparent if there are many rows in our TableViewComponent.

Is there a problem with the way I am using the modals, or is this an issue related to ngx-bootstrap modals? OR, is the issue related to the browser and unavoidable? I am developing on Chrome 62 right now.

I have verified that onDestroy is never called on the TableViewComponent inside the modal. It is not even called if I navigate to a different page component, though another table (not in the template) does have onDestroy called when navigating from the page.

Any feedback is appreciated greatly- I have been stuck for way too long on this.

答: This is an issue of ngx-bootstrap, unfortunately. I created a pull request (https://github.com/valor-software/ngx-bootstrap/pull/3179) so this will be fixed as soon as my PR is merged and new version is released.</p>

ContentLicense: CC BY-SA 3.0

Title: Modal memory leak as more modals added

Body:
I am developing an Angular 4 application using ngx-bootstrap modals heavily. I am currently using the template + modalService way of opening up modals. During a click event, this line of code is called:

@ViewChild() worklistTemplate;
// ...
this.modalRef = this.modalService.show(this.worklistTemplate, this.config);

And the worklist template looks like this:

<ng-template #worklistTemplate>
  <app-action-view
    [leftButtons]="leftButtons"
    [labelHeader]="modalHeader"
    [labelIcon]="modalIcon"
    [modalRef]="modalRef">

        <fa name="mars" class="gender-icon"></fa>

          <input type="text"
            [ngModel]="rowInfo.lastName"
            [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
            [disabled]="!modalFieldsEditable">
          <input type="text"
            [ngModel]="rowInfo.firstName"
            [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
            [disabled]="!modalFieldsEditable">

            MRN --
            <input id="modal-mrn" type="text"
              [ngModel]="rowInfo.mrn"
              [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
              [disabled]="!modalFieldsEditable">

            DOB --
            <input id="modal-dob" type="text"
              [ngModel]="rowInfo.birthDate"
              [ngClass]="{ 'modal-editable-field': modalFieldsEditable }"
              [disabled]="!modalFieldsEditable">

            <fa *ngIf=modalFieldsEditable class="worklist-edit-buttons green-hover link" name="floppy-o" tooltip="Save" (click)=saveChanges()></fa>
            <fa *ngIf=modalFieldsEditable class="worklist-edit-buttons red-hover link" name="times" tooltip="Cancel" (click)=toggleModalFields()></fa>

        Associated ID

{{i.id}}

{{i.source}}

      <app-table-view
            [columns]="objDetailsCols"
            [tableData]="objDetailsData"
            [expandTemplate]="rowImageContainer"
            [expandColStyle]="expandColStyle">
      </app-table-view>

        <fa class="lt-icon" name="wrench"></fa>
        Resolve QA Issue

        Hello, World!

        Validate
        Resolve
        Reload
        Close

  </app-action-view>
</ng-template>

The modal can be closed by clicking outside of the modal boundaries or there is a button inside the ActionViewComponent that calls modalRef.hide().

Memory usage increases drastically as more and more modals are opened. In fact, if I open the modal around 5 times, the application becomes sluggish and almost unusable. This is especially apparent if there are many rows in our TableViewComponent.

Is there a problem with the way I am using the modals, or is this an issue related to ngx-bootstrap modals? OR, is the issue related to the browser and unavoidable? I am developing on Chrome 62 right now.

I have verified that onDestroy is never called on the TableViewComponent inside the modal. It is not even called if I navigate to a different page component, though another table (not in the template) does have onDestroy called when navigating from the page.

Any feedback is appreciated greatly- I have been stuck for way too long on this.


问:
how to sign bytes using my own rsa private key using rs256 algorithm?
I have my own private key string, i.e.

```<code>-----BEGIN RSA PRIVATE KEY-----

MIICXAIBAAKBgQCSAYYgzvGTww....
....
....
.....
3yUMYj9oYzqdrRHP0XgD0cEEvyqPBwLaNsRdFwy5qTiHjj0f+ZWHQWmqcoLmmpzyZEbIvQm/VhbjRF6iKG4WZ9Hfa7ntYRNGdWgD/KMIeZI=

-----END RSA PRIVATE KEY-----
</code>```

Now, I need to sign my claim set using this private key in C# to generate JWT payload.

I have written the following code:

```<code>var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var issueTime = DateTime.Now;

var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

var payload = new
{
    iss = email,
    prn = prn,
    scope = "scope",
    aud = "https://example.com",
    exp = exp,
    iat = iat
};

var segments = new List<string>();
var header = new { typ = "JWT", alg = "RS256" };

byte[] headerBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(header));
byte[] payloadBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(payload));

segments.Add(Base64UrlEncode(headerBytes));
segments.Add(Base64UrlEncode(payloadBytes));

var stringToSign = string.Join(".", segments.ToArray());

var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
</code>```

Now I need these bytesToSign to be signed by my private key as I mentioned above using the rs256 alogorithm. Can anyone help?

I've updated my code as per the following:

```<code>var pemprivatekey = OpenSSLKey.DecodeOpenSSLPrivateKey(privateKey);
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

if (pemprivatekey != null)
{
    rsaProvider = OpenSSLKey.DecodeRSAPrivateKey(pemprivatekey);
}

byte[] signature = rsaProvider.SignData(bytesToSign, "SHA256");

segments.Add(Base64UrlEncode(signature));

return string.Join(".", segments.ToArray());
</code>```

and generated JWT token. Please let me know where I made a mistake as its not correct one: when I pass it to the API, it doesn't work and throws an error.

答:
I'll list my answer in steps

For this, you'll need to install a package to get a library called Jose-jwt. this stands for JavaScript Object Signing and Encrypting. Install the package from the NuGet package manager, Install-package Jose-jwt

Using OpenSSL, pack your private key in the form of a PKCS12 file (*.p12), you'll set a password for the file in the process.

```<code>openssl pkcs12 -export -nocerts -in ./myKey.key -out my-Key.p12
</code>```

as listed on the Library's readme, you'll need to generate an RSACryptoServiceProvider from that file, like this:

```<code>var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
</code>```

Use the RSACryptoServiceProvider createdalong with the password set up during the PKCS12 packing to encode your payload like this:

```<code>string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
</code>```

Body:
I have my own private key string, i.e.

-----BEGIN RSA PRIVATE KEY-----

MIICXAIBAAKBgQCSAYYgzvGTww....
....
....
.....
3yUMYj9oYzqdrRHP0XgD0cEEvyqPBwLaNsRdFwy5qTiHjj0f+ZWHQWmqcoLmmpzyZEbIvQm/VhbjRF6iKG4WZ9Hfa7ntYRNGdWgD/KMIeZI=

-----END RSA PRIVATE KEY-----

Now, I need to sign my claim set using this private key in C# to generate JWT payload.

I have written the following code:

var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var issueTime = DateTime.Now;

var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

var payload = new
{
    iss = email,
    prn = prn,
    scope = "scope",
    aud = "https://example.com",
    exp = exp,
    iat = iat
};

var segments = new List<string>();
var header = new { typ = "JWT", alg = "RS256" };

byte[] headerBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(header));
byte[] payloadBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(payload));

segments.Add(Base64UrlEncode(headerBytes));
segments.Add(Base64UrlEncode(payloadBytes));

var stringToSign = string.Join(".", segments.ToArray());

var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

Now I need these bytesToSign to be signed by my private key as I mentioned above using the rs256 alogorithm. Can anyone help?

I've updated my code as per the following:

var pemprivatekey = OpenSSLKey.DecodeOpenSSLPrivateKey(privateKey);
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

if (pemprivatekey != null)
{
    rsaProvider = OpenSSLKey.DecodeRSAPrivateKey(pemprivatekey);
}

byte[] signature = rsaProvider.SignData(bytesToSign, "SHA256");

segments.Add(Base64UrlEncode(signature));

return string.Join(".", segments.ToArray());

and generated JWT token. Please let me know where I made a mistake as its not correct one: when I pass it to the API, it doesn't work and throws an error.

Body:
I'll list my answer in steps

For this, you'll need to install a package to get a library called Jose-jwt. this stands for JavaScript Object Signing and Encrypting. Install the package from the NuGet package manager, Install-package Jose-jwt

Using OpenSSL, pack your private key in the form of a PKCS12 file (*.p12), you'll set a password for the file in the process.

openssl pkcs12 -export -nocerts -in ./myKey.key -out my-Key.p12

as listed on the Library's readme, you'll need to generate an RSACryptoServiceProvider from that file, like this:

var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;

Use the RSACryptoServiceProvider createdalong with the password set up during the PKCS12 packing to encode your payload like this:

string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);


问:
What is the best way to achieve following design (attached image)?
All,

I know this is not difficult one, But I just want to know that which is the best way to achieve . You can see two icons exactly between two layouts (blackish and white). I know we can achieve this using margin but is there any other better way ?

P.S To clarify the confusion this is what my entire screen should look like

Thanks in advance.
Answer will be appreciated.

答:
You can Achieve that Design using RelativeLayout

Try this

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/nilu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccentJob"
            android:orientation="vertical"
            android:paddingBottom="30dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/nilu2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/nilu"
            android:background="@color/colorAccentAdhoc"
            android:orientation="vertical"
            android:paddingTop="30dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/nilu"
            android:layout_marginTop="-15dp"
            android:orientation="horizontal">

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="16dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_toStartOf="@+id/floatingActionButton"
                android:src="@mipmap/ic_launcher_round"
                app:elevation="2dp" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/floatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="139dp"
                android:layout_marginRight="30dp"
                android:src="@mipmap/ic_launcher" />

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>
</code>```

Body:
You can Achieve that Design using RelativeLayout

Try this

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/nilu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccentJob"
            android:orientation="vertical"
            android:paddingBottom="30dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/nilu2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/nilu"
            android:background="@color/colorAccentAdhoc"
            android:orientation="vertical"
            android:paddingTop="30dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="NILU" />

        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/nilu"
            android:layout_marginTop="-15dp"
            android:orientation="horizontal">

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="16dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_toStartOf="@+id/floatingActionButton"
                android:src="@mipmap/ic_launcher_round"
                app:elevation="2dp" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/floatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="139dp"
                android:layout_marginRight="30dp"
                android:src="@mipmap/ic_launcher" />

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>


问:
How do I make the "action" of this card game keep executing until a winner is found?
I created this card game that asks the user for an action. "attack" and "swap". they both work fine on the first execution, but how do I make it so that the system keeps asking the user for an action until one of the player wins?

This contains my code for the class GameMaster that the GameConsole will reference. It has links to two other classes I have called Player and Card.

```<code>import java.util.*;
public class GameMaster
{
private int turnCounter = 0;
private ArrayList<Card> deck;
private boolean isThereWinner;
private Player player1;
private Player player2;
public GameMaster (Player a, Player b) //initializes values
{
    turnCounter = turnCounter + 1;
    player1 = a;
    player2 = b;
    deck = new ArrayList<Card>();
    assembleDeck();
    dealCard();
}
private void assembleDeck() //given order of cards
{
    deck.add( new Card( "Dragon", "Aquira", 174, 26 ) );
    deck.add( new Card( "Ghost", "Brawn", 130, 48 ) );
    deck.add( new Card( "Fairy", "Cerulea", 162, 29 ) );
    deck.add( new Card( "Dragon", "Demi", 147, 28 ) );
    deck.add( new Card( "Ghost", "Elba", 155, 37 ) );
    deck.add( new Card( "Fairy", "Fye", 159, 42 ) );
    deck.add( new Card( "Dragon", "Glyede", 129, 26 ) );
    deck.add( new Card( "Ghost", "Hydran", 163, 35 ) );
    deck.add( new Card( "Fairy", "Ivy", 146, 45 ) );
    deck.add( new Card( "Dragon", "Jet", 170, 24 ) );
    deck.add( new Card( "Ghost", "Kineti", 139, 21 ) );
    deck.add( new Card( "Fairy", "Levi", 160, 43 ) );
    deck.add( new Card( "Dragon", "Meadow", 134, 29 ) );
    deck.add( new Card( "Ghost", "Naidem", 165, 26 ) );
    deck.add( new Card( "Fairy", "Omi", 145, 21 ) );
    deck.add( new Card( "Dragon", "Puddles", 170, 34 ) );
    deck.add( new Card( "Ghost", "Quarrel", 151, 29 ) );
    deck.add( new Card( "Fairy", "Raven", 168, 32 ) );
    deck.add( new Card( "Dragon", "Surge", 128, 27 ) );
    deck.add( new Card( "Ghost", "Takiru", 140, 26 ) );
    deck.add( new Card( "Fairy", "Ustelia", 163, 47 ) );
    deck.add( new Card( "Dragon", "Verwyn", 145, 25 ) );
    deck.add( new Card( "Ghost", "Wyverin", 158, 32 ) );
    deck.add( new Card( "Fairy", "Xios", 155, 27 ) );
    deck.add( new Card( "Dragon", "Yora", 159, 44 ) );
    deck.add( new Card( "Ghost", "Zulu", 125, 46 ) );
}
public java.lang.String play (java.lang.String action) // lets player enter action swap or attack
{
   if (turnCounter%2==1) //player 1's turn
   {
        if (action.equals("swap")) // if player one enters "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " swaps out " + player1.getActiveCard().getName()+".");
            player1.swap();

        }
        else if (action.equals("attack")) // if player one enter "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " attacks with " + player1.getActiveCard().getName()+".");
            dealDamage(player1.getActiveCard(), player2.getActiveCard());

            if (player2.getActiveCard().getHealth()<1) //if player 2's health goes below 1
            {
                player2.discard();
                System.out.println("   "+player2.getName() + " discards " + player2.getActiveCard().getName());
                player2.drawCard(deck.get(0));
                System.out.println(player2.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) // if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player1.claimToken();
                System.out.println("   "+player1.getName() + " gets a token!");
                if (player1.getTokens()==3) //if player1 kills three of player2's cards = 3 tokens
                {
                    hasWinner();
                    System.out.println(player1.getName() + " wins!");
                }
            }
        }
    }
    else if (turnCounter%2==0) //player 2's turn
    {
        if (action.equals("swap")) //if player 2 chooses "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getActiveCard().getName() + " swaps out " + player2.getActiveCard().getName());
            player2.swap();

        }
        else if (action.equals("attack")) //if player two chooses "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getName() + " attacks with " + player2.getActiveCard());
            dealDamage(player2.getActiveCard(), player1.getActiveCard());
            if (player1.getActiveCard().getHealth()<1) //if player 1's health drops below 1
            {
                player1.discard();
                System.out.println("   "+player1.getName() + " discards " + player1.getActiveCard().getName());
                player1.drawCard(deck.get(0));
                System.out.println("   "+player1.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) //if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player2.claimToken();
                System.out.println("   "+player2.getName() + " gets a token!");
                if (player2.getTokens()==3) //if player 2 kills 3 of player1's cards = get three tokens
                {
                    hasWinner();
                    System.out.println(player2.getName() + " wins!");
                }
            }

        }

   }
   return "";
}
public boolean checkResistance(java.lang.String type1, java.lang.String type2) //checks for resistance
{
    if (type1.equals("Dragon")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public boolean checkWeakness(java.lang.String type1, java.lang.String type2) //checks for weakness
{
    if (type1.equals("Dragon")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public java.lang.String dealCard() //altertately deals cards to each player at the start of the game
{
    if (turnCounter==1)
    {
        for (int i=0; i<5; i++)
        {
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(i).getName()+".");
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(i).getName()+".");
        }
    }
    else if (turnCounter%2==1) //odd turns = player 1
    {
        if (player1.playerHand.size()==5)
        {
            System.out.println(player1.getName() + "'s hand is full.");
        }
        else if (player1.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter + 1;
    }
    else if (turnCounter%2==0) //even turns = player2
    {
        if (player2.playerHand.size()==5)
        {
            System.out.println(player2.getName() + "'s hand is full.");
        }
        else if (player2.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter;
    }

    return "";
}
public java.lang.String dealDamage(Card inPlay, Card target) //calculates how much damage a card receives, taking into account weakness and resistance
{
    if (checkResistance(target.getType(),inPlay.getType())==true) //if there is resistance
    {
        System.out.println("      "+target.getType() +" is resistant to "+inPlay.getType()+".");
        target.takeHalfDamage(inPlay.getPower());
        checkResistance(inPlay.getType(),target.getType());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()/2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else if (checkWeakness(target.getType(),inPlay.getType())==true) //if there is weakness
    {
        System.out.println("      "+target.getType() +" is weak to "+inPlay.getType()+".");
        target.takeDoubleDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()*2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else //if it does normal damage
    {
        target.takeDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    return "";
}
public boolean hasWinner() //as long as there is no winner, it is false
{
    return true;
}
public java.lang.String gameReport() //prints out a summary of a game as well as each player's stats
{
    System.out.println("___=== GAME SUMMARY ===___");
    System.out.println("This game lasted "+turnCounter+" turns.");
    System.out.println();
    System.out.println(player1.getName());
    System.out.println("        "+player1.statusReport());
    System.out.println();
    System.out.println(player2.getName());
    System.out.println("        "+player2.statusReport());
    return "";

}
</code>```

This is the runner I currently have called GameConsole.

```<code>import java.util.Scanner;
public class GameConsole
{
    public static void main (String[] args)
    {
    Scanner player = new Scanner(System.in);
    System.out.print("Player 1: ");
    String player1String = player.next(); // input player1 name
    System.out.print("Player 2: ");
    String player2String = player.next(); // input player2 name
    System.out.println("Welcome, "+player1String+" and "+player2String+"!");
    System.out.println("The game begins.");
    Player player1 = new Player(player1String); // turns player1's String name into an object
    Player player2 = new Player(player2String); // turns player2's Strign name into an object
    System.out.println();
    GameMaster game = new GameMaster(player1,player2); // uses the player1 and player2 objects as objects for the GameMAster
    System.out.println();
    Scanner move = new Scanner(System.in);
    System.out.print("Attack or Swap? ");
    String whatMove = move.next(); //input for action

    //i tried putting this in a while-loop but the action won't even execute once
    game.play(whatMove); // executes play for action
    }
}
</code>```

When I run it, this is what happens //user input is in ALL CAPS

```<code>Player 1: ADAM
Player 2: BOB
Welcome, ADAM and BOB!
The game begins.
//space
ADAM draws Aquira.
BOB draws Brawn.
ADAM draws Cerulea.
BOB draws Demi.
ADAM draws Elba.
BOB draws Fye.
ADAM draws Glyede.
BOB draws Hydran.
ADAM draws Ivy.
BOB draws Jet.
//space
Attack or Swap? ATTACK    //SWAP works fine too
   ADAM attacks with Aquira.
      Ghost is weak to Dragon.
   Aquira deals 52 damage on Brawn.
   Brawn has 78 left.
//and then it just stops
</code>```

tbh I'm not completely sure if my code works, but because I don't know how to repeat the action, I wouldn't know...I hope what I said made sense...I'm new to CS so I would appreciate any amount of help.

答:
Replace the last couple lines with this:

```<code>String whatMove = "QUIT";
do {
    whatMove = move.next(); //input for action
    (whatMove.equalsIgnoreCase("QUIT")) ? break : game.play(whatMove);
} while (true);
</code>```

This gives you a loop and a command option to end play mid-game.

Body:
I created this card game that asks the user for an action. "attack" and "swap". they both work fine on the first execution, but how do I make it so that the system keeps asking the user for an action until one of the player wins?

This contains my code for the class GameMaster that the GameConsole will reference. It has links to two other classes I have called Player and Card.

import java.util.*;
public class GameMaster
{
private int turnCounter = 0;
private ArrayList<Card> deck;
private boolean isThereWinner;
private Player player1;
private Player player2;
public GameMaster (Player a, Player b) //initializes values
{
    turnCounter = turnCounter + 1;
    player1 = a;
    player2 = b;
    deck = new ArrayList<Card>();
    assembleDeck();
    dealCard();
}
private void assembleDeck() //given order of cards
{
    deck.add( new Card( "Dragon", "Aquira", 174, 26 ) );
    deck.add( new Card( "Ghost", "Brawn", 130, 48 ) );
    deck.add( new Card( "Fairy", "Cerulea", 162, 29 ) );
    deck.add( new Card( "Dragon", "Demi", 147, 28 ) );
    deck.add( new Card( "Ghost", "Elba", 155, 37 ) );
    deck.add( new Card( "Fairy", "Fye", 159, 42 ) );
    deck.add( new Card( "Dragon", "Glyede", 129, 26 ) );
    deck.add( new Card( "Ghost", "Hydran", 163, 35 ) );
    deck.add( new Card( "Fairy", "Ivy", 146, 45 ) );
    deck.add( new Card( "Dragon", "Jet", 170, 24 ) );
    deck.add( new Card( "Ghost", "Kineti", 139, 21 ) );
    deck.add( new Card( "Fairy", "Levi", 160, 43 ) );
    deck.add( new Card( "Dragon", "Meadow", 134, 29 ) );
    deck.add( new Card( "Ghost", "Naidem", 165, 26 ) );
    deck.add( new Card( "Fairy", "Omi", 145, 21 ) );
    deck.add( new Card( "Dragon", "Puddles", 170, 34 ) );
    deck.add( new Card( "Ghost", "Quarrel", 151, 29 ) );
    deck.add( new Card( "Fairy", "Raven", 168, 32 ) );
    deck.add( new Card( "Dragon", "Surge", 128, 27 ) );
    deck.add( new Card( "Ghost", "Takiru", 140, 26 ) );
    deck.add( new Card( "Fairy", "Ustelia", 163, 47 ) );
    deck.add( new Card( "Dragon", "Verwyn", 145, 25 ) );
    deck.add( new Card( "Ghost", "Wyverin", 158, 32 ) );
    deck.add( new Card( "Fairy", "Xios", 155, 27 ) );
    deck.add( new Card( "Dragon", "Yora", 159, 44 ) );
    deck.add( new Card( "Ghost", "Zulu", 125, 46 ) );
}
public java.lang.String play (java.lang.String action) // lets player enter action swap or attack
{
   if (turnCounter%2==1) //player 1's turn
   {
        if (action.equals("swap")) // if player one enters "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " swaps out " + player1.getActiveCard().getName()+".");
            player1.swap();

        }
        else if (action.equals("attack")) // if player one enter "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " attacks with " + player1.getActiveCard().getName()+".");
            dealDamage(player1.getActiveCard(), player2.getActiveCard());

            if (player2.getActiveCard().getHealth()<1) //if player 2's health goes below 1
            {
                player2.discard();
                System.out.println("   "+player2.getName() + " discards " + player2.getActiveCard().getName());
                player2.drawCard(deck.get(0));
                System.out.println(player2.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) // if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player1.claimToken();
                System.out.println("   "+player1.getName() + " gets a token!");
                if (player1.getTokens()==3) //if player1 kills three of player2's cards = 3 tokens
                {
                    hasWinner();
                    System.out.println(player1.getName() + " wins!");
                }
            }
        }
    }
    else if (turnCounter%2==0) //player 2's turn
    {
        if (action.equals("swap")) //if player 2 chooses "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getActiveCard().getName() + " swaps out " + player2.getActiveCard().getName());
            player2.swap();

        }
        else if (action.equals("attack")) //if player two chooses "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getName() + " attacks with " + player2.getActiveCard());
            dealDamage(player2.getActiveCard(), player1.getActiveCard());
            if (player1.getActiveCard().getHealth()<1) //if player 1's health drops below 1
            {
                player1.discard();
                System.out.println("   "+player1.getName() + " discards " + player1.getActiveCard().getName());
                player1.drawCard(deck.get(0));
                System.out.println("   "+player1.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) //if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player2.claimToken();
                System.out.println("   "+player2.getName() + " gets a token!");
                if (player2.getTokens()==3) //if player 2 kills 3 of player1's cards = get three tokens
                {
                    hasWinner();
                    System.out.println(player2.getName() + " wins!");
                }
            }

        }

   }
   return "";
}
public boolean checkResistance(java.lang.String type1, java.lang.String type2) //checks for resistance
{
    if (type1.equals("Dragon")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public boolean checkWeakness(java.lang.String type1, java.lang.String type2) //checks for weakness
{
    if (type1.equals("Dragon")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public java.lang.String dealCard() //altertately deals cards to each player at the start of the game
{
    if (turnCounter==1)
    {
        for (int i=0; i<5; i++)
        {
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(i).getName()+".");
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(i).getName()+".");
        }
    }
    else if (turnCounter%2==1) //odd turns = player 1
    {
        if (player1.playerHand.size()==5)
        {
            System.out.println(player1.getName() + "'s hand is full.");
        }
        else if (player1.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter + 1;
    }
    else if (turnCounter%2==0) //even turns = player2
    {
        if (player2.playerHand.size()==5)
        {
            System.out.println(player2.getName() + "'s hand is full.");
        }
        else if (player2.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter;
    }

    return "";
}
public java.lang.String dealDamage(Card inPlay, Card target) //calculates how much damage a card receives, taking into account weakness and resistance
{
    if (checkResistance(target.getType(),inPlay.getType())==true) //if there is resistance
    {
        System.out.println("      "+target.getType() +" is resistant to "+inPlay.getType()+".");
        target.takeHalfDamage(inPlay.getPower());
        checkResistance(inPlay.getType(),target.getType());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()/2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else if (checkWeakness(target.getType(),inPlay.getType())==true) //if there is weakness
    {
        System.out.println("      "+target.getType() +" is weak to "+inPlay.getType()+".");
        target.takeDoubleDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()*2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else //if it does normal damage
    {
        target.takeDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    return "";
}
public boolean hasWinner() //as long as there is no winner, it is false
{
    return true;
}
public java.lang.String gameReport() //prints out a summary of a game as well as each player's stats
{
    System.out.println("___=== GAME SUMMARY ===___");
    System.out.println("This game lasted "+turnCounter+" turns.");
    System.out.println();
    System.out.println(player1.getName());
    System.out.println("        "+player1.statusReport());
    System.out.println();
    System.out.println(player2.getName());
    System.out.println("        "+player2.statusReport());
    return "";

}

This is the runner I currently have called GameConsole.

import java.util.Scanner;
public class GameConsole
{
    public static void main (String[] args)
    {
    Scanner player = new Scanner(System.in);
    System.out.print("Player 1: ");
    String player1String = player.next(); // input player1 name
    System.out.print("Player 2: ");
    String player2String = player.next(); // input player2 name
    System.out.println("Welcome, "+player1String+" and "+player2String+"!");
    System.out.println("The game begins.");
    Player player1 = new Player(player1String); // turns player1's String name into an object
    Player player2 = new Player(player2String); // turns player2's Strign name into an object
    System.out.println();
    GameMaster game = new GameMaster(player1,player2); // uses the player1 and player2 objects as objects for the GameMAster
    System.out.println();
    Scanner move = new Scanner(System.in);
    System.out.print("Attack or Swap? ");
    String whatMove = move.next(); //input for action

    //i tried putting this in a while-loop but the action won't even execute once
    game.play(whatMove); // executes play for action
    }
}

When I run it, this is what happens //user input is in ALL CAPS

Player 1: ADAM
Player 2: BOB
Welcome, ADAM and BOB!
The game begins.
//space
ADAM draws Aquira.
BOB draws Brawn.
ADAM draws Cerulea.
BOB draws Demi.
ADAM draws Elba.
BOB draws Fye.
ADAM draws Glyede.
BOB draws Hydran.
ADAM draws Ivy.
BOB draws Jet.
//space
Attack or Swap? ATTACK    //SWAP works fine too
   ADAM attacks with Aquira.
      Ghost is weak to Dragon.
   Aquira deals 52 damage on Brawn.
   Brawn has 78 left.
//and then it just stops

tbh I'm not completely sure if my code works, but because I don't know how to repeat the action, I wouldn't know...I hope what I said made sense...I'm new to CS so I would appreciate any amount of help.

Body:
Replace the last couple lines with this:

String whatMove = "QUIT";
do {
    whatMove = move.next(); //input for action
    (whatMove.equalsIgnoreCase("QUIT")) ? break : game.play(whatMove);
} while (true);

This gives you a loop and a command option to end play mid-game.


问:
Localizable.strings - The data couldn’t be read because it isn’t in the correct format
If I copy something from textedit or web and paste it to localizable file it shows this compilation error. If I type those in localizable file it does not show any error. I am assuring you that I using the correct format and ';' in the file.</p>

```<code>"New" = "New";
"In Progress" = "In Progress";
"Waiting" = "Waiting";
"Closed" = "Closed";
</code>```

答: For me, it was missing semi-colons. If you use a tool to generate .strings file, make sure there are no un-escaped quotes that may 'eat' the delimiting semi-colons.

Body:
If I copy something from textedit or web and paste it to localizable file it shows this compilation error. If I type those in localizable file it does not show any error. I am assuring you that I using the correct format and ';' in the file.

"New" = "New";
"In Progress" = "In Progress";
"Waiting" = "Waiting";
"Closed" = "Closed";


问:
SQL Query to query data hierarchically in the same table
I have the following table, which has a list of subjects and objects related with the same relationship.

```
    |---------------------------------------|
    |Subject    |Relationship    |Object    |
    |---------------------------------------|
    |A          |x               |B         |
    |B          |x               |C         |
    |B          |x               |D         |
    |C          |x               |E         |
    |D          |x               |F         |
    |P          |x               |G         |
    |---------------------------------------|
```

My need is to write a SQL to get all the related Subjects and Objects given an initial subject.

For example:

If "C" is given as the initial subject, output should be "C" and "E" (because "C" related to "E" with "x")

If "A" is given as the initial subject, output should be "A", "B", "C", "D", "E" and "F". Explanation,

"A" is related to "B"

"B" is related to "C" and "D"

"C" is related to "E"

"D" is related to "F"

答:
You need to use recursion:

```<code>DECLARE @Subject char(1) = 'A'

;WITH cte AS (  -- Your table sample
    SELECT  [Subject],
            [Relationship],
            [Object]
    FROM (VALUES
    ('A' ,'x' ,'B'),
    ('B' ,'x' ,'C'),
    ('B' ,'x' ,'D'),
    ('C' ,'x' ,'E'),
    ('D' ,'x' ,'F'),
    ('P' ,'x' ,'G')
    ) as t([Subject],[Relationship],[Object])
), rec AS ( -- Recursive CTE
    SELECT [Object]
    FROM cte
    WHERE [Subject] = @Subject
    UNION ALL
    SELECT c.[Object]
    FROM cte c
    INNER JOIN rec r
        ON r.[Object] = c.[Subject]
)

SELECT @Subject
UNION ALL
SELECT *
FROM rec
</code>```

Output:

```<code>A
B
C
D
F
E
</code>```

Body:
I have the following table, which has a list of subjects and objects related with the same relationship.

    |---------------------------------------|
    |Subject    |Relationship    |Object    |
    |---------------------------------------|
    |A          |x               |B         |
    |B          |x               |C         |
    |B          |x               |D         |
    |C          |x               |E         |
    |D          |x               |F         |
    |P          |x               |G         |
    |---------------------------------------|

My need is to write a SQL to get all the related Subjects and Objects given an initial subject.

For example:

If "C" is given as the initial subject, output should be "C" and "E" (because "C" related to "E" with "x")

If "A" is given as the initial subject, output should be "A", "B", "C", "D", "E" and "F". Explanation,

"A" is related to "B"

"B" is related to "C" and "D"

"C" is related to "E"

"D" is related to "F"

Body:
You need to use recursion:

DECLARE @Subject char(1) = 'A'

;WITH cte AS (  -- Your table sample
    SELECT  [Subject],
            [Relationship],
            [Object]
    FROM (VALUES
    ('A' ,'x' ,'B'),
    ('B' ,'x' ,'C'),
    ('B' ,'x' ,'D'),
    ('C' ,'x' ,'E'),
    ('D' ,'x' ,'F'),
    ('P' ,'x' ,'G')
    ) as t([Subject],[Relationship],[Object])
), rec AS ( -- Recursive CTE
    SELECT [Object]
    FROM cte
    WHERE [Subject] = @Subject
    UNION ALL
    SELECT c.[Object]
    FROM cte c
    INNER JOIN rec r
        ON r.[Object] = c.[Subject]
)

SELECT @Subject
UNION ALL
SELECT *
FROM rec

Output:

A
B
C
D
F
E


问:
Nth max salary in Oracle
To find out the Nth max sal in oracle i'm using below query

```<code>SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;
</code>```

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

```<code>SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;
</code>```

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

答:
```<code>select min(sal) from (select distinct(sal) from emp  order by sal desc) where rownum <=&n;
</code>```

Inner query select distinct(sal) from emp  order by sal desc will give the below output as given below.

SAL
5000
3000
2975
2850
2450
1600
1500
1300
1250
1100
950
800

without distinct in the above query select sal from emp  order by sal desc
output as given below.

SAL
5000
3000
3000
2975
2850
2450
1600
1500
1300
1250
1250
1100
950
800

outer query will give the 'N'th max sal (E.g) I have tried here for 4th Max sal and out put as given below.

MIN(SAL)
2850

Title: Nth max salary in Oracle

Body:
To find out the Nth max sal in oracle i'm using below query

SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

Body:
select min(sal) from (select distinct(sal) from emp  order by sal desc) where rownum <=&n;

Inner query select distinct(sal) from emp  order by sal desc will give the below output as given below.

SAL
5000
3000
2975
2850
2450
1600
1500
1300
1250
1100
950
800

without distinct in the above query select sal from emp  order by sal desc
output as given below.

SAL
5000
3000
3000
2975
2850
2450
1600
1500
1300
1250
1250
1100
950
800

outer query will give the 'N'th max sal (E.g) I have tried here for 4th Max sal and out put as given below.

MIN(SAL)
2850


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
```<code>select * from users u
where 2 = (select count(*) from tags t where t.user_id = u.id and name in ('tag1','tag2'))
</code>```

Assuming that any given tag can only be present once per user.

ContentLicense: CC BY-SA 2.5

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
select * from users u
where 2 = (select count(*) from tags t where t.user_id = u.id and name in ('tag1','tag2'))

Assuming that any given tag can only be present once per user.


问:
Get Email To Receiver When Submitted And Also Sender Get Submission Copy using PHPMailer
I am newbie with PHPMailer library , I want to get emails from my contact form  But on submission of form I want sender  also get a copy of mail With additional message as " thanks for registering with us." As I gone through PHP mailer examples We can use addCC();. But how to embed additional msg.

Could you please help me with this ?

答:
Using CC or BCC will always result in identical message being sent to all; If you want the messages to be different for different recipients, you must send separate messages with different bodies. With PHPMailer:

```<code>$mail->addAddress('recipient1@example.com');
$mail->Body = "hello abc";
$mail->send();
$mail->clearAddresses();
$mail->addAddress('recipient2@example.com');
$mail->Body = "hello xyz";
$mail->send();
</code>```

It's important to call clearAddresses as otherwise the second message will be sent to both recpients.

Body:
Using CC or BCC will always result in identical message being sent to all; If you want the messages to be different for different recipients, you must send separate messages with different bodies. With PHPMailer:

$mail->addAddress('recipient1@example.com');
$mail->Body = "hello abc";
$mail->send();
$mail->clearAddresses();
$mail->addAddress('recipient2@example.com');
$mail->Body = "hello xyz";
$mail->send();

It's important to call clearAddresses as otherwise the second message will be sent to both recpients.


问:
appassembler-maven-plugin - how to include native library files when generating scripts for Windows and Unix
Hi am working on a Java application that is built into a distribution file (a zip file) using the appassembler-maven-plugin. End-users extract the contents of the zip.

Using this plugin, we build a distribution structure that includes the required jars and two execution scripts (a shell script for unix and a batch script for windows). These scripts are generated automatically by the build process.

The pom file contains the following:

```<code>    ...
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <attach>true</attach>
                <descriptors>
                    <descriptor>src/main/resources/distribution.xml</descriptor>
                </descriptors>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <!-- this is used for inheritance merges -->
                    <phase>package</phase>
                    <!-- bind to the packaging phase -->
                    <goals>
                        <goal>assembly</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>appassembler-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>assemble-standalone</id>
                    <phase>package</phase>
                    <goals>
                        <goal>assemble</goal>
                    </goals>
                    <configuration>
                        <programs>
                            <program>
                                <name>mixnet</name>
                                <mainClass>com.company.products.Application</mainClass>
                            </program>
                        </programs>
                        <repositoryLayout>flat</repositoryLayout>
                        <repositoryName>lib</repositoryName>
                        <configurationDirectory>properties</configurationDirectory>
                        <binFileExtensions>
                            <unix>.sh</unix>
                        </binFileExtensions>
                        <copyConfigurationDirectory>true</copyConfigurationDirectory>
                        <configurationSourceDirectory>src/main/resources</configurationSourceDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>attach-distribution</id>
                    <phase>package</phase>
                    <goals>
                        <goal>attach-artifact</goal>
                    </goals>
                    <configuration>
                        <artifacts>
                            <artifact>
                                <file>target/${project.artifactId}-${project.version}-distribution.zip</file>
                                <type>zip</type>
                            </artifact>
                        </artifacts>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</code>```

The generated shell script contains the following line which makes the actual call to Java:

```<code>%JAVACMD% %JAVA_OPTS% %EXTRA_JVM_ARGUMENTS% -classpath%CLASSPATH_PREFIX%;%CLASSPATH% -Dapp.name="mixnet" -Dapp.repo="%REPO%" -Dbasedir="%BASEDIR%" com.company.products.Application %CMD_LINE_ARGS%
</code>```

The batch script contains the following line which makes the actual call to Java:

```<code>exec "$JAVACMD" $JAVA_OPTS \
  $EXTRA_JVM_ARGUMENTS \
 -classpath "$CLASSPATH" \
 -Dapp.name="mixnet" \
 -Dapp.pid="$$" \
 -Dapp.repo="$REPO" \
 -Dapp.home="$BASEDIR" \
 -Dbasedir="$BASEDIR" \
  com.company.products.Application \
  "$@"
</code>```

We have now extended the Java program so that it uses native library files, these files are included in the distribution in a folder called "native" ( .dll files for windows and .so files for unix environments are included in the native directory)

I would like to edit the build process so that the generated scripts (both the shell script for unix and the batch script for windows) include the parameter "-Djava.library.path=PATH_OF_LIBRARY_FILES".

I have done some searching, but I cant find any documentation regarding support for this parameter in the appassembler plugin.

I tried to find a "hacky" solution by adding the "extraJvmArguments" tag to the application pom file, and specifing the "-Djava.library.path" parameter there, but I ran into problems with the path separator being different on windows and linux ("\" or "/"). I also thought about using "extraJvmArguments" and using a system variable to specify the path of the directory (which would have to be defined by the user), but this approach also has platform problems because a system variable is referenced using $VARIABLE_NAME on linux, but with %VARIABLE_NAME% on windows.

We could ask the end-users to edit the execution script themselves before they execute it, but it would be much better if the process was automatic, and totally transparent to the end-users. In this way, the end-users would not even know that they are running a Java application which is making use of JNI to call a native library.

I dont know any platform-neutral solution. Does appassembler already support this requirement? or how should this be handled?

答:
According to maven-assembly-plugin sources here and here, single setting <repositoryName>lib</repositoryName> controls both java.library.path and jar classpath dir.

Feel free to vote for feature request to have them separate:

Option to have native libraries in separate directory, not visible in classpath #62

Body:
Hi am working on a Java application that is built into a distribution file (a zip file) using the appassembler-maven-plugin. End-users extract the contents of the zip.

Using this plugin, we build a distribution structure that includes the required jars and two execution scripts (a shell script for unix and a batch script for windows). These scripts are generated automatically by the build process.

The pom file contains the following:

    ...
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <attach>true</attach>
                <descriptors>
                    <descriptor>src/main/resources/distribution.xml</descriptor>
                </descriptors>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>

                    <phase>package</phase>

                    <goals>
                        <goal>assembly</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>appassembler-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>assemble-standalone</id>
                    <phase>package</phase>
                    <goals>
                        <goal>assemble</goal>
                    </goals>
                    <configuration>
                        <programs>
                            <program>
                                <name>mixnet</name>
                                <mainClass>com.company.products.Application</mainClass>
                            </program>
                        </programs>
                        <repositoryLayout>flat</repositoryLayout>
                        <repositoryName>lib</repositoryName>
                        <configurationDirectory>properties</configurationDirectory>
                        <binFileExtensions>
                            <unix>.sh</unix>
                        </binFileExtensions>
                        <copyConfigurationDirectory>true</copyConfigurationDirectory>
                        <configurationSourceDirectory>src/main/resources</configurationSourceDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>attach-distribution</id>
                    <phase>package</phase>
                    <goals>
                        <goal>attach-artifact</goal>
                    </goals>
                    <configuration>
                        <artifacts>
                            <artifact>
                                <file>target/${project.artifactId}-${project.version}-distribution.zip</file>
                                <type>zip</type>
                            </artifact>
                        </artifacts>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>

The generated shell script contains the following line which makes the actual call to Java:

%JAVACMD% %JAVA_OPTS% %EXTRA_JVM_ARGUMENTS% -classpath%CLASSPATH_PREFIX%;%CLASSPATH% -Dapp.name="mixnet" -Dapp.repo="%REPO%" -Dbasedir="%BASEDIR%" com.company.products.Application %CMD_LINE_ARGS%

The batch script contains the following line which makes the actual call to Java:

exec "$JAVACMD" $JAVA_OPTS \
  $EXTRA_JVM_ARGUMENTS \
 -classpath "$CLASSPATH" \
 -Dapp.name="mixnet" \
 -Dapp.pid="$$" \
 -Dapp.repo="$REPO" \
 -Dapp.home="$BASEDIR" \
 -Dbasedir="$BASEDIR" \
  com.company.products.Application \
  "$@"

We have now extended the Java program so that it uses native library files, these files are included in the distribution in a folder called "native" ( .dll files for windows and .so files for unix environments are included in the native directory)

I would like to edit the build process so that the generated scripts (both the shell script for unix and the batch script for windows) include the parameter "-Djava.library.path=PATH_OF_LIBRARY_FILES".

I have done some searching, but I cant find any documentation regarding support for this parameter in the appassembler plugin.

I tried to find a "hacky" solution by adding the "extraJvmArguments" tag to the application pom file, and specifing the "-Djava.library.path" parameter there, but I ran into problems with the path separator being different on windows and linux ("\" or "/"). I also thought about using "extraJvmArguments" and using a system variable to specify the path of the directory (which would have to be defined by the user), but this approach also has platform problems because a system variable is referenced using $VARIABLE_NAME on linux, but with %VARIABLE_NAME% on windows.

We could ask the end-users to edit the execution script themselves before they execute it, but it would be much better if the process was automatic, and totally transparent to the end-users. In this way, the end-users would not even know that they are running a Java application which is making use of JNI to call a native library.

I dont know any platform-neutral solution. Does appassembler already support this requirement? or how should this be handled?


问:
Scraping with out Selenium Webdriver stealing focus
I am using Selenium to automate a website. First, I open the main website with C#.
Then, I manually click to open new windows from the main site. Now, I want to scrape the data of these new windows. This is not an issue. The problem lies in the fact that Selenium seems to need a window to be focused to scrape it. I use the SwitchTo method currently before scraping. When you switch, the new windows pop to the front and steal focus from other windows. Is there a way to scrape a window without giving it focus?</p>

答:
Answering straight, No Selenium can't scrape a window without the required focus.

It's not only Selenium needs focus. The WebElements with whom you intend to interact with, needs to be within the Viewport

Update:

As per your comment if you want to work through an alternatives to Selenium that wouldn't require focus the Answer is Beautiful Soup through Selenium Python Clients using urllib.request module.


问:
Test if button selected based
I need to locate a button , which may or may not be selected.

I first find the xpath to the button, check is its selected, it is failing in this check   "Unable to locate element: {"method":"tag name","selector":"input"}"

What should my boolean line check be ?

```<code>  WebElement element =  driver.findElement(By.xpath("//i[contains(@class,'i-icon--plus-18-movie')]"));

    boolean isChecked = element.findElement(By.tagName("input")).isSelected();
        if(isChecked){
            System.out.println("is checked");
                 element.click();
        }

<age-question-button class="ng-scope ng-isolate-scope" state="qc.answer[question.name]" icon="plus-18-movie" active-text="The Customer is over 18" inactive-text="The Customer is NOT over 18" ng-repeat="question in qc.questionsList track by question.name" audit="cc.utils.audit(qc.answer[question.name] ? question.auditInactive : question.auditActive)">
<label class="c-option u-p-0 u-ml-md u-pull-left" tooltip-append-to-body="true" uib-tooltip="The Customer is NOT over 18">
<input class="ng-untouched ng-valid ng-dirty ng-valid-parse" ng-model="state" ng-change="audit()" style="" type="checkbox">
<i class="c-option__button i-icon i-icon--plus-18-movie"></i>
</label>
</age-question-button>
</code>```

答:
Try using cssSelector input[type='checkbox']

```<code>WebElement element =  driver.findElement(By.cssSelector("input[type='checkbox']"));
boolean isChecked = element.isSelected();
    if(isChecked){
        System.out.println("is checked");
             element.click();
    }
</code>```

Title: Test if button selected based

Body:
I need to locate a button , which may or may not be selected.

I first find the xpath to the button, check is its selected, it is failing in this check   "Unable to locate element: {"method":"tag name","selector":"input"}"

What should my boolean line check be ?

  WebElement element =  driver.findElement(By.xpath("//i[contains(@class,'i-icon--plus-18-movie')]"));

    boolean isChecked = element.findElement(By.tagName("input")).isSelected();
        if(isChecked){
            System.out.println("is checked");
                 element.click();
        }

<age-question-button class="ng-scope ng-isolate-scope" state="qc.answer[question.name]" icon="plus-18-movie" active-text="The Customer is over 18" inactive-text="The Customer is NOT over 18" ng-repeat="question in qc.questionsList track by question.name" audit="cc.utils.audit(qc.answer[question.name] ? question.auditInactive : question.auditActive)">

<input class="ng-untouched ng-valid ng-dirty ng-valid-parse" ng-model="state" ng-change="audit()" style="" type="checkbox">

</age-question-button>

Body:
Try using cssSelector input[type='checkbox']

WebElement element =  driver.findElement(By.cssSelector("input[type='checkbox']"));
boolean isChecked = element.isSelected();
    if(isChecked){
        System.out.println("is checked");
             element.click();
    }


问:
Validation for Excel sheet using core java
I have built core java code to read excel data and push into database. And it works fine. Now I want to add some validatation checks to the excel sheet. I am not able to do that. Consider I have some columns which are SettleDate,TradeDate, TradeID, IFStatus, IFVersion, IFDate, IFTime. I want to do below vlidation rules.

Settle should not be more thatn TradeDate.

TradID should be 14 letteres.

IFStatus, IFVersion, IFDate, IFTime should be blank

Below is my code........

```<code>try {
    Class forName = Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
    Connection con = null;
    con = DriverManager.getConnection("jdbc:sybase:Tds:tkbgssvt1:4105", "kauai_rwu", "rwu_kauai");
    System.out.println("Database connected to Sybase..");
    con.setAutoCommit(false);
    PreparedStatement pstm = null;
    FileInputStream input = new FileInputStream(
            "C:\\Users\\suresnar\\Desktop\\Mizu_FGloss\\Kauai_IN_Table_test.xlsx");
    XSSFWorkbook workbook = new XSSFWorkbook(input);
    XSSFSheet sheet = workbook.getSheetAt(0);
    Row row;
    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
        row = (Row) sheet.getRow(i);
        DataFormatter formatter = new DataFormatter();
        String TradeAction = formatter.formatCellValue(row.getCell(0));
        String TradeID = formatter.formatCellValue(row.getCell(1));
        String Version = formatter.formatCellValue(row.getCell(2));
        String TradeType = formatter.formatCellValue(row.getCell(3));
        String Book = formatter.formatCellValue(row.getCell(4));
        String Direction = row.getCell(5).getStringCellValue();
        String SafekeepFlag = row.getCell(6).getStringCellValue();
        String OurSettlePlace = formatter.formatCellValue(row.getCell(7));
        String OurSettleDepot = row.getCell(8).getStringCellValue();
        String TheirSettlePlace = row.getCell(9).getStringCellValue();
        String TheirSettleDepot = row.getCell(10).getStringCellValue();
        String BrokerCode = row.getCell(11).getStringCellValue();
        String CustomerCode = formatter.formatCellValue(row.getCell(12));
        String ProductCode = formatter.formatCellValue(row.getCell(13));
        String TradeDate = formatter.formatCellValue(row.getCell(14));
        String TradeTime = formatter.formatCellValue(row.getCell(15));
        String CreditPerson = row.getCell(16).getStringCellValue();
        String Quantity = formatter.formatCellValue(row.getCell(17));
        String Factor = formatter.formatCellValue(row.getCell(18));
        String ActualQuantity = formatter.formatCellValue(row.getCell(19));
        String SettleDate = formatter.formatCellValue(row.getCell(20));
        String Price = formatter.formatCellValue(row.getCell(21));
        String TradeCcy = row.getCell(22).getStringCellValue();
        String TradeValue = formatter.formatCellValue(row.getCell(23));
        String AccDays = formatter.formatCellValue(row.getCell(24));
        String TradeAICcy = formatter.formatCellValue(row.getCell(25));
        String TradeAI = formatter.formatCellValue(row.getCell(26));
        String SettleAmt = formatter.formatCellValue(row.getCell(27));
        String RateCalc = formatter.formatCellValue(row.getCell(28));
        String FxRate = formatter.formatCellValue(row.getCell(29));
        String SettleCcy = formatter.formatCellValue(row.getCell(30));
        String SettleAmtInFX = formatter.formatCellValue(row.getCell(31));
        String Memo1 = row.getCell(32).getStringCellValue();
        String Memo2 = row.getCell(33).getStringCellValue();
        String Memo3 = row.getCell(34).getStringCellValue();
        String Memo4 = row.getCell(35).getStringCellValue();
        String Memo5 = row.getCell(36).getStringCellValue();
        String Remark1 = row.getCell(37).getStringCellValue();
        String Remark2 = row.getCell(38).getStringCellValue();
        String SelfStBrCode = formatter.formatCellValue(row.getCell(39));
        String SelfStBrSubCode = formatter.formatCellValue(row.getCell(40));
        String CustStBrCode = formatter.formatCellValue(row.getCell(41));
        String CustStClCode = formatter.formatCellValue(row.getCell(42));
        String CustStSubCode = formatter.formatCellValue(row.getCell(43));
        String DiscretionFlg = formatter.formatCellValue(row.getCell(44));
        String InputTime = formatter.formatCellValue(row.getCell(45));
        String UpdateTime = formatter.formatCellValue(row.getCell(46));
        String IFStatus = formatter.formatCellValue(row.getCell(47));
        String IFVersion = formatter.formatCellValue(row.getCell(48));
        String IFDate = formatter.formatCellValue(row.getCell(49));
        String IFTime = formatter.formatCellValue(row.getCell(50));
        String AzIFStatus = formatter.formatCellValue(row.getCell(51));
        String AzIFVersion = formatter.formatCellValue(row.getCell(52));
        String AzIFTime = formatter.formatCellValue(row.getCell(53));
        String AzCKTime = formatter.formatCellValue(row.getCell(54));
        String sql = "INSERT INTO FB_KAUAI_IN (\"my query\")";
        pstm = (PreparedStatement) con.prepareStatement(sql);
        pstm.execute();
        System.out.println("Imported rows " + i);
    }
    con.commit();
    pstm.close();
    con.close();
    input.close();
    System.out.println("Success import excel to mysql table");
} catch (IOException e) {
    e.printStackTrace();
} catch (Exception e) {
    // Handle errors for Class.forName
    e.printStackTrace();
}
</code>```

Can anyone help me please?
your help is much appriciated...
Thanks,
Suresh N

答:
I guess there's a couple of different ways to do this:

if you really own the Excel file and you create it. You can create your own formula to "validate" the cells you want.

you can create different classes for each type you want to validate and each "cell" will have it's own class/validation

you can manually create validation and apply for each field you want to validate (directly in java, per "String" you get from the
excel file).

since you (really) should change the SQL query to Hibernate for example, after that you can use hibernate validators (before inserting into db).

Body:
I have built core java code to read excel data and push into database. And it works fine. Now I want to add some validatation checks to the excel sheet. I am not able to do that. Consider I have some columns which are SettleDate,TradeDate, TradeID, IFStatus, IFVersion, IFDate, IFTime. I want to do below vlidation rules.

Settle should not be more thatn TradeDate.

TradID should be 14 letteres.

IFStatus, IFVersion, IFDate, IFTime should be blank

Below is my code........

try {
    Class forName = Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
    Connection con = null;
    con = DriverManager.getConnection("jdbc:sybase:Tds:tkbgssvt1:4105", "kauai_rwu", "rwu_kauai");
    System.out.println("Database connected to Sybase..");
    con.setAutoCommit(false);
    PreparedStatement pstm = null;
    FileInputStream input = new FileInputStream(
            "C:\\Users\\suresnar\\Desktop\\Mizu_FGloss\\Kauai_IN_Table_test.xlsx");
    XSSFWorkbook workbook = new XSSFWorkbook(input);
    XSSFSheet sheet = workbook.getSheetAt(0);
    Row row;
    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
        row = (Row) sheet.getRow(i);
        DataFormatter formatter = new DataFormatter();
        String TradeAction = formatter.formatCellValue(row.getCell(0));
        String TradeID = formatter.formatCellValue(row.getCell(1));
        String Version = formatter.formatCellValue(row.getCell(2));
        String TradeType = formatter.formatCellValue(row.getCell(3));
        String Book = formatter.formatCellValue(row.getCell(4));
        String Direction = row.getCell(5).getStringCellValue();
        String SafekeepFlag = row.getCell(6).getStringCellValue();
        String OurSettlePlace = formatter.formatCellValue(row.getCell(7));
        String OurSettleDepot = row.getCell(8).getStringCellValue();
        String TheirSettlePlace = row.getCell(9).getStringCellValue();
        String TheirSettleDepot = row.getCell(10).getStringCellValue();
        String BrokerCode = row.getCell(11).getStringCellValue();
        String CustomerCode = formatter.formatCellValue(row.getCell(12));
        String ProductCode = formatter.formatCellValue(row.getCell(13));
        String TradeDate = formatter.formatCellValue(row.getCell(14));
        String TradeTime = formatter.formatCellValue(row.getCell(15));
        String CreditPerson = row.getCell(16).getStringCellValue();
        String Quantity = formatter.formatCellValue(row.getCell(17));
        String Factor = formatter.formatCellValue(row.getCell(18));
        String ActualQuantity = formatter.formatCellValue(row.getCell(19));
        String SettleDate = formatter.formatCellValue(row.getCell(20));
        String Price = formatter.formatCellValue(row.getCell(21));
        String TradeCcy = row.getCell(22).getStringCellValue();
        String TradeValue = formatter.formatCellValue(row.getCell(23));
        String AccDays = formatter.formatCellValue(row.getCell(24));
        String TradeAICcy = formatter.formatCellValue(row.getCell(25));
        String TradeAI = formatter.formatCellValue(row.getCell(26));
        String SettleAmt = formatter.formatCellValue(row.getCell(27));
        String RateCalc = formatter.formatCellValue(row.getCell(28));
        String FxRate = formatter.formatCellValue(row.getCell(29));
        String SettleCcy = formatter.formatCellValue(row.getCell(30));
        String SettleAmtInFX = formatter.formatCellValue(row.getCell(31));
        String Memo1 = row.getCell(32).getStringCellValue();
        String Memo2 = row.getCell(33).getStringCellValue();
        String Memo3 = row.getCell(34).getStringCellValue();
        String Memo4 = row.getCell(35).getStringCellValue();
        String Memo5 = row.getCell(36).getStringCellValue();
        String Remark1 = row.getCell(37).getStringCellValue();
        String Remark2 = row.getCell(38).getStringCellValue();
        String SelfStBrCode = formatter.formatCellValue(row.getCell(39));
        String SelfStBrSubCode = formatter.formatCellValue(row.getCell(40));
        String CustStBrCode = formatter.formatCellValue(row.getCell(41));
        String CustStClCode = formatter.formatCellValue(row.getCell(42));
        String CustStSubCode = formatter.formatCellValue(row.getCell(43));
        String DiscretionFlg = formatter.formatCellValue(row.getCell(44));
        String InputTime = formatter.formatCellValue(row.getCell(45));
        String UpdateTime = formatter.formatCellValue(row.getCell(46));
        String IFStatus = formatter.formatCellValue(row.getCell(47));
        String IFVersion = formatter.formatCellValue(row.getCell(48));
        String IFDate = formatter.formatCellValue(row.getCell(49));
        String IFTime = formatter.formatCellValue(row.getCell(50));
        String AzIFStatus = formatter.formatCellValue(row.getCell(51));
        String AzIFVersion = formatter.formatCellValue(row.getCell(52));
        String AzIFTime = formatter.formatCellValue(row.getCell(53));
        String AzCKTime = formatter.formatCellValue(row.getCell(54));
        String sql = "INSERT INTO FB_KAUAI_IN (\"my query\")";
        pstm = (PreparedStatement) con.prepareStatement(sql);
        pstm.execute();
        System.out.println("Imported rows " + i);
    }
    con.commit();
    pstm.close();
    con.close();
    input.close();
    System.out.println("Success import excel to mysql table");
} catch (IOException e) {
    e.printStackTrace();
} catch (Exception e) {
    // Handle errors for Class.forName
    e.printStackTrace();
}

Can anyone help me please?
your help is much appriciated...
Thanks,
Suresh N