问:
Start activity crashes app else the app is minimazin
My app receives data from the database for authorization and registration.When startActivity(new Intent(this, Main.class));
line is commented out the app just minimize, and when uncommented it crashes.

Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.littledev.test_v2">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main">

        </activity>
    </application>

</manifest>
</code>```

Login.java

```<code>package com.example.littledev.test_v2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Login extends AppCompatActivity {

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

    public void onLoginSuccess() {
        startActivity(new Intent(this, Main.class));
    }

    public void onLogin(View view){
        EditText eLogin = (EditText) findViewById(R.id.username);
        EditText ePass = (EditText) findViewById(R.id.password);
        String login = eLogin.getText().toString();
        String pass = ePass.getText().toString();
        Sql_bridge bridge = new Sql_bridge(this);
        bridge.execute("login",login,pass);
        finish();
    }

    public void onRegister(View view) {
        //startActivity(new Intent(this, Register.class));
    }
}
</code>```

Sql_bridge.java

```<code>package com.example.littledev.test_v2;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LittleDev on 3/30/2017.
 */

public class Sql_bridge extends AsyncTask<String,Void,String> {
    private Context ctx;
    Sql_bridge (Context ctx)
    {
        this.ctx =ctx;
    }
    @Override
    protected void onPreExecute() {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Main Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://e-shops.hol.es/app_register";
        String log_url = "http://e-shops.hol.es/app_login";
        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String surname = params[2];
            String email = params[3];
            String password = params[4];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(surname, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (method.equals("login")){
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(log_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Login login = new Login();
        switch (result) {
            case "Registered":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                break;
            case "Login":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                login.onLoginSuccess();

                break;
            default:
                Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
                break;
        }

    }
}
</code>```

Logcat

```<code>03-30 15:11:48.323 9997-9997/com.example.littledev.test_v2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.littledev.test_v2, PID: 9997
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4298)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4245)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4582)
                                                                                at android.app.Activity.startActivity(Activity.java:4550)
                                                                                at com.example.littledev.test_v2.Login.onLoginSuccess(Login.java:19)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:131)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:23)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7329)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

I realy don`t have a clue why it crashes.

答:
Have you tried removing finish() from onLogin() and call it only when login result is received?

```<code>public void onLoginSuccess() {
    finish();
    startActivity(new Intent(this, Main.class));
}
</code>```

Body:
My app receives data from the database for authorization and registration.When startActivity(new Intent(this, Main.class));
line is commented out the app just minimize, and when uncommented it crashes.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.littledev.test_v2">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main">

        </activity>
    </application>

</manifest>

Login.java

package com.example.littledev.test_v2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Login extends AppCompatActivity {

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

    public void onLoginSuccess() {
        startActivity(new Intent(this, Main.class));
    }

    public void onLogin(View view){
        EditText eLogin = (EditText) findViewById(R.id.username);
        EditText ePass = (EditText) findViewById(R.id.password);
        String login = eLogin.getText().toString();
        String pass = ePass.getText().toString();
        Sql_bridge bridge = new Sql_bridge(this);
        bridge.execute("login",login,pass);
        finish();
    }

    public void onRegister(View view) {
        //startActivity(new Intent(this, Register.class));
    }
}

Sql_bridge.java

package com.example.littledev.test_v2;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LittleDev on 3/30/2017.
 */

public class Sql_bridge extends AsyncTask<String,Void,String> {
    private Context ctx;
    Sql_bridge (Context ctx)
    {
        this.ctx =ctx;
    }
    @Override
    protected void onPreExecute() {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Main Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://e-shops.hol.es/app_register";
        String log_url = "http://e-shops.hol.es/app_login";
        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String surname = params[2];
            String email = params[3];
            String password = params[4];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(surname, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (method.equals("login")){
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(log_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Login login = new Login();
        switch (result) {
            case "Registered":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                break;
            case "Login":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                login.onLoginSuccess();

                break;
            default:
                Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
                break;
        }

    }
}

Logcat

03-30 15:11:48.323 9997-9997/com.example.littledev.test_v2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.littledev.test_v2, PID: 9997
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4298)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4245)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4582)
                                                                                at android.app.Activity.startActivity(Activity.java:4550)
                                                                                at com.example.littledev.test_v2.Login.onLoginSuccess(Login.java:19)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:131)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:23)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7329)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I realy don`t have a clue why it crashes.

Body:
Have you tried removing finish() from onLogin() and call it only when login result is received?

public void onLoginSuccess() {
    finish();
    startActivity(new Intent(this, Main.class));
}


来源: stackexchange

问:
Autosave Form along with image using jQuery
Can anybody suggest me a jquery plugin that will auto save html forms data to LocalStorage to restore them after browser crashes,tabs closings or other disasters ?

I have used this one,its works fine,but it does not save image ?

Any suggestion would be highly appreciated.

答:
ok, you could keep that component but extend what you need to cover the image upload. I'm assuming you want it on the 'change' event of the file input so:

```<code><input type="file" id="myimage" name="myimage" />
</code>```

EDIT here is a better example - then in JS:

```<code>$(document).ready(function() {
    $("#myimage").on('change', function() {
        getImage(this);
    });
});

function getImage(e) {
    var reader = new FileReader();
    reader.onload = function(event) {

    var img = new Image();
    img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var dataURL = canvas.toDataURL("image/png");
        console.log(dataURL);
        var base64Data = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

        localStorage.setItem("myImageData", base64Data);

        setImage(); //set the image from the base64 string.
      }
      img.src = event.target.result;
    }
    reader.readAsDataURL(e.files[0]);
}
</code>```

Then to read and set the image back on the page:

```<code><img id="myImageElement" src="" />

function setImage() {
    try {
    var imgObj = $("#myimageElement");

    var base64Data = localStorage.getItem("myImageData");
    imgObj.src = "data:image/png;base64," + base64Data;
    }
    catch(e) {}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
ok, you could keep that component but extend what you need to cover the image upload. I'm assuming you want it on the 'change' event of the file input so:

<input type="file" id="myimage" name="myimage" />

EDIT here is a better example - then in JS:

$(document).ready(function() {
    $("#myimage").on('change', function() {
        getImage(this);
    });
});

function getImage(e) {
    var reader = new FileReader();
    reader.onload = function(event) {

    var img = new Image();
    img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var dataURL = canvas.toDataURL("image/png");
        console.log(dataURL);
        var base64Data = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

        localStorage.setItem("myImageData", base64Data);

        setImage(); //set the image from the base64 string.
      }
      img.src = event.target.result;
    }
    reader.readAsDataURL(e.files[0]);
}

Then to read and set the image back on the page:

<img id="myImageElement" src="" />

function setImage() {
    try {
    var imgObj = $("#myimageElement");

    var base64Data = localStorage.getItem("myImageData");
    imgObj.src = "data:image/png;base64," + base64Data;
    }
    catch(e) {}
}


问:
How to pass a table type to a stored procedure in a job?
I need to create a stored procedure that's called within a temporary job, so I'm doing:

```<code>CREATE PROCEDURE create_test_job
    @criteria Criteria READONLY
