问:
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.

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

remove finish() from onLogin method

Because AsyncTask working background you call finish method to finish current activity.

```<code>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(); remove it
}
</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:
public void onLoginSuccess() {
    startActivity(new Intent(Login.this, Main.class));
}

remove finish() from onLogin method

Because AsyncTask working background you call finish method to finish current activity.

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(); remove it
}


来源: stackexchange

答:
Use Current Activity context in first param</p>

```<code>startActivity(new Intent(Login.this, Main.class));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Start activity crashes app else the app is minimazin

Body:
Use Current Activity context in first param

startActivity(new Intent(Login.this, Main.class));


问:
Rails: Query database for users with specific time value while respect individual users time zone setting
I have a background job that runs every 15 minutes and generates reminder emails. I would like to create a query that returns all users who have a specific time saved and respect how their timezone setting effects that time.

So I have a User model that stores:

:time: a users reminder time, eg 17:00:00

:string: their timezone, eg EST

So if the job runs at 17:00:00 EST, it will return users whose settings are:

reminder_time: 17:00:00, time_zone: EST

reminder_time: 13:00:00, time_zone: PST

What is the best way to build that query? Can it be done in one pass, relying on Postgres to handle the work? Do I have to stagger it, group by each time zone and doing the math for each on in Ruby?

I currently have this setup as an ActiveRecord scope that doesn't consider timezones, and I am trying to add that consideration now.

```<code>scope :receives_reminder_at, -> (time) do
  ready.where(reminder_time: time)
end
</code>```

答:
Just met same problem. And found article how to make it, just how to think solve it myself. But with ready code. https://robots.thoughtbot.com/a-case-study-in-multiple-time-zones

Main idea is to:

At first you find timezones which have specific time now.

```<code>module ActiveSupport
  class TimeZone
    def self.current_zones(hour)
      all.select { |zone|
        t = Time.current.in_time_zone(zone)
        t.hour == hour
      }.map(&:tzinfo).map(&:name)
    end
  end
end
</code>```

You find users with this timezone.

```<code>User.where(zone: ActiveSupport::TimeZone.current_zones(hour)).where(options)
</code>```

Body:
I have a background job that runs every 15 minutes and generates reminder emails. I would like to create a query that returns all users who have a specific time saved and respect how their timezone setting effects that time.

So I have a User model that stores:

:time: a users reminder time, eg 17:00:00

:string: their timezone, eg EST

So if the job runs at 17:00:00 EST, it will return users whose settings are:

reminder_time: 17:00:00, time_zone: EST

reminder_time: 13:00:00, time_zone: PST

What is the best way to build that query? Can it be done in one pass, relying on Postgres to handle the work? Do I have to stagger it, group by each time zone and doing the math for each on in Ruby?

I currently have this setup as an ActiveRecord scope that doesn't consider timezones, and I am trying to add that consideration now.

scope :receives_reminder_at, -> (time) do
  ready.where(reminder_time: time)
end

Body:
Just met same problem. And found article how to make it, just how to think solve it myself. But with ready code. https://robots.thoughtbot.com/a-case-study-in-multiple-time-zones

Main idea is to:

At first you find timezones which have specific time now.

module ActiveSupport
  class TimeZone
    def self.current_zones(hour)
      all.select { |zone|
        t = Time.current.in_time_zone(zone)
        t.hour == hour
      }.map(&:tzinfo).map(&:name)
    end
  end
end

You find users with this timezone.

User.where(zone: ActiveSupport::TimeZone.current_zones(hour)).where(options)


问:
Newbie stuck on a jQuery question...conditional statement
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total') == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>
</code>```

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

```<code><span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
</code>```

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

答:
the below should work...please try </p>

```<code><script type="text/javascript">
    $(document).ready(function(){
     if($('.fc_cart_item_price_total').text() == 0) {
      $('.fc_info').addClass('foo');
     };
    });
    </script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

Info 1

$0.00

Info 2

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

Body:
the below should work...please try

<script type="text/javascript">
    $(document).ready(function(){
     if($('.fc_cart_item_price_total').text() == 0) {
      $('.fc_info').addClass('foo');
     };
    });
    </script>


问:
C++ - Method/Member access
We all know that private methods and members are only accessable inside the class, same way that protected methods and members are accessable inside the class and classes that derived from that class. But where is the «access control» of this? Does the «access control» happen in compile time, or does the compiler add addional machine code that controls that in runtime?

Can I create a class like this:

```<code>class Print
{
        public:
                void printPublic();

        private:
                void printPrivate();
};

int main()
{
        Print print;

        print.printPublic() // Change this to printPrivate() after compiling the code

        return(EXIT_SUCCESS);
}
</code>```

And then after compiling the code edit the machine code to call printPrivate() instead of printPublic() method without error?

答: The «access control» happen at compile time</p>

Title: C++ - Method/Member access

Body:
We all know that private methods and members are only accessable inside the class, same way that protected methods and members are accessable inside the class and classes that derived from that class. But where is the «access control» of this? Does the «access control» happen in compile time, or does the compiler add addional machine code that controls that in runtime?

Can I create a class like this:

class Print
{
        public:
                void printPublic();

        private:
                void printPrivate();
};

int main()
{
        Print print;

        print.printPublic() // Change this to printPrivate() after compiling the code

        return(EXIT_SUCCESS);
}

And then after compiling the code edit the machine code to call printPrivate() instead of printPublic() method without error?


问:
HybridAuth Facebook returned an invalid user id
I am getting the following error:

```<code>Authentication failed. The user has canceled the authentication or the provider refused the connection.
Original error message: Authentication failed! Facebook returned an invalid user id.
</code>```

tried a lot of things like to add in the base_facebook.php

```<code>CURLOPT_SSL_VERIFYPEER => false
</code>```

aswell as to improve the curl timeout, but it wont works.

The app isnt in facebook sandbox mode anymore so I literally have no guess left.

答:
Recently this occurred due to facebook graph API change, v2.2 is depreciate
https://developers.facebook.com/docs/apps/changelog

So we need to change php facebook-sdk for facebook graph api latest version v2.8. you can download the sdk from https://github.com/facebook/php-graph-sdk

after replacing sdk you may need to add auto-load configurations for facebook sdk.

Body:
I am getting the following error:

Authentication failed. The user has canceled the authentication or the provider refused the connection.
Original error message: Authentication failed! Facebook returned an invalid user id.

tried a lot of things like to add in the base_facebook.php

CURLOPT_SSL_VERIFYPEER => false

aswell as to improve the curl timeout, but it wont works.

The app isnt in facebook sandbox mode anymore so I literally have no guess left.


问:
Undefined index from paypal shipping details
I got this Error message from paypal shipping details