AS
BEGIN
    DECLARE @jobName nvarchar(max);
    SET @jobName = 'test';

    --Get database name
    DECLARE @dbName sysname;
    SELECT @dbName = DB_NAME();

    --Create job
    EXEC msdb.dbo.sp_add_job @job_name = @jobName;

    --Create step
    EXEC msdb.dbo.sp_add_jobstep
        @job_name = @jobName,
        @step_name = 'Step 1',
        @subsystem = N'TSQL',
        @database_name = @dbName,
        @command = N'EXEC my_actual_sp ' + @criteria;

    ----TODO Schedule the job at a specified date and time

    ----TODO Add the job to the SQL Server server

    EXEC msdb.dbo.sp_delete_job @job_name = @jobName;
END
GO
</code>```

And obviously @command is wrong. How can I pass the table type to my sp?

答:
You'll have to spill the contents into a real table, and re-read that inside your job.

Something like:

```<code>INSERT INTO PendingCriteria (/* Columns */)
SELECT /* Columns */ FROm @Criteria

...

@command = N'DECLARE @C Criteria
             INSERT INTO @C (/* Columns */) SELECT /* Columns */ FROM PendingCriteria
      EXEC my_actual_sp @C';
</code>```

I'd then probably do the cleanup of the permanent table as a separate job step.

The problem is that jobs represent something to be done in the (for a computer) far future. Table-variables represent an object that exists solely in the here-and-now. They're also local to the session - when the job runs in the future it will be running each step in a new session.

Body:
I need to create a stored procedure that's called within a temporary job, so I'm doing:

CREATE PROCEDURE create_test_job
    @criteria Criteria READONLY
AS
BEGIN
    DECLARE @jobName nvarchar(max);
    SET @jobName = 'test';

    --Get database name
    DECLARE @dbName sysname;
    SELECT @dbName = DB_NAME();

    --Create job
    EXEC msdb.dbo.sp_add_job @job_name = @jobName;

    --Create step
    EXEC msdb.dbo.sp_add_jobstep
        @job_name = @jobName,
        @step_name = 'Step 1',
        @subsystem = N'TSQL',
        @database_name = @dbName,
        @command = N'EXEC my_actual_sp ' + @criteria;

    ----TODO Schedule the job at a specified date and time

    ----TODO Add the job to the SQL Server server

    EXEC msdb.dbo.sp_delete_job @job_name = @jobName;
END
GO

And obviously @command is wrong. How can I pass the table type to my sp?

Body:
You'll have to spill the contents into a real table, and re-read that inside your job.

Something like:

INSERT INTO PendingCriteria (/* Columns */)
SELECT /* Columns */ FROm @Criteria

...

@command = N'DECLARE @C Criteria
             INSERT INTO @C (/* Columns */) SELECT /* Columns */ FROM PendingCriteria
      EXEC my_actual_sp @C';

I'd then probably do the cleanup of the permanent table as a separate job step.

The problem is that jobs represent something to be done in the (for a computer) far future. Table-variables represent an object that exists solely in the here-and-now. They're also local to the session - when the job runs in the future it will be running each step in a new session.


问:
How can I scrape/parse this data using regular expressions?
I'm really a beginner when it comes to regular expressions, and I'm not really sure where to start. I have some html code scraped from a web page and stored in a variable, and it looks something like this:

```<code><thead><tr>
<th></th>
<th>GENERAL INFORMATION</th>
<th></th>
<th>DETAILED DATA</th>
</tr></thead>
<tbody><tr>
<th>ID</th>
<td>123456789ABCD</td>
<th>Field1</th>
<td>6 = (Some-Specification (3 or more details))</td>

</tr></tbody>
<tbody><tr>
<th>AGL</th>
<td>1 - United States ; TH - Some Data</td>
<th>Field2</th>
<td>7 = (Option/Other Option)</td>
</tr></tbody>
<tbody><tr>
<th>MANUFACTURER</th>
<td>2010 SPECIFICATION  (ADSD: HMKC)</td>
<th>Field3</th>

<td>8 = (My Type)</td>
</tr></tbody>
<tbody><tr>
<th>MODEL</th>
<td>6X4 MY-MODEL/SOME_SPECS LONG SPECIFICATION, BLAH</td>
<th>Field4</th>
<td>9 = (STUFF/OTHER STUFF)</td>
</tr></tbody>
<tbody>
</code>```

And then there is more of the same... I would like to parse the data from these cells into variables. (e.g. parse "123456789ABCD" into an ID variable) I'm working in ColdFusion and was thinking of using methods like REFindNoCase, REReplaceNoCase, SpanExcluding... Any idea how I can accomplish this? Or if you're not familiar with ColdFusion, even just the regular expressions necessary to parse this data would be very useful.

答: Use the CF xml parser, XmlParse. Looks like its based on strict XML though so make sure you run the input through something like htmltidy.

ContentLicense: CC BY-SA 2.5

Body:
I'm really a beginner when it comes to regular expressions, and I'm not really sure where to start. I have some html code scraped from a web page and stored in a variable, and it looks something like this:

GENERAL INFORMATION

DETAILED DATA

ID
123456789ABCD
Field1
6 = (Some-Specification (3 or more details))

AGL
1 - United States ; TH - Some Data
Field2
7 = (Option/Other Option)

MANUFACTURER
2010 SPECIFICATION  (ADSD: HMKC)
Field3

8 = (My Type)

MODEL
6X4 MY-MODEL/SOME_SPECS LONG SPECIFICATION, BLAH
Field4
9 = (STUFF/OTHER STUFF)

And then there is more of the same... I would like to parse the data from these cells into variables. (e.g. parse "123456789ABCD" into an ID variable) I'm working in ColdFusion and was thinking of using methods like REFindNoCase, REReplaceNoCase, SpanExcluding... Any idea how I can accomplish this? Or if you're not familiar with ColdFusion, even just the regular expressions necessary to parse this data would be very useful.


问:
What is deep linking in AngularJS?
I was studying AngularJS for interview propose then deep linking but i am not able understand why it is used, when it used, and What is the propose of it in angularjs.

答:
Here is a clear definition of deep linking from this blog:

Deep linking is the usage of the URL, which will take to specific page
  (content) directly without traversing application from home page.
  It helps in getting indexed so that these links can be easily
  searchable by search engines like Google, Yahoo.. etc.

Using Angular, the deep linking is defaut done with the # prefix (when the HTML5 mode is not set).

Title: What is deep linking in AngularJS?


问:
Intellij - Unable to use newer Java 8 classes - Error : "Usage of API documented as @since 1.6+.."
I'm trying to use a java.lang.function.Function in my java 8 code base, but i keep getting the following error in Intellij.

Usage of API documented as @since 1.6+  This inspection finds all
  usages of methods that have @since tag in their documentation.  This
  may be useful when development is performed under newer SDK version as
  the target platform for production

I seem to have the correct Project and Compiler settings

Project Settings: (File -> Project Structure)

```<code>Project Settings -> Project -> Project SDK = Java 1.8
Project Settings -> Project -> Project Language Level = 8 - Lambdas, Type Annotations etc
</code>```

Compiler Settings: (File -> Settings)

```<code>Build, Execution, Deployment -> Compiler -> Java Compiler -> Project Bytecode Version : 1.8
Build, Execution, Deployment -> Compiler -> Java Compiler -> Per module Bytecode Version -> Target Bytecode Version : 1.8
</code>```

What is the problem?

答:
File > Settings > Build, Execution, Deployment > Java Compiler

Change Target bytecode version to 1.8 of the module that you are working for.

If you are using Maven

Add the compiler plugin to pom.xml under the top-level project node:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>```

Body:
I'm trying to use a java.lang.function.Function in my java 8 code base, but i keep getting the following error in Intellij.

Usage of API documented as @since 1.6+  This inspection finds all
  usages of methods that have @since tag in their documentation.  This
  may be useful when development is performed under newer SDK version as
  the target platform for production

I seem to have the correct Project and Compiler settings

Project Settings: (File -> Project Structure)

Project Settings -> Project -> Project SDK = Java 1.8
Project Settings -> Project -> Project Language Level = 8 - Lambdas, Type Annotations etc

Compiler Settings: (File -> Settings)

Build, Execution, Deployment -> Compiler -> Java Compiler -> Project Bytecode Version : 1.8
Build, Execution, Deployment -> Compiler -> Java Compiler -> Per module Bytecode Version -> Target Bytecode Version : 1.8

What is the problem?


问:
Sending multiple selected items to Controller via AJAX
I have a list of policies that I'm displaying to the end user. Each policy entry has a checkbox to indicate whether or not they want to select that policy. They can choose multiple policies. Once they click on the Next button I want to be able to send the policies back to my controller(with the updated checkbox values) via an AJAX call. I see many examples of sending data when it's just one item but I can't get it working for multiple. I feel like it's something easy but I'm struggling and I'm hoping someone can help. Here's what I have thus far.

ViewModel:

```<code>public class PolicySelection
{
    public bool Selected { get; set; }
    public string PolicyType { get; set; }
    public string PolicyNumber { get; set; }
    public string Mod { get; set; }
    public string CompanyName { get; set; }
}

public class PolicySelectionViewModel
{
    public List<PolicySelection> Policies { get; set; }
}
</code>```

View:

```<code>@model Models.PolicySelectionViewModel

@using (Html.BeginForm())
{
    <div>
        @{ string policyType = "";}
        @for (int i = 0; i < Model.Policies.Count; i++)
        {
            if (Model.Policies[i].PolicyType != policyType)
            {
                <h3>@Model.Policies[i].PolicyType</h3>
                policyType = Model.Policies[i].PolicyType;
            }

            <div class="col-lg-1" style="width:5%;">
                @Html.CheckBoxFor(m => m.Policies[i].Selected)
            </div>

            <div class="col-lg-3 padding-0">
                @Html.DisplayFor(m => m.Policies[i].PolicyNumber)<text>-</text>@Html.DisplayFor(m => m.Policies[i].Mod)
            </div>

            <div>
                @Html.DisplayFor(m => m.Policies[i].CompanyName)
            </div>
        }
    </div>

    <button class="btn btn-default btn-primary" style="position:absolute; left:300px; bottom:7px; width: 200px;" onclick="Next()" type="button">Next</button>
</div>
}

<script type="text/javascript">
    function GetModelData()
    {
        return $("form").serializeArray();
    }

    function Next()
    {
        var url = '@Url.Action("VerifyPolicies", "Home")';
        var model = GetModelData();
        $.ajax({
            url: url,
            data: { PolicyList: model},
            type: "POST",
            success: function (data, textStatus, XMLHttpRequest) {
                alert(data);
            }
        });
    }
</script>
</code>```

Controller:

```<code>[HttpPost]
public string VerifyPolicies(PolicySelectionViewModel PolicyList)
{
    string selectedPolicyNumbers = string.Empty;

    foreach(var policy in PolicyList.Policies)
    {
        if(policy.Selected)
        {
            selectedPolicyNumbers += policy.PolicyNumber + ',';
        }
    }
    return selectedPolicyNumber;
}
</code>```

I ran this with 3 policies and checked the checkbox for 2 of them. When I break in my controller the PolicyList object had 5 policies and each policy's field is null except for Selected which is always false. I tried again this time just checking one of the 3 policies and now the PolicyList object had 4 objects. Thanks in advance for any help with this.

答:
Thanks to Stephen Muecke I was able to get it working. I had to remove the curly braces {} and the property name(PolicyList) from the data option in the Ajax call, add Hidden Fields for the other properties I wanted to pass back and use .serialize() instead of .serializeArray(). Here's what my working View looks like:

View:

```<code>@model Models.PolicySelectionViewModel

@using (Html.BeginForm())
{
    <div>
        @{ string policyType = "";}
        @for (int i = 0; i < Model.Policies.Count; i++)
        {
            @Html.HiddenFor(m => m.Policies[i].PolicyNumber);
            @Html.HiddenFor(m => m.Policies[i].Mod);
            @Html.HiddenFor(m => m.Policies[i].PolicyType);

            if (Model.Policies[i].PolicyType != policyType)
            {
                <h3>@Model.Policies[i].PolicyType</h3>
                policyType = Model.Policies[i].PolicyType;
            }

            <div class="col-lg-1" style="width:5%;">
                @Html.CheckBoxFor(m => m.Policies[i].Selected)
            </div>

            <div class="col-lg-3 padding-0">
                @Html.DisplayFor(m => m.Policies[i].PolicyNumber)<text>-</text>@Html.DisplayFor(m => m.Policies[i].Mod)
            </div>

            <div>
                @Html.DisplayFor(m => m.Policies[i].CompanyName)
            </div>
        }
    </div>

    <button class="btn btn-default btn-primary" style="position:absolute; left:300px; bottom:7px; width: 200px;" onclick="Next()" type="button">Next</button>
</div>
}

<script type="text/javascript">
    function GetModelData()
    {
        return $("form").serialize();
    }

    function Next()
    {
        var url = '@Url.Action("VerifyPolicies", "Home")';
        var model = GetModelData();
        $.ajax({
            url: url,
            data: model,
            type: "POST",
            success: function (data, textStatus, XMLHttpRequest) {
                alert(data);
            }
        });
    }
</script>
</code>```

My Controller and ViewModel stayed the same. Thanks again to Stephen for his help with this.

Body:
I have a list of policies that I'm displaying to the end user. Each policy entry has a checkbox to indicate whether or not they want to select that policy. They can choose multiple policies. Once they click on the Next button I want to be able to send the policies back to my controller(with the updated checkbox values) via an AJAX call. I see many examples of sending data when it's just one item but I can't get it working for multiple. I feel like it's something easy but I'm struggling and I'm hoping someone can help. Here's what I have thus far.

ViewModel:

public class PolicySelection
{
    public bool Selected { get; set; }
    public string PolicyType { get; set; }
    public string PolicyNumber { get; set; }
    public string Mod { get; set; }
    public string CompanyName { get; set; }
}

public class PolicySelectionViewModel
{
    public List<PolicySelection> Policies { get; set; }
}

View:

@model Models.PolicySelectionViewModel

@using (Html.BeginForm())
{

        @{ string policyType = "";}
        @for (int i = 0; i < Model.Policies.Count; i++)
        {
            if (Model.Policies[i].PolicyType != policyType)
            {

@Model.Policies[i].PolicyType

                policyType = Model.Policies[i].PolicyType;
            }

                @Html.CheckBoxFor(m => m.Policies[i].Selected)

                @Html.DisplayFor(m => m.Policies[i].PolicyNumber)<text>-</text>@Html.DisplayFor(m => m.Policies[i].Mod)

                @Html.DisplayFor(m => m.Policies[i].CompanyName)

        }

    <button class="btn btn-default btn-primary" style="position:absolute; left:300px; bottom:7px; width: 200px;" onclick="Next()" type="button">Next</button>

}