Notice: Undefined index: SALUTATION in
  /var/www/html/pp/temp/review.php on line 41

Notice: Undefined index: MIDDLENAME in
  /var/www/html/pp/temp/review.php on line 43

Notice: Undefined index: SUFFIX in /var/www/html/pp/temp/review.php on
  line 45

Notice: Undefined index: SHIPTOSTREET2 in
  /var/www/html/pp/temp/review.php on line 50

Notice: Undefined index: INVNUM in /var/www/html/pp/temp/review.php on
  line 56

Notice: Undefined index: PHONENUM in /var/www/html/pp/temp/review.php
  on line 57

I tried this

```<code>if( $ack == "SUCCESS" || $ack == "SUCESSWITHWARNING")
    {
          ///  echo '```';print_r($resArray);exit;
        /*
        ' The information that is returned by the GetExpressCheckoutDetails call should be integrated by the partner into his Order Review
        ' page
        */
        $email              = $resArray["EMAIL"]; // ' Email address of payer.
        $payerId            = $resArray["PAYERID"]; // ' Unique PayPal customer account identification number.
        $payerStatus        = $resArray["PAYERSTATUS"]; // ' Status of payer. Character length and limitations: 10 single-byte alphabetic characters.
        $salutation         = $resArray["SALUTATION"]?$resArray["SALUTATION"]:''; // ' Payer's salutation.
        $firstName          = $resArray["FIRSTNAME"]; // ' Payer's first name.
        $middleName         = $resArray["MIDDLENAME"]?$resArray["MIDDLENAME"]:''; // ' Payer's middle name.
        $lastName           = $resArray["LASTNAME"]; // ' Payer's last name.
        $suffix             = $resArray["SUFFIX"]?$resArray["SUFFIX"]:''; // ' Payer's suffix.
        $cntryCode          = $resArray["COUNTRYCODE"]; // ' Payer's country of residence in the form of ISO standard 3166 two-character country codes.
        $business           = $resArray["BUSINESS"]; // ' Payer's business name.
        $shipToName         = $resArray["SHIPTONAME"]; // ' Person's name associated with this address.
        $shipToStreet       = $resArray["SHIPTOSTREET"]; // ' First street address.
        $shipToStreet2      = $resArray["SHIPTOSTREET2"]?$resArray["SHIPTOSTREET2"]:''; // ' Second street address.
        $shipToCity         = $resArray["SHIPTOCITY"]; // ' Name of city.
        $shipToState        = $resArray["SHIPTOSTATE"]; // ' State or province
        $shipToCntryCode    = $resArray["SHIPTOCOUNTRYCODE"]; // ' Country code.
        $shipToZip          = $resArray["SHIPTOZIP"]; // ' U.S. Zip code or other country-specific postal code.
        $addressStatus      = $resArray["ADDRESSSTATUS"]; // ' Status of street address on file with PayPal
        $invoiceNumber      = $resArray["INVNUM"]?$resArray["INVNUM"]:''; // ' Your own invoice or tracking number, as set by you in the element of the same name in SetExpressCheckout request .
        $phonNumber         = $resArray["PHONENUM"]?$resArray["PHONENUM"]:''; // ' Payer's contact telephone number. Note:  PayPal returns a contact telephone number only if your Merchant account profile settings require that the buyer enter one.

    }
```

But still the same issue.How can i resolve this issue?please help me

答:
use isset () function is used to check whether a variable is set or not.
replace

```<code>$salutation         = $resArray["SALUTATION"]?$resArray["SALUTATION"]:'';
</code>```

to

```<code> $salutation = $resArray["SALUTATION"] ?? "default"; (for php 7)
$var = isset($resArray["SALUTATION"]) ? $resArray["SALUTATION"] : "default"; (before php 7)
</code>```

similarly all.

Body:
I got this Error message from paypal shipping details

Notice: Undefined index: SALUTATION in
  /var/www/html/pp/temp/review.php on line 41

Notice: Undefined index: MIDDLENAME in
  /var/www/html/pp/temp/review.php on line 43

Notice: Undefined index: SUFFIX in /var/www/html/pp/temp/review.php on
  line 45

Notice: Undefined index: SHIPTOSTREET2 in
  /var/www/html/pp/temp/review.php on line 50

Notice: Undefined index: INVNUM in /var/www/html/pp/temp/review.php on
  line 56

Notice: Undefined index: PHONENUM in /var/www/html/pp/temp/review.php
  on line 57

I tried this

if( $ack == "SUCCESS" || $ack == "SUCESSWITHWARNING")
    {
          ///  echo '
';print_r($resArray);exit;
        /*
        ' The information that is returned by the GetExpressCheckoutDetails call should be integrated by the partner into his Order Review
        ' page
        */
        $email              = $resArray["EMAIL"]; // ' Email address of payer.
        $payerId            = $resArray["PAYERID"]; // ' Unique PayPal customer account identification number.
        $payerStatus        = $resArray["PAYERSTATUS"]; // ' Status of payer. Character length and limitations: 10 single-byte alphabetic characters.
        $salutation         = $resArray["SALUTATION"]?$resArray["SALUTATION"]:''; // ' Payer's salutation.
        $firstName          = $resArray["FIRSTNAME"]; // ' Payer's first name.
        $middleName         = $resArray["MIDDLENAME"]?$resArray["MIDDLENAME"]:''; // ' Payer's middle name.
        $lastName           = $resArray["LASTNAME"]; // ' Payer's last name.
        $suffix             = $resArray["SUFFIX"]?$resArray["SUFFIX"]:''; // ' Payer's suffix.
        $cntryCode          = $resArray["COUNTRYCODE"]; // ' Payer's country of residence in the form of ISO standard 3166 two-character country codes.
        $business           = $resArray["BUSINESS"]; // ' Payer's business name.
        $shipToName         = $resArray["SHIPTONAME"]; // ' Person's name associated with this address.
        $shipToStreet       = $resArray["SHIPTOSTREET"]; // ' First street address.
        $shipToStreet2      = $resArray["SHIPTOSTREET2"]?$resArray["SHIPTOSTREET2"]:''; // ' Second street address.
        $shipToCity         = $resArray["SHIPTOCITY"]; // ' Name of city.
        $shipToState        = $resArray["SHIPTOSTATE"]; // ' State or province
        $shipToCntryCode    = $resArray["SHIPTOCOUNTRYCODE"]; // ' Country code.
        $shipToZip          = $resArray["SHIPTOZIP"]; // ' U.S. Zip code or other country-specific postal code.
        $addressStatus      = $resArray["ADDRESSSTATUS"]; // ' Status of street address on file with PayPal
        $invoiceNumber      = $resArray["INVNUM"]?$resArray["INVNUM"]:''; // ' Your own invoice or tracking number, as set by you in the element of the same name in SetExpressCheckout request .
        $phonNumber         = $resArray["PHONENUM"]?$resArray["PHONENUM"]:''; // ' Payer's contact telephone number. Note:  PayPal returns a contact telephone number only if your Merchant account profile settings require that the buyer enter one.

    }

But still the same issue.How can i resolve this issue?please help me

Body:
use isset () function is used to check whether a variable is set or not.
replace

$salutation         = $resArray["SALUTATION"]?$resArray["SALUTATION"]:'';

to

 $salutation = $resArray["SALUTATION"] ?? "default"; (for php 7)
$var = isset($resArray["SALUTATION"]) ? $resArray["SALUTATION"] : "default"; (before php 7)

similarly all.


问:
Different button, same navigation activity, but the result from fragment in navigation activity is different
i had a problem. I have many button with looping, and i want to intent them into same activity(navigation activity) but i want the result of fragment from navigation is different. Can you help me to solve this?

ButtonSelectActivity (the place of the button)

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

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

    LinearLayout f = (LinearLayout) findViewById(R.id.lala);
    f.setOrientation(LinearLayout.VERTICAL);

    for (int i = 0; i <= 6; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        for (int a = 0; a <= 7; a++) {
            for (int l = 65; l <= 90; l++) {
                Button button = new Button(this);
                button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                button.setText("" + (char) (l + (i * 4)));
                button.setId((char) (l + (i * 4)));
                row.addView(button);

                final String id = String.valueOf((char) (l + (i * 4)));
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(ButtonSelectActivity.this, Main2Activity.class));
                    }
                });
            }
        }
        f.addView(row);
    }
}}
</code>```