Controller:

[HttpPost]
public string VerifyPolicies(PolicySelectionViewModel PolicyList)
{
    string selectedPolicyNumbers = string.Empty;

    foreach(var policy in PolicyList.Policies)
    {
        if(policy.Selected)
        {
            selectedPolicyNumbers += policy.PolicyNumber + ',';
        }
    }
    return selectedPolicyNumber;
}

I ran this with 3 policies and checked the checkbox for 2 of them. When I break in my controller the PolicyList object had 5 policies and each policy's field is null except for Selected which is always false. I tried again this time just checking one of the 3 policies and now the PolicyList object had 4 objects. Thanks in advance for any help with this.

Body:
Thanks to Stephen Muecke I was able to get it working. I had to remove the curly braces {} and the property name(PolicyList) from the data option in the Ajax call, add Hidden Fields for the other properties I wanted to pass back and use .serialize() instead of .serializeArray(). Here's what my working View looks like:

View:

@model Models.PolicySelectionViewModel

@using (Html.BeginForm())
{
    <div>
        @{ string policyType = "";}
        @for (int i = 0; i < Model.Policies.Count; i++)
        {
            @Html.HiddenFor(m => m.Policies[i].PolicyNumber);
            @Html.HiddenFor(m => m.Policies[i].Mod);
            @Html.HiddenFor(m => m.Policies[i].PolicyType);

            if (Model.Policies[i].PolicyType != policyType)
            {
                <h3>@Model.Policies[i].PolicyType</h3>
                policyType = Model.Policies[i].PolicyType;
            }

            <div class="col-lg-1" style="width:5%;">
                @Html.CheckBoxFor(m => m.Policies[i].Selected)
            </div>

            <div class="col-lg-3 padding-0">
                @Html.DisplayFor(m => m.Policies[i].PolicyNumber)<text>-</text>@Html.DisplayFor(m => m.Policies[i].Mod)
            </div>

            <div>
                @Html.DisplayFor(m => m.Policies[i].CompanyName)
            </div>
        }
    </div>

    <button class="btn btn-default btn-primary" style="position:absolute; left:300px; bottom:7px; width: 200px;" onclick="Next()" type="button">Next</button>
</div>
}

<script type="text/javascript">
    function GetModelData()
    {
        return $("form").serialize();
    }

    function Next()
    {
        var url = '@Url.Action("VerifyPolicies", "Home")';
        var model = GetModelData();
        $.ajax({
            url: url,
            data: model,
            type: "POST",
            success: function (data, textStatus, XMLHttpRequest) {
                alert(data);
            }
        });
    }
</script>

My Controller and ViewModel stayed the same. Thanks again to Stephen for his help with this.


问:
Javascript regex selecting numbers that are not connected to letters
This is my current regex:

```<code>var re = '/\d+\s+[\d+a-z]+/gi';
</code>```

I'm trying to get my regex to select numbers before if there are there own and then any abc characters and numbers after a whitespace

This is my test string

```<code>part1 6

22 part2

part3 8
</code>```

At the moment its selecting the following

```<code>1 : 6

22 part2

3 8
</code>```

But I just want to be selecting this

```<code>22 part2
</code>```

So i'm only wanting to select this if the number is on its own.

Any help thanks ?

答:
The regex is /^\d+\s[a-zA-Z0-9]+$/

^ start

\d+\s 1 or more digits and 1 space

[a-zA-Z0-9]+ the alpha numeric combination

$ end

var arr=["part1 6","22 part2","part3 8"];

var re=/^\d+\s[a-zA-Z0-9]+$/;

arr.forEach(x => console.log(x,re.test(x)));```

Body:
This is my current regex:

var re = '/\d+\s+[\d+a-z]+/gi';

I'm trying to get my regex to select numbers before if there are there own and then any abc characters and numbers after a whitespace

This is my test string

part1 6

22 part2

part3 8

At the moment its selecting the following

1 : 6

22 part2

3 8

But I just want to be selecting this

22 part2

So i'm only wanting to select this if the number is on its own.

Any help thanks ?


问:
Proper Project Type for Cross-platform Renderer
I need to develop a cross-platform app that ranges from mobile to desktop to TV. App includes a huge variety of 3D elements which are vital for application's correct display.

At first, I was going to use C++ and native compilers (utilizing directives) but I have gone that road many times, there are a lot of overlapping factors you can't unify (or find work, too much, arounds to overcome this issue), so I decided to try other alternatives.

I found Xamarin most outstanding cross-platform toolkit allowing native performance applications but I got lost in some terminology. In my application, there will be a base class called "GraphRenderer". I will override it for each platform and on each platform, I will include a different GPU library (eg. Metal for Mac, DirectX 12 for Windows, Vulkan for Android) and utilize it. If possible, I don't want to use directives, creating interfaces approach seem way more cleaner in the long run.

Is there a project type (as you can imagine Shared Library, PCL etc. left me confused)  that allows this hierarchy:

App

Shared Code Files

GraphRenderer.cs : Definition of GraphRenderer with Empty Functions to make it compatible for other shared code

Platform-Specific Code Files

GraphRenderer.Windows.cs : Replaces GraphRenderer.cs when compiling App for Windows 10 platform, includes DirectX 12 headers and override functions with proper functionality

Thanks.

答:
There are two approaches one is shared and another PCL
In shared approach you have to use directives as you will be using single shared file in all platforms.
In PCL approach you need to have an interface created in PCL project and implement in platform specific projects. </p>


问:
Loopback: Event resetPasswordRequest not called after reset
I am trying to tap into the password reset process on Loopback, so I can send an e-mail with the instructions to the user. I created a custom model called 'user' that extends 'User'. Then I added "User.on('resetPasswordRequest'...", but it never gets executed. Please check the console.log on the user.js

model-config.json

```<code>{
...

  "user": {
    "dataSource": "mysqlDs",
    "public": true,
    "options": {
      "emailVerificationRequired": false
    }
  },
...
}
</code>```

user.json

```<code>{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}
</code>```

user.js

```<code>module.exports = function(User) {

  console.log('It prints this log here.');

  User.on('resetPasswordRequest', function(info) {

    console.log('But it does not print this log here ever.');

    var url = 'http://www.example.com/reset-password';
    var html = 'Click <a href="' + url + '?access_token=' + info.accessToken.id + '">here</a>';
    loopback.Email.send({
      to: info.email,
      from: 'mail@example.com',
      subject: 'My Subject',
      html: html
    }, function() {
      console.log('> sending password reset email to:', info.email);
      if (err) return console.log('> error sending password reset email');
    });
  });

};
</code>```

答:
The solution is explained here:
http://loopback.io/doc/en/lb3/Extending-built-in-models.html#setting-up-a-custom-model

So you will need:

```<code>User.setup = function() {
  var User = this;
  // since setup is called for every extended model
  // the extended model will also have the event listener
  User.on('resetPasswordRequest', function() {
    ///Do your stuff here
  });
}
</code>```

Body:
I am trying to tap into the password reset process on Loopback, so I can send an e-mail with the instructions to the user. I created a custom model called 'user' that extends 'User'. Then I added "User.on('resetPasswordRequest'...", but it never gets executed. Please check the console.log on the user.js

model-config.json

{
...

  "user": {
    "dataSource": "mysqlDs",
    "public": true,
    "options": {
      "emailVerificationRequired": false
    }
  },
...
}

user.json

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}

user.js

module.exports = function(User) {

  console.log('It prints this log here.');

  User.on('resetPasswordRequest', function(info) {

    console.log('But it does not print this log here ever.');

    var url = 'http://www.example.com/reset-password';
    var html = 'Click here';
    loopback.Email.send({
      to: info.email,
      from: 'mail@example.com',
      subject: 'My Subject',
      html: html
    }, function() {
      console.log('> sending password reset email to:', info.email);
      if (err) return console.log('> error sending password reset email');
    });
  });

};

Body:
The solution is explained here:
http://loopback.io/doc/en/lb3/Extending-built-in-models.html#setting-up-a-custom-model

So you will need:

User.setup = function() {
  var User = this;
  // since setup is called for every extended model
  // the extended model will also have the event listener
  User.on('resetPasswordRequest', function() {
    ///Do your stuff here
  });
}


问:
Javascript (Jquery or MooTools or pure Javascript) hide Element by content or href
I have a HTML that looks like this:

```<code><tr>
<td nowrap="nowrap">
<a href="/home" class="mainlevel_jos_mainmenu_menu" >Home</a>
<a href="/somethingelse" class="mainlevel_jos_mainmenu_menu" >Something Else</a>
<a href="/somethingelse2" class="mainlevel_jos_mainmenu_menu" id="active_menu_jos_mainmenu_menu">Something Else 2</a>
<a href="/somethingelse3" class="mainlevel_jos_mainmenu_menu" >Something Else 3</a>
<a href="/somethingelse4" class="mainlevel_jos_mainmenu_menu">Something Else 4</a>
</td>
</tr>
</code>```

and i need to hide the Element a with content Home, either by href (because its the only element with this href on page) or by content (which is always "Home").

But the problem is, i can not add ID to Home.

答:
Using jQuery:

First element

```<code>$(".mainlevel_jos_mainmenu_menu:first").hide();
</code>```

By content

```<code>$(".mainlevel_jos_mainmenu_menu:contains('Home')").hide();
</code>```

By href

```<code>$(".mainlevel_jos_mainmenu_menu[href='/home']").hide();
</code>```

Body:
I have a HTML that looks like this:

Home
Something Else
Something Else 2
Something Else 3
Something Else 4

and i need to hide the Element a with content Home, either by href (because its the only element with this href on page) or by content (which is always "Home").

But the problem is, i can not add ID to Home.

Body:
Using jQuery:

First element

$(".mainlevel_jos_mainmenu_menu:first").hide();

By content

$(".mainlevel_jos_mainmenu_menu:contains('Home')").hide();

By href

$(".mainlevel_jos_mainmenu_menu[href='/home']").hide();


问:
UNION to JPA Query
Is it possible to query "UNION" in JPA and even "Criteria Builder"?

I'm looking for examples, but so far i got no result.

Does anyone have any examples of how to use it?

Or would that be with native sql?

答:
You can directly use UNION in your query.
The following query returns id of friends from FRIENDSHIP table.

Eg:

```<code>TypedQuery<String> queryFriend = em.createQuery("SELECT f.Id FROM Friendship f WHERE f.frStuId = :stuId UNION "
                                 + "SELECT f.frStuId FROM Friendship f WHERE f.FriendId = :stuId", String.class);
queryFriend.setParameter("stuId", stuId);

List<String> futureFriends = queryFriend.getResultList();
</code>```

Title: UNION to JPA Query

Body:
You can directly use UNION in your query.
The following query returns id of friends from FRIENDSHIP table.

Eg:

TypedQuery<String> queryFriend = em.createQuery("SELECT f.Id FROM Friendship f WHERE f.frStuId = :stuId UNION "
                                 + "SELECT f.frStuId FROM Friendship f WHERE f.FriendId = :stuId", String.class);
queryFriend.setParameter("stuId", stuId);

List<String> futureFriends = queryFriend.getResultList();


问:
Hiding textView below toolbar in coordinator layout
I'm working on creating a layout that works as follows:

Toolbar at the top

textView(a title) below top toolbar

RecyclerView

button

where the toolbar is in the main_activity
and the others are in an other xml file

And when I scroll, I want to hide the textView in between top toolbar and recyclerView.

答:
why don't try the following, it might help</p>

```<code>myRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrolled(RecyclerView rv, int dx, int dy) {
                //boolean hasStarted = state == rv.SCROLL_STATE_DRAGGING; //Scrollbar is MOVING
                //boolean hasEnded = state == rv.SCROLL_STATE_IDLE;       //ScrollBar is NOT MOVING
                //boolean isStopping = state == rv.SCROLL_STATE_SETTLING; //Scrollbar is STOPPING
                if(dy > 0){
                   myTextview.setVisibility(View.VISIBLE);
                }
            }
        });
</code>```

Body:
why don't try the following, it might help

myRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrolled(RecyclerView rv, int dx, int dy) {
                //boolean hasStarted = state == rv.SCROLL_STATE_DRAGGING; //Scrollbar is MOVING
                //boolean hasEnded = state == rv.SCROLL_STATE_IDLE;       //ScrollBar is NOT MOVING
                //boolean isStopping = state == rv.SCROLL_STATE_SETTLING; //Scrollbar is STOPPING
                if(dy > 0){
                   myTextview.setVisibility(View.VISIBLE);
                }
            }
        });


问:
How do I calculate the date in JavaScript three months prior to today?
I Am trying to form a date which is 3 months before the current date. I get the current month by the below code

```<code>var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
</code>```

Can you guys provide me the logic to calculate and form a date (an object of the Date data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?

答:
In my case I needed to substract 1 month to current date. The important part was the month number, so it doesn't care in which day of the current month you are at, I needed last month. This is my code:

```<code>var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
</code>```

Substract 1 month to actual date it's not accurate, that's why in first place I set first day of the month (first day of any month always is first day) and in second place I substract 1 day, which always send you to last month.
Hope to help you dude.

var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)```

Body:
I Am trying to form a date which is 3 months before the current date. I get the current month by the below code

var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;

Can you guys provide me the logic to calculate and form a date (an object of the Date data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?

Body:
In my case I needed to substract 1 month to current date. The important part was the month number, so it doesn't care in which day of the current month you are at, I needed last month. This is my code:

var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)

Substract 1 month to actual date it's not accurate, that's why in first place I set first day of the month (first day of any month always is first day) and in second place I substract 1 day, which always send you to last month.
Hope to help you dude.

var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)


问:
Why does container div insist on being slightly larger than IMG or SVG content?
I'm trying to produce yet another lightbox as much needed HTML/CSS/Javascript practice, but I've encountered a styling issue that looks trivial (and probably is!) but I just can't solve it.