And this the activity result

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

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        if (position == 1) {
            return new FragmentDua();
        } else if (position == 0) {
            return new FragmentSatu();
        } else if (position == 2) {
            return new FragmentTiga();
        } else
            return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}
</code>```

}

Thankyou before :)

答:
Assuming you want different result depends on what button is clicked.

Just pass your final String id in bundle to Main2Activity.class

So you should have in ButtonSelectActivity class

```<code>    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(ButtonSelectActivity .this, Main2Activity.class);
        intent.putExtra("key", id);
        startActivity(intent);
      }
    });
</code>```

And inside onCreate of Main2Activity class

```<code>int id = getIntent().getExtras().getInt("key");
</code>```

Then you can show what you need depends on this id variable

UPD:

Also better practice is using RecyclerView where its elements contains Buttons. Would be the same but easier to work with.

Body:
i had a problem. I have many button with looping, and i want to intent them into same activity(navigation activity) but i want the result of fragment from navigation is different. Can you help me to solve this?

ButtonSelectActivity (the place of the button)

public class ButtonSelectActivity extends AppCompatActivity {

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

    LinearLayout f = (LinearLayout) findViewById(R.id.lala);
    f.setOrientation(LinearLayout.VERTICAL);

    for (int i = 0; i <= 6; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        for (int a = 0; a <= 7; a++) {
            for (int l = 65; l <= 90; l++) {
                Button button = new Button(this);
                button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                button.setText("" + (char) (l + (i * 4)));
                button.setId((char) (l + (i * 4)));
                row.addView(button);

                final String id = String.valueOf((char) (l + (i * 4)));
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(ButtonSelectActivity.this, Main2Activity.class));
                    }
                });
            }
        }
        f.addView(row);
    }
}}

And this the activity result

public class Main2Activity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        if (position == 1) {
            return new FragmentDua();
        } else if (position == 0) {
            return new FragmentSatu();
        } else if (position == 2) {
            return new FragmentTiga();
        } else
            return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

Thankyou before :)

Body:
Assuming you want different result depends on what button is clicked.

Just pass your final String id in bundle to Main2Activity.class

So you should have in ButtonSelectActivity class

    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(ButtonSelectActivity .this, Main2Activity.class);
        intent.putExtra("key", id);
        startActivity(intent);
      }
    });

And inside onCreate of Main2Activity class

int id = getIntent().getExtras().getInt("key");

Then you can show what you need depends on this id variable

UPD:

Also better practice is using RecyclerView where its elements contains Buttons. Would be the same but easier to work with.


问:
Find and remove parameter declaration inside Expression.Block
I know how to replace a parameter with ExpressionVisitor but I was wondering if there's a way to remove a parameter from a Expression.Block.

Ideally I should crawl the entire Expression tree and remove the parameter every time it is declared inside a Block.

Any idea how to do that with ExpressionVisitor?

答:
A simple class to remove local variables from a BlockExpression and replace them with whatever you want.

```<code>public class BlockVariableRemover : ExpressionVisitor
{
    private readonly Dictionary<Expression, Expression> replaces = new Dictionary<Expression, Expression>();

    public readonly Func<ParameterExpression, int, Expression> Replacer;

    public BlockVariableRemover(Func<ParameterExpression, int, Expression> replacer)
    {
        Replacer = replacer;
    }

    protected override Expression VisitBlock(BlockExpression node)
    {
        var removed = new List<Expression>();

        var variables = node.Variables.ToList();

        for (int i = 0; i < variables.Count; i++)
        {
            var variable = variables[i];
            var to = Replacer(variable, i);

            if (to != variable)
            {
                removed.Add(variable);
                replaces.Add(variable, to);
                variables.RemoveAt(i);
                i--;
            }
        }

        if (removed.Count == 0)
        {
            return base.VisitBlock(node);
        }

        var expressions = node.Expressions.ToArray();

        for (int i = 0; i < expressions.Length; i++)
        {
            expressions[i] = Visit(expressions[i]);
        }

        foreach (var rem in removed)
        {
            replaces.Remove(rem);
        }

        return Expression.Block(variables, expressions);
    }

    public override Expression Visit(Expression node)
    {
        Expression to;

        if (node != null && replaces.TryGetValue(node, out to))
        {
            return base.Visit(to);
        }

        return base.Visit(node);
    }
}
</code>```

Use it like:

```<code>Expression<Func<int, int>> exp;

{
    var var1 = Expression.Variable(typeof(int), "var1");
    var var2 = Expression.Variable(typeof(long), "var2");

    var par1 = Expression.Parameter(typeof(int), "par1");

    var block = Expression.Block(new[] { var1, var2 }, Expression.Increment(var1));

    exp = Expression.Lambda<Func<int, int>>(block, par1);

    // Test
    var compiled = exp.Compile();
    Console.WriteLine(compiled(10));
}