I have a div that contains an img. No matter what I try (border, margin, padding, auto height etc.) I just can't make the div shrink to match the image dimensions. I've reduced the problem to this:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
        <title>Layout experiments</title>

        <style type="text/css">
            #lightbox {
                margin: 0;
                padding: 0;
                position    : fixed;
                left        : 50%;
                margin-left : -320px;
                top         : 100px;
                border-radius: 22px;
                background  : #e0e0f0;
                color       : #102020;
            }

            #lightbox img {
                border-radius: 15px;
            }
            .imagebg {
                margin      : 7px;
                background  : black;
                border-radius: 15px;
                height      : 100%;
            }

        </style>

    </head>
    <body>

        <div id="lightbox">
            <div class="imagebg">
                <img src="picture.jpg">
            </div>
        </div>
    </body>
</html>
</code>```

'picture.jpg' is 640x400, but the container div wants to be 640x404, the difference showing itself as a black strip below the image. The div exists so that I can fade the image to black by blending it's opacity down to 0, swap it, then blend it back in.

I've looked at the computed styles in multiple browsers and can't see where the 4px delta is coming from.

答:
try adding:

```<code>vertical-align: middle;
</code>```

This is used in google material design lite for removing the gap between audio, canvas, iframes, images, videos and the bottom of their containers.

Material Design Lite: https://getmdl.io

Github discusion: https://github.com/h5bp/html5-boilerplate/issues/440

Body:
I'm trying to produce yet another lightbox as much needed HTML/CSS/Javascript practice, but I've encountered a styling issue that looks trivial (and probably is!) but I just can't solve it.

I have a div that contains an img. No matter what I try (border, margin, padding, auto height etc.) I just can't make the div shrink to match the image dimensions. I've reduced the problem to this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
        <title>Layout experiments</title>

'picture.jpg' is 640x400, but the container div wants to be 640x404, the difference showing itself as a black strip below the image. The div exists so that I can fade the image to black by blending it's opacity down to 0, swap it, then blend it back in.

I've looked at the computed styles in multiple browsers and can't see where the 4px delta is coming from.

Body:
try adding:

vertical-align: middle;

This is used in google material design lite for removing the gap between audio, canvas, iframes, images, videos and the bottom of their containers.

Material Design Lite: https://getmdl.io

Github discusion: https://github.com/h5bp/html5-boilerplate/issues/440


问:
Visual Studio 2017 c# console project does not provide namespace win32.registry
I noticed that when you create a VS 2017 C# console project and try to access the

Microsoft.Win32.Registry

class, it seems not to be part of the references. As it is part of mscorlib.dll it should. Adding mscorlib.dll as a reference results - obviously - in double definition of basic types.

Even better: Do the same thing in VB (console project, use the Registry class) and it works right away...

Is it me or is this a bug in VS2017??

--- Edited ---

The code:

```<code>using System;
using Microsoft.Win32;

public class GetDotNetVersion
{
    public static void Get45PlusFromRegistry()
{
    const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

    using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
    {
        if (ndpKey != null && ndpKey.GetValue("Release") != null)
        {
            Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release")));
        }
        else
        {
            Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
        }
    }
}

// Checking the version using >= will enable forward compatibility.
private static string CheckFor45PlusVersion(int releaseKey)
{
    if (releaseKey >= 394802)
        return "4.6.2 or later";
    if (releaseKey >= 394254)
    {
        return "4.6.1";
    }
    if (releaseKey >= 393295)
    {
        return "4.6";
    }
    if ((releaseKey >= 379893))
    {
        return "4.5.2";
    }
    if ((releaseKey >= 378675))
    {
        return "4.5.1";
    }
    if ((releaseKey >= 378389))
    {
        return "4.5";
    }
    // This code should never execute. A non-null release key should mean
    // that 4.5 or later is installed.
    return "No 4.5 or later version detected";
}
}
// Calling the GetDotNetVersion.Get45PlusFromRegistry method produces
// output like the following:
//       .NET Framework Version: 4.6.1

namespace ConsoleApp1
{
 class Program
 {
    static void Main(string[] args)
    {
        GetDotNetVersion.Get45PlusFromRegistry();
    }
 }
}
</code>```

It is a .netCoreApp 1.1 ...

I get error CS0246 (Type or namespace RegistryKey not found) and subsequent errors (4 altogether).

VS also hints that the using directive for Microsoft.Win32 is obsolete.

Thanks!!

答:
You do have a reference to Microsoft.Win32 in your code, and try accessing GetValue (or other method) using the Registry class (eg Registry.GetValue())

Registry is a static class.

Body:
I noticed that when you create a VS 2017 C# console project and try to access the

Microsoft.Win32.Registry

class, it seems not to be part of the references. As it is part of mscorlib.dll it should. Adding mscorlib.dll as a reference results - obviously - in double definition of basic types.

Even better: Do the same thing in VB (console project, use the Registry class) and it works right away...

Is it me or is this a bug in VS2017??

--- Edited ---

The code:

using System;
using Microsoft.Win32;

public class GetDotNetVersion
{
    public static void Get45PlusFromRegistry()
{
    const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

    using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
    {
        if (ndpKey != null && ndpKey.GetValue("Release") != null)
        {
            Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release")));
        }
        else
        {
            Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
        }
    }
}

// Checking the version using >= will enable forward compatibility.
private static string CheckFor45PlusVersion(int releaseKey)
{
    if (releaseKey >= 394802)
        return "4.6.2 or later";
    if (releaseKey >= 394254)
    {
        return "4.6.1";
    }
    if (releaseKey >= 393295)
    {
        return "4.6";
    }
    if ((releaseKey >= 379893))
    {
        return "4.5.2";
    }
    if ((releaseKey >= 378675))
    {
        return "4.5.1";
    }
    if ((releaseKey >= 378389))
    {
        return "4.5";
    }
    // This code should never execute. A non-null release key should mean
    // that 4.5 or later is installed.
    return "No 4.5 or later version detected";
}
}
// Calling the GetDotNetVersion.Get45PlusFromRegistry method produces
// output like the following:
//       .NET Framework Version: 4.6.1

namespace ConsoleApp1
{
 class Program
 {
    static void Main(string[] args)
    {
        GetDotNetVersion.Get45PlusFromRegistry();
    }
 }
}

It is a .netCoreApp 1.1 ...

I get error CS0246 (Type or namespace RegistryKey not found) and subsequent errors (4 altogether).

VS also hints that the using directive for Microsoft.Win32 is obsolete.

Thanks!!


问:
Disable certification chain validation in 2-way SSL
I refer to the second answer to this question:

Web Service Client (JAX-WS) in Weblogic(10.3) with 2 way SSL cannot complete the handshake

I have a client program that connects to another server A with one-way SSL. To turn off certificate chain validation, I used the solution in the second answer to the above question to install an all-trusting trust manager. It works fine.

However, when the client program connects to another server B with two-way SSL, the following exception is thrown.

```<code>java.net.SocketException: Software caused connection abort: recv failed
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
        at java.net.SocketInputStream.read(SocketInputStream.java:171)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
        at sun.security.ssl.InputRecord.read(InputRecord.java:503)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
        at sun.security.ssl.SSLSocketImpl.waitForClose(SSLSocketImpl.java:1769)
        at sun.security.ssl.HandshakeOutStream.flush(HandshakeOutStream.java:124
)
        at sun.security.ssl.Handshaker.sendChangeCipherSpec(Handshaker.java:1130
)
        at sun.security.ssl.ClientHandshaker.sendChangeCipherAndFinish(ClientHan
dshaker.java:1216)
        at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.ja