// Begin replace
{
    var par1 = exp.Parameters[0];

    var block2 = new BlockVariableRemover(
        // ix is the index of the variable,
        // return x if you don't want to modify,
        // return whatever you want (even Expression.Empty()) to do
        // a replace
        (x, ix) => ix == 0 && x.Type == typeof(int) ? par1 : x)
        .Visit(exp.Body);

    // Final result
    var exp2 = Expression.Lambda<Func<int, int>>(block2, par1);

    // Test
    var compiled = exp2.Compile();
    Console.WriteLine(compiled(10));
}
</code>```

Body:
A simple class to remove local variables from a BlockExpression and replace them with whatever you want.

public class BlockVariableRemover : ExpressionVisitor
{
    private readonly Dictionary<Expression, Expression> replaces = new Dictionary<Expression, Expression>();

    public readonly Func<ParameterExpression, int, Expression> Replacer;

    public BlockVariableRemover(Func<ParameterExpression, int, Expression> replacer)
    {
        Replacer = replacer;
    }

    protected override Expression VisitBlock(BlockExpression node)
    {
        var removed = new List<Expression>();

        var variables = node.Variables.ToList();

        for (int i = 0; i < variables.Count; i++)
        {
            var variable = variables[i];
            var to = Replacer(variable, i);

            if (to != variable)
            {
                removed.Add(variable);
                replaces.Add(variable, to);
                variables.RemoveAt(i);
                i--;
            }
        }

        if (removed.Count == 0)
        {
            return base.VisitBlock(node);
        }

        var expressions = node.Expressions.ToArray();

        for (int i = 0; i < expressions.Length; i++)
        {
            expressions[i] = Visit(expressions[i]);
        }

        foreach (var rem in removed)
        {
            replaces.Remove(rem);
        }

        return Expression.Block(variables, expressions);
    }

    public override Expression Visit(Expression node)
    {
        Expression to;

        if (node != null && replaces.TryGetValue(node, out to))
        {
            return base.Visit(to);
        }

        return base.Visit(node);
    }
}

Use it like:

Expression<Func<int, int>> exp;

{
    var var1 = Expression.Variable(typeof(int), "var1");
    var var2 = Expression.Variable(typeof(long), "var2");

    var par1 = Expression.Parameter(typeof(int), "par1");

    var block = Expression.Block(new[] { var1, var2 }, Expression.Increment(var1));

    exp = Expression.Lambda<Func<int, int>>(block, par1);

    // Test
    var compiled = exp.Compile();
    Console.WriteLine(compiled(10));
}

// Begin replace
{
    var par1 = exp.Parameters[0];

    var block2 = new BlockVariableRemover(
        // ix is the index of the variable,
        // return x if you don't want to modify,
        // return whatever you want (even Expression.Empty()) to do
        // a replace
        (x, ix) => ix == 0 && x.Type == typeof(int) ? par1 : x)
        .Visit(exp.Body);

    // Final result
    var exp2 = Expression.Lambda<Func<int, int>>(block2, par1);

    // Test
    var compiled = exp2.Compile();
    Console.WriteLine(compiled(10));
}


问:
Print pdf on schedule automatically
I want schedule PDF print in my PHP MySQL application, let me explain in details.

In working hours I have set 50 pdf which I want to print after 12:00 AM, because in working hours printer is busy.

So how I can set schedule print pdf using PHP, I required directly call command from the server using CRON job so no required to On my PC.

Please help me.

答:
Use a cronjob with this setup:</p>

```<code>* 0 * * * [user] [path to your php] [path to your php script]
</code>```

Title: Print pdf on schedule automatically

Body:
Use a cronjob with this setup:

* 0 * * * [user] [path to your php] [path to your php script]


问:
Get the length of a video in Android
I want to get the length of a saved video from my device. I have tried with MediaMetadataRetriever but my application crashes. I am testing it on Android 6.0 but it is not working at all.

Below is my Activity.

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

    private static final int PICK_IMAGE_REQUEST = 1; // put it on the top.
    private Button btnOpenGallery;

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

        btnOpenGallery = (Button)findViewById(R.id.btnOpenGallery);
        btnOpenGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri selectedImageUri = data.getData();
            String strPath = selectedImageUri.getPath();
            Log.e("Path is ","===>"+strPath);

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(strPath); // Enter Full File Path Here
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            long timeInmillisec = Long.parseLong(time);
            Log.e("Media duration in ","==>"+timeInmillisec);

        }
    }
}
</code>```

答:
Try this:</p>

```<code>    MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Environment.getExternalStorageDirectory() + "/Downloads/" + "vid" + ".mp4")); // Downloads is the folder and vid is video file.
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            int duration = mp.getDuration();
            mp.release();
        }
    });
</code>```

Title: Get the length of a video in Android

Body:
I want to get the length of a saved video from my device. I have tried with MediaMetadataRetriever but my application crashes. I am testing it on Android 6.0 but it is not working at all.

Below is my Activity.

    public class MainActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1; // put it on the top.
    private Button btnOpenGallery;

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

        btnOpenGallery = (Button)findViewById(R.id.btnOpenGallery);
        btnOpenGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri selectedImageUri = data.getData();
            String strPath = selectedImageUri.getPath();
            Log.e("Path is ","===>"+strPath);

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(strPath); // Enter Full File Path Here
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            long timeInmillisec = Long.parseLong(time);
            Log.e("Media duration in ","==>"+timeInmillisec);

        }
    }
}

Body:
Try this:

    MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Environment.getExternalStorageDirectory() + "/Downloads/" + "vid" + ".mp4")); // Downloads is the folder and vid is video file.
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            int duration = mp.getDuration();
            mp.release();
        }
    });


问:
How can I pass code into a method without it running first?
Please help as how can I achieve below in java.

```<code>public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}
</code>```

I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is

```<code>TRUE
Printing iteration #1
</code>```

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

```<code>FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3
</code>```

答:
The point is:

```<code>ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
</code>```

In Java, all method arguments get evaluated (aka computed) before the invocation takes place.

In other words:

equals(1,1) will always result in true

thus always the first "Value" is returned (although that doesn't really matter; as you are using the same value in both cases)

as said, both calls to iterateValue() will be executed; that means that this method is invoked twice, with the respective arguments for each call.

So, if you want to call iterateValue() only once; you should not use it as parameter. Instead, go for something like:

```<code>ifElse(equals(1,1), "ValueA", "ValueB"));
</code>```

and then call iterateValue() on the first or second incoming String argument directly; and only once.

Body:
Please help as how can I achieve below in java.

public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}

I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is

TRUE
Printing iteration #1

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3

Body:
The point is:

ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));

In Java, all method arguments get evaluated (aka computed) before the invocation takes place.

In other words:

equals(1,1) will always result in true

thus always the first "Value" is returned (although that doesn't really matter; as you are using the same value in both cases)

as said, both calls to iterateValue() will be executed; that means that this method is invoked twice, with the respective arguments for each call.

So, if you want to call iterateValue() only once; you should not use it as parameter. Instead, go for something like:

ifElse(equals(1,1), "ValueA", "ValueB"));

and then call iterateValue() on the first or second incoming String argument directly; and only once.


问:
How to set ProgressBar at the center screen in frame layout?
I am using following code, but my progress bar is not displaying in the center of frame layout. I want to avoid padding to my progressbar.Can any one please explain? It is perfectly working if i am using "Linear Layout"</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal">

    <ProgressBar android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView android:id="@+id/gallery_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

 </FrameLayout>
</code>```

答: you must set the postion in pixels as in framelayout different components overlap each other. So, you can try it by setting pixels in dip.</p>

Body:
I am using following code, but my progress bar is not displaying in the center of frame layout. I want to avoid padding to my progressbar.Can any one please explain? It is perfectly working if i am using "Linear Layout"

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal">

    <ProgressBar android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView android:id="@+id/gallery_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

 </FrameLayout>


问:
SQLAlchemy Query returning None
I have a web application using SQLAlchemy and MySQL-server on my ubuntu 16 & Nginx + uwsgi.

while creating the engine, i put

```<code>echo=True
</code>```

to get tracing of the query. I have problem registering user, everytime user_loader is called on flask login, I execute:

```<code>dbsession.query(User).filter_by(id=user_id).first()
</code>```

The result i get is :

```<code>INFO sqlalchemy.engine.base.Engine SELECT user.id AS user_id, user.name AS user_name, user.email AS user_email, user.pass$
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: FROM user
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: WHERE user.id = %s
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]:  LIMIT %s
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: 2017-03-29 23:48:56,517 INFO sqlalchemy.engine.base.Engine ('61', 1)
</code>```

The result is None. However, the on the above example, using user_id = 61 , , I can find the user on mysql shell in ubuntu to get user id 61.

When i refresh the page a few times, then the result will come out.
Once user finished registering, they will be redirected to login page, upon completing the form, it shows error "Please register", which is triggered if user is now found using this query:

```<code>dbsession.query(User).filter_by(id=user_id).first()
</code>```

On registration my code is:

```<code>user = User(name=name, email=email, password=password)
dbsession.add(user)
dbsession.commit()
return redirect(url_for('login'))
</code>```

checking has been done to ensure name, email password is valid.

Thanks

答:
Solved the problem.

Thanks to @iljaEverila.

Basically I need to make sure the dbsession from SQLAlchemy has persisted the data and there is no pending transaction. So that once user registered and user_loader is invoke, i just need to call:

```<code>dbsession.commit()
</code>```

Then calling this:

```<code>dbsession.query(User).filter_by(id=user_id).first()
</code>```

will be successful.

Thanks

Title: SQLAlchemy Query returning None

Body:
I have a web application using SQLAlchemy and MySQL-server on my ubuntu 16 & Nginx + uwsgi.

while creating the engine, i put

echo=True

to get tracing of the query. I have problem registering user, everytime user_loader is called on flask login, I execute:

dbsession.query(User).filter_by(id=user_id).first()

The result i get is :

INFO sqlalchemy.engine.base.Engine SELECT user.id AS user_id, user.name AS user_name, user.email AS user_email, user.pass$
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: FROM user
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: WHERE user.id = %s
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]:  LIMIT %s
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: 2017-03-29 23:48:56,517 INFO sqlalchemy.engine.base.Engine ('61', 1)

The result is None. However, the on the above example, using user_id = 61 , , I can find the user on mysql shell in ubuntu to get user id 61.

When i refresh the page a few times, then the result will come out.
Once user finished registering, they will be redirected to login page, upon completing the form, it shows error "Please register", which is triggered if user is now found using this query:

dbsession.query(User).filter_by(id=user_id).first()

On registration my code is:

user = User(name=name, email=email, password=password)
dbsession.add(user)
dbsession.commit()
return redirect(url_for('login'))

checking has been done to ensure name, email password is valid.

Thanks

Body:
Solved the problem.

Thanks to @iljaEverila.

Basically I need to make sure the dbsession from SQLAlchemy has persisted the data and there is no pending transaction. So that once user registered and user_loader is invoke, i just need to call:

dbsession.commit()

Then calling this:

dbsession.query(User).filter_by(id=user_id).first()

will be successful.

Thanks


问:
Whats wrong with this GOTO command?
i've made this menu to select stuff but if i select start it crashes
i have no idea why. it must be an error in the code but this part is fairly new to me so i can't find the errors myself.
heres the code:</p>

```<code>@echo off
title Tic Tac Toe
set "22=  "
set "23=  "
set "24=  "
set "32=  "
set "33=  "
set "34=  "
set "42=  "
set "43=  "
set "44=  "
set "pos1=22"

:Start
color f0
cls
echo                 ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß
echo                 °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß
echo                 °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß
echo                                                        by SpoodyTheone

ping localhost -n 5 >nul

:menuSTART1
color 06
cls
echo ---------------------------------------------------------------------------
echo ^|                ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß          ^|
echo ^|                °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß          ^|
echo ^|                °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß          ^|
echo ---------------------------------------------------------------------------
echo                                PRESS E TO SELECT
echo                                    START^<
echo                                     HELP
echo                                     EXIT
:: Selection
choice /c:EWS >nul

if "%errorlevel%"=="1" goto game
if "%errorlevel%"=="2" goto menuSTART3
if "%errorlevel%"=="3" goto menuSTART2

:menuSTART2
color 06
cls
echo ---------------------------------------------------------------------------
echo ^|                ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß          ^|
echo ^|                °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß          ^|
echo ^|                °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß          ^|
echo ---------------------------------------------------------------------------
echo                                PRESS E TO SELECT
echo                                    START
echo                                     HELP^<
echo                                     EXIT
:: Selection
choice /c:EWS >nul

if "%errorlevel%"=="1" goto help
if "%errorlevel%"=="2" goto menuSTART1
if "%errorlevel%"=="3" goto menuSTART3

:menuSTART3
color 06
cls
echo ---------------------------------------------------------------------------
echo ^|                ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß          ^|
echo ^|                °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß          ^|
echo ^|                °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß          ^|
echo ---------------------------------------------------------------------------
echo                                PRESS E TO SELECT
echo                                    START
echo                                     HELP
echo                                     EXIT^<
:: Selection
choice /c:EWS >nul