va:1128)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.jav
a:348)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.
java:1375)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403
)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387
)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:
559)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(AbstractDelegateHttpsURLConnection.java:185)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLC
onnection.java:1316)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLCo
nnection.java:1291)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Htt
psURLConnectionImpl.java:250)
</code>```

If I don't install the all-trusting trust manager, I can still make the connection to both servers work (whether one-way or two-way SSL), provided that I specify the identity store and trust store:

```<code>System.setProperty("javax.net.ssl.keyStore", "path/to/your/key");
System.setProperty("javax.net.ssl.keyStorePassword", "your-keystore-password");
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", "path/to/your/trust/keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "your-truststore-password");
</code>```

However, I still want to turn off certificate chain validation in two-way SSL. Installing the all-trusting trust manager does not seem to work. Why?

Thanks in advance.

答:
However, I still want to turn off certificate chain validation in
  two-way SSL. Installing the all-trusting trust manager does not seem
  to work. Why?

The server requires you to provide an identifying client certificate.  If your client doesn't provide a certificate that the server is configured to accept, it drops your connection attempt.

You can't change this in the client - at all.

The SSL protocol is designed such that if a client or server requires the other side to identify itself with a certificate, that can't be modified by the side required to provide the certificate.

Body:
I refer to the second answer to this question:

Web Service Client (JAX-WS) in Weblogic(10.3) with 2 way SSL cannot complete the handshake

I have a client program that connects to another server A with one-way SSL. To turn off certificate chain validation, I used the solution in the second answer to the above question to install an all-trusting trust manager. It works fine.

However, when the client program connects to another server B with two-way SSL, the following exception is thrown.

java.net.SocketException: Software caused connection abort: recv failed
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
        at java.net.SocketInputStream.read(SocketInputStream.java:171)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
        at sun.security.ssl.InputRecord.read(InputRecord.java:503)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
        at sun.security.ssl.SSLSocketImpl.waitForClose(SSLSocketImpl.java:1769)
        at sun.security.ssl.HandshakeOutStream.flush(HandshakeOutStream.java:124
)
        at sun.security.ssl.Handshaker.sendChangeCipherSpec(Handshaker.java:1130
)
        at sun.security.ssl.ClientHandshaker.sendChangeCipherAndFinish(ClientHan
dshaker.java:1216)
        at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.ja
va:1128)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.jav
a:348)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.
java:1375)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403
)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387
)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:
559)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(AbstractDelegateHttpsURLConnection.java:185)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLC
onnection.java:1316)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLCo
nnection.java:1291)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Htt
psURLConnectionImpl.java:250)

If I don't install the all-trusting trust manager, I can still make the connection to both servers work (whether one-way or two-way SSL), provided that I specify the identity store and trust store:

System.setProperty("javax.net.ssl.keyStore", "path/to/your/key");
System.setProperty("javax.net.ssl.keyStorePassword", "your-keystore-password");
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", "path/to/your/trust/keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "your-truststore-password");

However, I still want to turn off certificate chain validation in two-way SSL. Installing the all-trusting trust manager does not seem to work. Why?

Thanks in advance.


问:
how to add localization in ionic popup
i had completed ionic project. i would like to change lanaguages in this code. project title, place holder , button it had changed but popup was doesn't changed. i used this code in controller and language change file.

farmer-ctrl.js :

```<code>function showPopup () {
  $scope.data = {};
  var myPopup = $ionicPopup.show({
    template: '<input type="text" ng-model="data.category">',
    title: '{{"farmers_message" | translate}}', //'Enter CoconutType',
    scope: $scope,
    buttons: [
     { text: 'Cancel' },
      {
        text: '<b>{{"save_message" | translate}}</b>',
        type: 'button-positive',
        onTap: function (e) {
          if (!$scope.data.category) {
            //don't allow the user to close unless he enters producttype
            e.preventDefault();

          } else {
            $log.log('yes clicked: ', $scope.data.category);
            addProductType();
            return $scope.data.category;
          }
        }
      },
    ]
  });
  myPopup.then(function (res) {
    $log.log('Tapped!', res);
  });
}
</code>```

答:
i had founded by adding translate.instant</p>

```<code>function showPopup () {
  $scope.data = {};
  var myPopup = $ionicPopup.show({
    template: '<input type="text" ng-model="data.category">',
    // title: 'Enter CoconutType',
    title: $translate.instant('{{"farmers_message" | translate}}'),
    scope: $scope,
    buttons: [
     { text: 'Cancel' },
      {
        text: $translate.instant('{{"save_message" | translate}}'),
        type: 'button-positive',
        onTap: function (e) {
          if (!$scope.data.category) {
            //don't allow the user to close unless he enters producttype
            e.preventDefault();

          } else {
            $log.log('yes clicked: ', $scope.data.category);
            addProductType();
            return $scope.data.category;
          }
        }
      },
    ]
  });
  myPopup.then(function (res) {
    $log.log('Tapped!', res);
  });
}
</code>```

Title: how to add localization in ionic popup

Body:
i had completed ionic project. i would like to change lanaguages in this code. project title, place holder , button it had changed but popup was doesn't changed. i used this code in controller and language change file.

farmer-ctrl.js :

function showPopup () {
  $scope.data = {};
  var myPopup = $ionicPopup.show({
    template: '<input type="text" ng-model="data.category">',
    title: '{{"farmers_message" | translate}}', //'Enter CoconutType',
    scope: $scope,
    buttons: [
     { text: 'Cancel' },
      {
        text: '{{"save_message" | translate}}',
        type: 'button-positive',
        onTap: function (e) {
          if (!$scope.data.category) {
            //don't allow the user to close unless he enters producttype
            e.preventDefault();

          } else {
            $log.log('yes clicked: ', $scope.data.category);
            addProductType();
            return $scope.data.category;
          }
        }
      },
    ]
  });
  myPopup.then(function (res) {
    $log.log('Tapped!', res);
  });
}

Body:
i had founded by adding translate.instant

function showPopup () {
  $scope.data = {};
  var myPopup = $ionicPopup.show({
    template: '<input type="text" ng-model="data.category">',
    // title: 'Enter CoconutType',
    title: $translate.instant('{{"farmers_message" | translate}}'),
    scope: $scope,
    buttons: [
     { text: 'Cancel' },
      {
        text: $translate.instant('{{"save_message" | translate}}'),
        type: 'button-positive',
        onTap: function (e) {
          if (!$scope.data.category) {
            //don't allow the user to close unless he enters producttype
            e.preventDefault();

          } else {
            $log.log('yes clicked: ', $scope.data.category);
            addProductType();
            return $scope.data.category;
          }
        }
      },
    ]
  });
  myPopup.then(function (res) {
    $log.log('Tapped!', res);
  });
}


问:
How to use a separate Enum class in my form
I have a function like this

```<code>        public void SetOperationDropDown()
        {

        int ? cbSelectedValue = null;
        if(cmbOperations.Items.Count == 0)

            {

            //ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-.
            cmbOperations.SelectedItem = "-SELECT OPERATIONS-";
            //This is for adding four operations with value in operation dropdown
            cmbOperations.Items.Insert(0, "PrimaryKeyTables");
            cmbOperations.Items.Insert(1, "NonPrimaryKeyTables");
            cmbOperations.Items.Insert(2, "ForeignKeyTables");
            cmbOperations.Items.Insert(3, "NonForeignKeyTables");
            cmbOperations.Items.Insert(4, "UPPERCASEDTables");
            cmbOperations.Items.Insert(5, "lowercasedtables");
            }
        else
            {
            if(!string.IsNullOrEmpty("cmbOperations.SelectedValue"))
                cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue);
            }
        //Load the combo box cmbOperations again
        if(cbSelectedValue != null)
            cmbOperations.SelectedValue = cbSelectedValue.ToString();
        }