if "%errorlevel%"=="1" exit
if "%errorlevel%"=="2" goto menuSTART2
if "%errorlevel%"=="3" goto menuSTART1

:help
cls
echo.
echo         CONTROLS
echo -------------------------
echo ^|WASD to move the marker^|
echo ^|      E to place       ^|
echo -------------------------
echo.
echo         OBJECTIVE
echo -------------------------
echo ^| get 3 in a row to win ^|
echo -------------------------
pause >nul
goto menuSTART1

:game
if %rpos1% LSS 22 set "rpos1=42"
if %rpos1% GTR 44 set "rpos1=24"
set "rpos1=X "
cls
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo Û%42%Û  Û%43%Û  Û%44%Û
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo.
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo Û%32%Û  Û%33%Û  Û%34%Û
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo.
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo Û%22%Û  Û%23%Û  Û%24%Û
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
choice /c:WASDE >nul
if "%errorlevel%"=="1" goto ad10
if "%errorlevel%"=="2" goto re1
if "%errorlevel%"=="3" goto re10
if "%errorlevel%"=="4" goto ad1
if "%errorlevel%"=="5" goto sel

::add and subtract
:ad10
set /a "rpos1=+10"
goto game

:re1
set /a "rpos1=-1"
goto game

:re10
set /a "rpos=-10"
goto game

:ad1
set /a "rpos1=+1"
</code>```

答:
The problem is this line, under game:

```<code>if %rpos1% LSS 22 set "rpos1=42"
</code>```

rpos1 is initially undefined, and as you have no quotes it's evaluating against nothing.

Title: Whats wrong with this GOTO command?

Body:
i've made this menu to select stuff but if i select start it crashes
i have no idea why. it must be an error in the code but this part is fairly new to me so i can't find the errors myself.
heres the code:

@echo off
title Tic Tac Toe
set "22=  "
set "23=  "
set "24=  "
set "32=  "
set "33=  "
set "34=  "
set "42=  "
set "43=  "
set "44=  "
set "pos1=22"

:Start
color f0
cls
echo                 ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß
echo                 °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß
echo                 °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß
echo                                                        by SpoodyTheone

ping localhost -n 5 >nul

:menuSTART1
color 06
cls
echo ---------------------------------------------------------------------------
echo ^|                ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß          ^|
echo ^|                °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß          ^|
echo ^|                °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß          ^|
echo ---------------------------------------------------------------------------
echo                                PRESS E TO SELECT
echo                                    START^<
echo                                     HELP
echo                                     EXIT
:: Selection
choice /c:EWS >nul

if "%errorlevel%"=="1" goto game
if "%errorlevel%"=="2" goto menuSTART3
if "%errorlevel%"=="3" goto menuSTART2

:menuSTART2
color 06
cls
echo ---------------------------------------------------------------------------
echo ^|                ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß          ^|
echo ^|                °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß          ^|
echo ^|                °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß          ^|
echo ---------------------------------------------------------------------------
echo                                PRESS E TO SELECT
echo                                    START
echo                                     HELP^<
echo                                     EXIT
:: Selection
choice /c:EWS >nul

if "%errorlevel%"=="1" goto help
if "%errorlevel%"=="2" goto menuSTART1
if "%errorlevel%"=="3" goto menuSTART3

:menuSTART3
color 06
cls
echo ---------------------------------------------------------------------------
echo ^|                ßßÛßß °ß° Ûßß   ßßÛßß ÛßßÛ Ûßß   ßßÛßß ÛßßÛ Ûßß          ^|
echo ^|                °±Û°° ßÛß Û°°   °±Û°° ÛÜÜÛ Û°°   °±Û°° Û°°Û Ûßß          ^|
echo ^|                °±Û°° ßßß ßßß   °±Û°° ß°°ß ßßß   °±Û°° ßßßß ßßß          ^|
echo ---------------------------------------------------------------------------
echo                                PRESS E TO SELECT
echo                                    START
echo                                     HELP
echo                                     EXIT^<
:: Selection
choice /c:EWS >nul

if "%errorlevel%"=="1" exit
if "%errorlevel%"=="2" goto menuSTART2
if "%errorlevel%"=="3" goto menuSTART1

:help
cls
echo.
echo         CONTROLS
echo -------------------------
echo ^|WASD to move the marker^|
echo ^|      E to place       ^|
echo -------------------------
echo.
echo         OBJECTIVE
echo -------------------------
echo ^| get 3 in a row to win ^|
echo -------------------------
pause >nul
goto menuSTART1

:game
if %rpos1% LSS 22 set "rpos1=42"
if %rpos1% GTR 44 set "rpos1=24"
set "rpos1=X "
cls
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo Û%42%Û  Û%43%Û  Û%44%Û
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo.
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo Û%32%Û  Û%33%Û  Û%34%Û
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo.
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
echo Û%22%Û  Û%23%Û  Û%24%Û
echo ÛÛÛÛ  ÛÛÛÛ  ÛÛÛÛ
choice /c:WASDE >nul
if "%errorlevel%"=="1" goto ad10
if "%errorlevel%"=="2" goto re1
if "%errorlevel%"=="3" goto re10
if "%errorlevel%"=="4" goto ad1
if "%errorlevel%"=="5" goto sel

::add and subtract
:ad10
set /a "rpos1=+10"
goto game

:re1
set /a "rpos1=-1"
goto game

:re10
set /a "rpos=-10"
goto game

:ad1
set /a "rpos1=+1"

Body:
The problem is this line, under game:

if %rpos1% LSS 22 set "rpos1=42"

rpos1 is initially undefined, and as you have no quotes it's evaluating against nothing.


问:
How to spool query results in oracle
I am trying to print query result. Here is the Oracle SQL Script:

```<code>set linesize 32767;
set pagesize 0;
set newpage 0;
set space 0;
set echo off;
set feedback off;
set verify off;
set heading off;
set sqlprompt '';
set trimspool on;
set headsep off;