</code>```

But what I need to do if I want this function to be defined in a separate enum class and then being called.

答:
It is not very clear what you actually want to obtain. If you want your hardcoded strings to be defined in an enum you could define it like this:

```<code>enum Tables
{
    PrimaryKeyTables,
    NonPrimaryKeyTables,
    ForeignKeyTables,
    NonForeignKeyTables,
    UPPERCASEDTables,
    lowercasedtables,
}
</code>```

Be aware that your string.IsNullOrEmpty("cmbOperations.SelectedValue"); always will return false since you are testing the specified string. You might want to test this instead:

```<code>cmbOperations.SelectedItem != null
</code>```

To assign your Tables enum from your selection you can do like this:

```<code>Tables cbSelectedValue = (Tables)Enum.Parse(typeof(Tables), cmbOperations.SelectedItem.ToString());
</code>```

Body:
I have a function like this

        public void SetOperationDropDown()
        {

        int ? cbSelectedValue = null;
        if(cmbOperations.Items.Count == 0)

            {

            //ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-.
            cmbOperations.SelectedItem = "-SELECT OPERATIONS-";
            //This is for adding four operations with value in operation dropdown
            cmbOperations.Items.Insert(0, "PrimaryKeyTables");
            cmbOperations.Items.Insert(1, "NonPrimaryKeyTables");
            cmbOperations.Items.Insert(2, "ForeignKeyTables");
            cmbOperations.Items.Insert(3, "NonForeignKeyTables");
            cmbOperations.Items.Insert(4, "UPPERCASEDTables");
            cmbOperations.Items.Insert(5, "lowercasedtables");
            }
        else
            {
            if(!string.IsNullOrEmpty("cmbOperations.SelectedValue"))
                cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue);
            }
        //Load the combo box cmbOperations again
        if(cbSelectedValue != null)
            cmbOperations.SelectedValue = cbSelectedValue.ToString();
        }

But what I need to do if I want this function to be defined in a separate enum class and then being called.

Body:
It is not very clear what you actually want to obtain. If you want your hardcoded strings to be defined in an enum you could define it like this:

enum Tables
{
    PrimaryKeyTables,
    NonPrimaryKeyTables,
    ForeignKeyTables,
    NonForeignKeyTables,
    UPPERCASEDTables,
    lowercasedtables,
}

Be aware that your string.IsNullOrEmpty("cmbOperations.SelectedValue"); always will return false since you are testing the specified string. You might want to test this instead:

cmbOperations.SelectedItem != null

To assign your Tables enum from your selection you can do like this:

Tables cbSelectedValue = (Tables)Enum.Parse(typeof(Tables), cmbOperations.SelectedItem.ToString());


问:
Akka: How to get Children actor on Restart
When the System is restarted, the context.children() call returns zero children for a particular parent.  Before restart, context.children() returned the actual count of children that parent had.

Can someone please let me know how can we get the children ActorRef for a parent after restart?

My use case is:

Before restart, there are let say 5 children of a parent. Now, i wish to calculate performance and to calculate performance i need participation from all these 5 children. So, after restart, i could just send the same message to all children, after which children will work and respond to parent. However, after restart, i am not even aware of who the children were. So, what's the best way to solve these type of problems?

答: One way is to make the parent actor persistent while making its state as list of children ids. This way, when the system restarts and parent is re-created, it will restore its state.</p>


问:
java.lang.NoClassDefFoundError: Could not initialize class xxx.xxx.xxx.HibernateUtil
Herewith I added my source code of web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>ussd</display-name>
    <servlet>
        <servlet-name>init</servlet-name>
        <jsp-file>/init.jsp</jsp-file>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <context-param>
        <param-name>javax.ws.rs.core.Application</param-name>
        <param-value>com.dialog.mife.ussd.api.USSDApplication</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.providers</param-name>
        <param-value>com.dialog.mife.ussd.exception.NotFoundException</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/</param-value>
    </context-param>
    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/webresources/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

Hibernate.cfg.xml.
My Web service project goes with Jersey+Hibernate..

```<code>    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">xxx</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/USSD</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.connection.autocommit">true</property>
        <mapping class="com.xxx.xxx.xxx.xxx.Application" />

    </session-factory>
</hibernate-configuration>
</code>```

Here is HibernateUtil Class

```<code>public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }
</code>```

Here is my error
I added Hibernate latest jar files.
[hibernate-core-4.3.7.Final.jar]

```<code>SEVERE: StandardWrapper.Throwable
java.lang.NoClassDefFoundError: Could not initialize class com.dialog.mife.ussd.util.HibernateUtil
    at org.apache.jsp.init_jsp.jspInit(init_jsp.java:23)
    at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:48)
    at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:180)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Nov 11, 2014 2:06:11 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /ussd threw load() exception
java.lang.NoClassDefFoundError: Could not initialize class com.dialog.mife.ussd.util.HibernateUtil
    at org.apache.jsp.init_jsp.jspInit(init_jsp.java:23)
    at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:48)
    at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:180)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
</code>```

Please help me to sort out this issue
thanks

答: In the HibernateUtils, there is reference for the "/hibernate.cfg.xml" file. In which we have to add the hbm.xml mapping. also confirm that mapping file present in the resource file.</p>

Body:
Herewith I added my source code of web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>ussd</display-name>
    <servlet>
        <servlet-name>init</servlet-name>
        <jsp-file>/init.jsp</jsp-file>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <context-param>
        <param-name>javax.ws.rs.core.Application</param-name>
        <param-value>com.dialog.mife.ussd.api.USSDApplication</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.providers</param-name>
        <param-value>com.dialog.mife.ussd.exception.NotFoundException</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/</param-value>
    </context-param>
    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/webresources/*</url-pattern>
    </servlet-mapping>
</web-app>

Hibernate.cfg.xml.
My Web service project goes with Jersey+Hibernate..

    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">xxx</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/USSD</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.connection.autocommit">true</property>
        <mapping class="com.xxx.xxx.xxx.xxx.Application" />

    </session-factory>
</hibernate-configuration>

Here is HibernateUtil Class

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }

Here is my error
I added Hibernate latest jar files.
[hibernate-core-4.3.7.Final.jar]

SEVERE: StandardWrapper.Throwable
java.lang.NoClassDefFoundError: Could not initialize class com.dialog.mife.ussd.util.HibernateUtil
    at org.apache.jsp.init_jsp.jspInit(init_jsp.java:23)
    at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:48)
    at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:180)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Nov 11, 2014 2:06:11 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /ussd threw load() exception
java.lang.NoClassDefFoundError: Could not initialize class com.dialog.mife.ussd.util.HibernateUtil
    at org.apache.jsp.init_jsp.jspInit(init_jsp.java:23)
    at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:48)
    at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:180)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Please help me to sort out this issue
thanks