spool C:\asd.tmp
SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID;
spool off;
</code>```

But the content of "asd.tmp" is that:

SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID

It prints just query text, not the result of it. How can I spool query results?

NOTE: I am using "sqldeveloper-4.0.3.16.84-x64" and it runned as administrator. Also setting properties given above may be non-sense. I have tried some combinations of them and executing just spool commands without settings.

Any other solution that I can execute in C++ is proper for me too.

答:
you can use command line/sqlplus. try save your script as a file, then in command line:</p>

```<code>    sqlplus -s [username]/[password]@[sid] @file_path > output.txt
</code>```

Title: How to spool query results in oracle

Body:
I am trying to print query result. Here is the Oracle SQL Script:

set linesize 32767;
set pagesize 0;
set newpage 0;
set space 0;
set echo off;
set feedback off;
set verify off;
set heading off;
set sqlprompt '';
set trimspool on;
set headsep off;

spool C:\asd.tmp
SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID;
spool off;

But the content of "asd.tmp" is that:

SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID

It prints just query text, not the result of it. How can I spool query results?

NOTE: I am using "sqldeveloper-4.0.3.16.84-x64" and it runned as administrator. Also setting properties given above may be non-sense. I have tried some combinations of them and executing just spool commands without settings.

Any other solution that I can execute in C++ is proper for me too.

Body:
you can use command line/sqlplus. try save your script as a file, then in command line:

    sqlplus -s [username]/[password]@[sid] @file_path > output.txt


问:
shell script command error
I try executing the CPU monitoring script below, and the script throws an error.  But direct execution of top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g' does not throw an error.  Can someone help here??

```<code> if (top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g') -gt 1 ; then
     echo ('CPU percentage is $CPU_PER, which is higher than 50%. Kindly login to server and validate the process.')
 else
     echo  ('Executing Else statement.')
 fi
</code>```

答:
I'm not sure what shell you're using but if you use Bash the commands would look like that:

```<code>#!/bin/bash

# ... code ...

op=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
if [ "y" = "$(echo | awk "($op > 1) { print \"y\"; }")" ]; then
    echo 'CPU Percentage is grater Which is Highere than 50% Kindly Login to server and validate the process'
else
    echo  'Excuting Else statement '
fi
</code>```

Also, since $(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g') doesn't always return a whole number, a normal -gt does not work. That's why I used awk in this example. It could also be done with bc but since not all distributions have that command pre-installed, I think the version above is the best in this case.

And here is the plain code for validating:

```<code>#!/bin/bash
op=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
num=1
if [ "y" = "$(echo | awk "($op > $num) { print \"y\"; }")" ]; then
    printf "\n${op} is bigger than ${num}\n\n"
else
    printf "\n${op} is smaller than ${num}\n\n"
fi
</code>```

Title: shell script command error

Body:
I try executing the CPU monitoring script below, and the script throws an error.  But direct execution of top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g' does not throw an error.  Can someone help here??

 if (top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g') -gt 1 ; then
     echo ('CPU percentage is $CPU_PER, which is higher than 50%. Kindly login to server and validate the process.')
 else
     echo  ('Executing Else statement.')
 fi

Body:
I'm not sure what shell you're using but if you use Bash the commands would look like that:

#!/bin/bash

# ... code ...

op=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
if [ "y" = "$(echo | awk "($op > 1) { print \"y\"; }")" ]; then
    echo 'CPU Percentage is grater Which is Highere than 50% Kindly Login to server and validate the process'
else
    echo  'Excuting Else statement '
fi

Also, since $(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g') doesn't always return a whole number, a normal -gt does not work. That's why I used awk in this example. It could also be done with bc but since not all distributions have that command pre-installed, I think the version above is the best in this case.

And here is the plain code for validating:

#!/bin/bash
op=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
num=1
if [ "y" = "$(echo | awk "($op > $num) { print \"y\"; }")" ]; then
    printf "\n${op} is bigger than ${num}\n\n"
else
    printf "\n${op} is smaller than ${num}\n\n"
fi


问:
How to use a CASE statement within a SELECT COUNT statement?
I need to make a case statement.

Depending on what the variables value is, it needs to select the correct column from the table

StartDate and EndDate are different variables.

There is a variable i created called Region which should determine what column the query selects.

EDIT: Region can either be 'EW' for England and Wales, 'SC' for Scotland or 'NI' for Northern Ireland.
If it is EW it should select column 1, SC for column 2, NI for column 3

```<code>SELECT
COUNT(COLUMN1)
FROM  bankholidays
WHERE COLUMN1 BETWEEN @StartDate AND @EndDate)
</code>```

答:
```<code>SELECT CASE
WHEN @Region = 'EW' THEN columnName
WHEN @Region = 'SC' THEN columnName
WHEN @Region = 'NI' THEN columnName
END AS newColumnName FROM bankholidaysT
</code>```

Try something like this

Body:
I need to make a case statement.

Depending on what the variables value is, it needs to select the correct column from the table

StartDate and EndDate are different variables.

There is a variable i created called Region which should determine what column the query selects.

EDIT: Region can either be 'EW' for England and Wales, 'SC' for Scotland or 'NI' for Northern Ireland.
If it is EW it should select column 1, SC for column 2, NI for column 3

SELECT
COUNT(COLUMN1)
FROM  bankholidays
WHERE COLUMN1 BETWEEN @StartDate AND @EndDate)

Body:
SELECT CASE
WHEN @Region = 'EW' THEN columnName
WHEN @Region = 'SC' THEN columnName
WHEN @Region = 'NI' THEN columnName
END AS newColumnName FROM bankholidaysT

Try something like this


问:
error htmlTreeParse in R
I'm trying to get the body text from this webpage www.kinyo.es
but it returns this problem:

```<code>Error in which(value == defs) :
  argument "code" is missing, with no default
In addition: Warning messages:
1: XML content does not seem to be XML: 'Error displaying the error page: Application Instantiation Error: Could not connect to MySQL.'
2: XML content does not seem to be XML: ''
</code>```

My code is the following loop:

```<code>for(i in 1:n)
{

#get the URL
u <- webpage[i]

doc <- getURL(u)

#get the text from the body
html <- htmlTreeParse(doc, useInternal = TRUE)
txt <- xpathApply(html, "//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]", xmlValue)
txt<-toString(txt)
txt

#clean
txt<-(str_replace_all(txt, "[\r\n\t,]" , ""))
txt<-tolower(txt)
txt
search <- c("wi-fi","router","switch","adsl","wireless")
search
stri_count_fixed(txt, search)

conta[i]<-sum(stri_count_fixed(txt, search))
#txt
}
</code>```

答:
This is a bit of a stretch, as I read your other questions and I can only suppose this is what you are after:

library(rvest)
library(stringr)

count_keywords <- function(url, keywords){
    read_html(url) %>%
        html_nodes(xpath = '//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]') %>%
        html_text() %>%
        toString() %>%
        str_count(keywords) %>%
        sum
}

urls <- c('http://www.dlink.com/it/it', 'http://www.kinyo.es')
search <- c("Wi-Fi","Router","Switch","ADSL")

res <- sapply(urls, count_keywords, search)

res
#> http://www.dlink.com/it/it        http://www.kinyo.es
#>                         11                          0
```

Title: error htmlTreeParse in R

Body:
I'm trying to get the body text from this webpage www.kinyo.es
but it returns this problem:

Error in which(value == defs) :
  argument "code" is missing, with no default
In addition: Warning messages:
1: XML content does not seem to be XML: 'Error displaying the error page: Application Instantiation Error: Could not connect to MySQL.'
2: XML content does not seem to be XML: ''

My code is the following loop:

for(i in 1:n)
{

#get the URL
u <- webpage[i]

doc <- getURL(u)

#get the text from the body
html <- htmlTreeParse(doc, useInternal = TRUE)
txt <- xpathApply(html, "//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]", xmlValue)
txt<-toString(txt)
txt

#clean
txt<-(str_replace_all(txt, "[\r\n\t,]" , ""))
txt<-tolower(txt)
txt
search <- c("wi-fi","router","switch","adsl","wireless")
search
stri_count_fixed(txt, search)

conta[i]<-sum(stri_count_fixed(txt, search))
#txt
}


问:
Onclick hide one div and show 2nd div.... in IE9
Working with an ancient device called Internet Explorer 9 (very long boring story to why I am using this)
But trying to get it so when a button is clicked it hides both div "one" and the button but shows div "two"
I can get it to work with Fire Fox but no clue to how to get IE9 to work all I get is a button that does nothing.</p>

答:
You have to use the native onclick event in your html, and call a function in your javascript for switching the visibility on both your divs.

Refer code:

function switchVisible() {
  if (document.getElementById('div1')) {

    if (document.getElementById('div1').style.display == 'none') {
      document.getElementById('div1').style.display = 'block';
      document.getElementById('div2').style.display = 'none';
    } else {
      document.getElementById('div1').style.display = 'none';
      document.getElementById('div2').style.display = 'block';
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div2 {
  display: none;
}</code>```

Div 1

Div 2

<input id="Button1" type="button" value="Click" onclick="switchVisible();" />```

Body:
You have to use the native onclick event in your html, and call a function in your javascript for switching the visibility on both your divs.

Refer code:

function switchVisible() {
  if (document.getElementById('div1')) {

    if (document.getElementById('div1').style.display == 'none') {
      document.getElementById('div1').style.display = 'block';
      document.getElementById('div2').style.display = 'none';
    } else {
      document.getElementById('div1').style.display = 'none';
      document.getElementById('div2').style.display = 'block';
    }
  }
}

#div2 {
  display: none;
}

<div id="div1">Div 1</div>
<div id="div2">Div 2</div>

<input id="Button1" type="button" value="Click" onclick="switchVisible();" />


问:
Spring MVC default @RequestMapping to catch unmatched URL
I have this Controller

```<code>@Controller
@RequestMapping(value = "/v1.0/user")
public class UserController {

    @RequestMapping(value = "/findOne/{id}", method = RequestMethod.GET)
    public @ResponseBody String findOne(@PathVariable("id") Integer id) {
        log.info("findOne");
        return "found URL";
    }

}
</code>```

Which will match the URL: http://localhost:8080/v1.0/user/findOne/4

But if my path varibale is not correct: http://localhost:8080/v1.0/user/findOne/4A

The I get nothing.  Not even an error.  It's as if Spring swallowed the URL.

I added

```<code>@RequestMapping(value = "/.*", method = RequestMethod.GET)
public @ResponseBody String redirectEverythingOtherThanTest(){
    log.info("no url matched");
    return "badly formed URL for Users";
}
</code>```

Again I get nothing. What I'm trying to accomplish is for each Controller to have a unique message when the URL does not match.

答:
In the end in each of my Controller classes I added

```<code>@ExceptionHandler(Exception.class)
public @ResponseBody String handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return e.getMessage();

}
</code>```

And this will catch all exceptions and I can treat it as a catch all.

Body:
I have this Controller

@Controller
@RequestMapping(value = "/v1.0/user")
public class UserController {

    @RequestMapping(value = "/findOne/{id}", method = RequestMethod.GET)
    public @ResponseBody String findOne(@PathVariable("id") Integer id) {
        log.info("findOne");
        return "found URL";
    }

}

Which will match the URL: http://localhost:8080/v1.0/user/findOne/4

But if my path varibale is not correct: http://localhost:8080/v1.0/user/findOne/4A

The I get nothing.  Not even an error.  It's as if Spring swallowed the URL.

I added

@RequestMapping(value = "/.*", method = RequestMethod.GET)
public @ResponseBody String redirectEverythingOtherThanTest(){
    log.info("no url matched");
    return "badly formed URL for Users";
}

Again I get nothing. What I'm trying to accomplish is for each Controller to have a unique message when the URL does not match.

Body:
In the end in each of my Controller classes I added

@ExceptionHandler(Exception.class)
public @ResponseBody String handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return e.getMessage();

}

And this will catch all exceptions and I can treat it as a catch all.


问:
SVG get text element width
I'm working on some ECMAScript/JavaScript for an SVG file and need to get the width and height of a text element so I can resize a rectangle that surrounds it. In HTML I would be able to use the offsetWidth and offsetHeight attributes on the element but it appears that those properties are unavailable.

Here's a fragment that I need to work with. I need to change the width of the rectangle whenever I change the text but I don't know how to get the actual width (in pixels) of the text element.

```<code><rect x="100" y="100" width="100" height="100" />
<text>Some Text</text>
</code>```

Any ideas?

答:
```<code>document.getElementById('yourTextId').getComputedTextLength();
</code>```

worked for me in

Title: SVG get text element width

Body:
I'm working on some ECMAScript/JavaScript for an SVG file and need to get the width and height of a text element so I can resize a rectangle that surrounds it. In HTML I would be able to use the offsetWidth and offsetHeight attributes on the element but it appears that those properties are unavailable.

Here's a fragment that I need to work with. I need to change the width of the rectangle whenever I change the text but I don't know how to get the actual width (in pixels) of the text element.

<rect x="100" y="100" width="100" height="100" />
<text>Some Text</text>

Any ideas?

Body:
document.getElementById('yourTextId').getComputedTextLength();

worked for me in


问:
how to do post in nsurlconection?
http://[domain]/functionsdata.php?action=get_projectdetails
This is my url how to do post city and how to fetch data based on city key in nsurlconnection in objective c  ios? </p>

答:
```<code>NSString * requestUrl = @"http://[domain]/functionsdata.php?action=get_projectdetails";

NSMutableRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: requestUrl]];

[request setHTTPMethod:@"POST"];

NSDictionary *requestParams = [@"city":@"value"];

NSData *jsonRequestData = [NSJSONSerialization dataWithJSONObject:requestParams options:kNilOptions error:&error];

[request setHTTPBody:jsonRequestData];

NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:request delegate:self];

[myConnection start];
</code>```

Title: how to do post in nsurlconection?