问:
Okhttp Interceptor issue
I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server? </p>

```<code>        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }
</code>```

<p>I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise. </p>

答:
You can use by method addHeader send chain as param and add headers.

```<code> Request getRequest = chain.request();
        Request.Builder requestBuilder = getRequest.newBuilder()
            .addHeader("Header", "123");
        Request request = requestBuilder.build();
        return chain.proceed(request);
</code>```

You can also visit and look at the answers link1 and link2.

Here is the all-request Structure you can use.

```<code>OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }
        };
        OkHttpClient client = httpClient.build();

        Request request = new Request.Builder()
                .url("URL")
                .addHeader("Header", "123")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("OKHTTP3", e.getMessage());
                // You get this failure
                runOnUiThread(() -> {

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final String _body = response.body().string();
                    Log.d("OKHTTP3", _body);
                    runOnUiThread(() -> {

                    });
                } catch (InterruptedIOException e) {
                    runOnUiThread(() -> {
                        // Or this exception depending when timeout is reached

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

Title: Okhttp Interceptor issue

Body:
I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server?

        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }

I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise.

Body:
You can use by method addHeader send chain as param and add headers.

 Request getRequest = chain.request();
        Request.Builder requestBuilder = getRequest.newBuilder()
            .addHeader("Header", "123");
        Request request = requestBuilder.build();
        return chain.proceed(request);

You can also visit and look at the answers link1 and link2.

Here is the all-request Structure you can use.

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }
        };
        OkHttpClient client = httpClient.build();

        Request request = new Request.Builder()
                .url("URL")
                .addHeader("Header", "123")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("OKHTTP3", e.getMessage());
                // You get this failure
                runOnUiThread(() -> {

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final String _body = response.body().string();
                    Log.d("OKHTTP3", _body);
                    runOnUiThread(() -> {

                    });
                } catch (InterruptedIOException e) {
                    runOnUiThread(() -> {
                        // Or this exception depending when timeout is reached

                    });
                }
            }
        });


来源: stackexchange

问:
Can not connect to "xampp server localhost" with android studio
I have tried to connect to my localhost xampp with android studio using AsyncTask class. Here is AsyncTask but it gives error saying Failed to connect
to /10.0.2.2:800

I tried my real ip address cmd --> ipconfig IPV4 and some other tricks but
they did not succeed

belwow is my app structure

AsyncTask using class

```<code>package app.buil.land.food.doymaj.doymaj;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

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.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by ProgrammingKnowledge on 1/5/2016.
 */
public class backGroundActivities extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    backGroundActivities (Context ctx) {
        context = ctx;
    }
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://10.0.2.2:800/login.php";
        if(type.equals("login")) {
            try {
                String phone_number = params[1];
//                String password = params[2];
                URL url = new URL(login_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 post_data = URLEncoder.encode("phone_number","UTF-8")+"="+URLEncoder.encode(phone_number,"UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                    Log.e("Line_from_php_server",result);
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();

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

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}
</code>```

here is my MainActivity

```<code>package app.buil.land.food.doymaj.doymaj;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText phone_Number;
    EditText user_Name;
    EditText pass_Word;
    Button singButton;

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

     //   singButton = (Button)findViewById(R.id.sing_id);
     //   singButton.setOnClickListener(kyListener);
        phone_Number =(EditText)findViewById(R.id.mobile_id);
        user_Name =(EditText)findViewById(R.id.name_id);
        pass_Word =(EditText)findViewById(R.id.p_id);

    }

//    Push_Identity db = new Push_Identity(this,"CustomerDatabas.db",null,1);

    public boolean validate(EditText[] fields){
        for(int i = 0; i < fields.length; i++){
            EditText currentField = fields[i];

            if(currentField.getText().toString().length() <= 0){

                switch (i){

                    case 0:

                        Toast.makeText(getApplicationContext(),"شماره تلفن وارد نشده  ",Toast.LENGTH_LONG).show() ;
                        break;

                    case 1:

                        Toast.makeText(getApplicationContext(),"نام کاربری وارد نشده  ",Toast.LENGTH_LONG).show() ;
                        break;

                    case 2:

                        Toast.makeText(getApplicationContext(),"رمز وارد نشده  ",Toast.LENGTH_LONG).show() ;
                        break;

                }
                return false;
            }
        }
        return true;
    }

    //private View.OnClickListener kyListener = new View.OnClickListener() {
        public void send_number(View v) {
            // do something when the button is clicked
            // Yes we will handle click here but which button clicked??? We don't know

            boolean fieldsOK = validate(new EditText[] { phone_Number, user_Name, pass_Word });

                 if (fieldsOK ==true){

                          String Phon = phone_Number.getText().toString();
                          Toast.makeText(getApplicationContext(),Phon,Toast.LENGTH_LONG);
                          // the Tooast dose not display anything
                       //    it seems that the EditText is empty buy i enter the value in
                        // in it.
                          String type ="login";

                          backGroundActivities back = new backGroundActivities(this);
                          back.execute(type,Phon);
        //
                 }
        }
   // };

}
</code>```

XML

```<code>        <EditText
            android:id="@+id/mobile_id"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:background="@drawable/customized_edtitext"
            android:drawablePadding="15dp"
            android:paddingRight="10dp"
            android:paddingLeft="15dp"
            android:drawableRight="@drawable/ic_smartphone"
            android:elevation="2dp"
            android:textStyle="bold"
            android:hint="@string/register_phone_commnet"
            android:fontFamily="@font/iransansmedium"
            android:textSize="12sp"

            />

        <EditText
            android:id="@+id/name_id"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_below="@id/mobile_id"
            android:background="@drawable/customized_edtitext1"
            android:drawablePadding="15dp"
            android:paddingRight="10dp"
            android:paddingLeft="15dp"
            android:drawableRight="@mipmap/ic_user"
            android:elevation="2dp"
            android:textStyle="bold"
            android:hint="@string/register_user_commnet"
            android:fontFamily="@font/iransansmedium"
            android:textSize="12dp" />

        <EditText
            android:id="@+id/p_id"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_below="@+id/name_id"
            android:background="@drawable/customized_edtitext2"
            android:drawablePadding="15dp"
            android:paddingRight="10dp"
            android:paddingLeft="15dp"
            android:drawableRight="@mipmap/ic_unlocked"
            android:elevation="2dp"
            android:textStyle="bold"
            android:hint="@string/register_pass_commnet"
            android:fontFamily="@font/iransansmedium"
            android:textSize="12sp"
            android:paddingEnd="10dp" />
</code>```

here is the url of my php page
enter image description here

And some more information: I have Genymotion installed and also bluestack, and VirtaulBox. Do they confilct about port? I mean could these softwares cause conflicting ports Apache xampp and their ports?

答: My Xampp was working with Port: 80 as shown in below image. So writing below ip address as http://10.0.2.2:80/ worked for me.

ContentLicense: CC BY-SA 4.0

Body:
I have tried to connect to my localhost xampp with android studio using AsyncTask class. Here is AsyncTask but it gives error saying Failed to connect
to /10.0.2.2:800

I tried my real ip address cmd --> ipconfig IPV4 and some other tricks but
they did not succeed

belwow is my app structure

AsyncTask using class

package app.buil.land.food.doymaj.doymaj;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

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.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by ProgrammingKnowledge on 1/5/2016.
 */
public class backGroundActivities extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    backGroundActivities (Context ctx) {
        context = ctx;
    }
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://10.0.2.2:800/login.php";
        if(type.equals("login")) {
            try {
                String phone_number = params[1];
//                String password = params[2];
                URL url = new URL(login_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 post_data = URLEncoder.encode("phone_number","UTF-8")+"="+URLEncoder.encode(phone_number,"UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                    Log.e("Line_from_php_server",result);
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();

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

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

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

here is my MainActivity

package app.buil.land.food.doymaj.doymaj;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText phone_Number;
    EditText user_Name;
    EditText pass_Word;
    Button singButton;

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

     //   singButton = (Button)findViewById(R.id.sing_id);
     //   singButton.setOnClickListener(kyListener);
        phone_Number =(EditText)findViewById(R.id.mobile_id);
        user_Name =(EditText)findViewById(R.id.name_id);
        pass_Word =(EditText)findViewById(R.id.p_id);

    }

//    Push_Identity db = new Push_Identity(this,"CustomerDatabas.db",null,1);

    public boolean validate(EditText[] fields){
        for(int i = 0; i < fields.length; i++){
            EditText currentField = fields[i];

            if(currentField.getText().toString().length() <= 0){

                switch (i){

                    case 0:

                        Toast.makeText(getApplicationContext(),"شماره تلفن وارد نشده  ",Toast.LENGTH_LONG).show() ;
                        break;

                    case 1:

                        Toast.makeText(getApplicationContext(),"نام کاربری وارد نشده  ",Toast.LENGTH_LONG).show() ;
                        break;

                    case 2:

                        Toast.makeText(getApplicationContext(),"رمز وارد نشده  ",Toast.LENGTH_LONG).show() ;
                        break;

                }
                return false;
            }
        }
        return true;
    }

    //private View.OnClickListener kyListener = new View.OnClickListener() {
        public void send_number(View v) {
            // do something when the button is clicked
            // Yes we will handle click here but which button clicked??? We don't know

            boolean fieldsOK = validate(new EditText[] { phone_Number, user_Name, pass_Word });

                 if (fieldsOK ==true){

                          String Phon = phone_Number.getText().toString();
                          Toast.makeText(getApplicationContext(),Phon,Toast.LENGTH_LONG);
                          // the Tooast dose not display anything
                       //    it seems that the EditText is empty buy i enter the value in
                        // in it.
                          String type ="login";

                          backGroundActivities back = new backGroundActivities(this);
                          back.execute(type,Phon);
        //
                 }
        }
   // };

}

XML

        <EditText
            android:id="@+id/mobile_id"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:background="@drawable/customized_edtitext"
            android:drawablePadding="15dp"
            android:paddingRight="10dp"
            android:paddingLeft="15dp"
            android:drawableRight="@drawable/ic_smartphone"
            android:elevation="2dp"
            android:textStyle="bold"
            android:hint="@string/register_phone_commnet"
            android:fontFamily="@font/iransansmedium"
            android:textSize="12sp"

            />

        <EditText
            android:id="@+id/name_id"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_below="@id/mobile_id"
            android:background="@drawable/customized_edtitext1"
            android:drawablePadding="15dp"
            android:paddingRight="10dp"
            android:paddingLeft="15dp"
            android:drawableRight="@mipmap/ic_user"
            android:elevation="2dp"
            android:textStyle="bold"
            android:hint="@string/register_user_commnet"
            android:fontFamily="@font/iransansmedium"
            android:textSize="12dp" />

        <EditText
            android:id="@+id/p_id"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_below="@+id/name_id"
            android:background="@drawable/customized_edtitext2"
            android:drawablePadding="15dp"
            android:paddingRight="10dp"
            android:paddingLeft="15dp"
            android:drawableRight="@mipmap/ic_unlocked"
            android:elevation="2dp"
            android:textStyle="bold"
            android:hint="@string/register_pass_commnet"
            android:fontFamily="@font/iransansmedium"
            android:textSize="12sp"
            android:paddingEnd="10dp" />

here is the url of my php page
enter image description here

And some more information: I have Genymotion installed and also bluestack, and VirtaulBox. Do they confilct about port? I mean could these softwares cause conflicting ports Apache xampp and their ports?


问:
GAE Update Question
I have a strange question.
What I want to do is update my GAE version from 1.3.5 to 1.4.1/1.4.0.
After installing, I want to run dev_appserver.
But there is a error:

```<code>ERROR    2011-01-19 21:50:11,262 dev_appserver.py:3214] Exception encountered handling request
Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3184, in _HandleRequest
    response = RewriteResponse(outfile, self.rewriter_chain)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2882, in RewriteResponse
    response_rewriter(response)
TypeError: DownloadRewriter() takes exactly 2 arguments (1 given)
</code>```

Note: I didn't change my code and it worked very well on GAE 1.3.5
Thanks for any answers.

答:
The problem has been solved.
We reinstalled gae again at "different folder"
"Different folder" is a key.
If you uninstall gae at the default (same) folder (c:\program files\google\google_appengine), the problems still exist.

So we installed it at c:\program files\goole\google_appending_x (x means any word).
Then it can work.

ContentLicense: CC BY-SA 2.5

Title: GAE Update Question

Body:
I have a strange question.
What I want to do is update my GAE version from 1.3.5 to 1.4.1/1.4.0.
After installing, I want to run dev_appserver.
But there is a error:

ERROR    2011-01-19 21:50:11,262 dev_appserver.py:3214] Exception encountered handling request
Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3184, in _HandleRequest
    response = RewriteResponse(outfile, self.rewriter_chain)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2882, in RewriteResponse
    response_rewriter(response)
TypeError: DownloadRewriter() takes exactly 2 arguments (1 given)

Note: I didn't change my code and it worked very well on GAE 1.3.5
Thanks for any answers.

ContentLicense: CC BY-SA 3.0


问:
Remove Picasso showing blue / green / red triangle at top of corner
I want to remove blue / green / red triangle showing at the top of corner using Picasso

Gradle:

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
</code>```

Code:

```<code>Picasso.get()
.load(img.getImage()).
placeholder(android.R.drawable.ic_menu_gallery)
.into(holder.imageView);
</code>```

Tried:

```<code>.setIndicatorsEnabled(false)
</code>```

Getting:

```<code>Cannot resolve method 'setIndicatorsEnabled(boolean)'
</code>```

答:
To use setIndicatorsEnabled, you need to assume Picasso as a singleton instance.

```<code>Picasso mPicasso = Picasso.get();
mPicasso.setIndicatorsEnabled(false);
mPicasso.load(img.getImage()).
placeholder(android.R.drawable.ic_menu_gallery)
.into(holder.imageView);
</code>```

And to remove blue/green/red triangle showing at the top of the corner  you need to set

setIndicatorsEnabled to false

```<code>.setIndicatorsEnabled(false)
</code>```

Hope this will help you.

Body:
I want to remove blue / green / red triangle showing at the top of corner using Picasso

Gradle:

implementation 'com.squareup.picasso:picasso:2.71828'

Code:

Picasso.get()
.load(img.getImage()).
placeholder(android.R.drawable.ic_menu_gallery)
.into(holder.imageView);

Tried:

.setIndicatorsEnabled(false)

Getting:

Cannot resolve method 'setIndicatorsEnabled(boolean)'

Body:
To use setIndicatorsEnabled, you need to assume Picasso as a singleton instance.

Picasso mPicasso = Picasso.get();
mPicasso.setIndicatorsEnabled(false);
mPicasso.load(img.getImage()).
placeholder(android.R.drawable.ic_menu_gallery)
.into(holder.imageView);

And to remove blue/green/red triangle showing at the top of the corner  you need to set

setIndicatorsEnabled to false

.setIndicatorsEnabled(false)

Hope this will help you.


问:
Error is Trying to get property 'id' of non-object, but seems object has
I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -

```<code>        try{
            ///try to connect with database
            $conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $ex){
            echo "error";
        }
        $mysqlcode="SELECT * FROM users";
        $ret=$conn->query($mysqlcode);
        foreach($ret as $ret1)
        print $ret1->id;
</code>```

in the browser,
showing this error:

Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44

In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.

答:
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code

```<code>$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);

if ($ret->num_rows > 0) {
  // output data of each row
  while($row = $ret->fetch_assoc()) {
    echo "id: " . $ret["id"] . "<br>";
  }
} else {
  echo "0 results";
}
$conn->close();
</code>```

that'll work fine.

Body:
I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -

        try{
            ///try to connect with database
            $conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $ex){
            echo "error";
        }
        $mysqlcode="SELECT * FROM users";
        $ret=$conn->query($mysqlcode);
        foreach($ret as $ret1)
        print $ret1->id;

in the browser,
showing this error:

Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44

In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.

Body:
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code

$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);

if ($ret->num_rows > 0) {
  // output data of each row
  while($row = $ret->fetch_assoc()) {
    echo "id: " . $ret["id"] . "<br>";
  }
} else {
  echo "0 results";
}
$conn->close();

that'll work fine.


问:
No strict inequalities in cvxpy problem but still get the error "Strict inequalities are not allowed"
I was using the CVXPY library in Python, trying to solve a particular optimization problem.

```<code>import cvxpy as cp
import numpy as np
from scipy.stats import norm

(...)

a = cp.Variable([10, 1])

obj = cp.Maximize(sum(norm.logcdf(A @ a, scale=sigma)))
constraints = [a >= np.zeros([10, 1]), a <= np.ones([10, 1])]

prob = cp.Problem(objective=obj, constraints=constraints)

prob.solve()
</code>```

Here A is a particular numpy Matrix, and sigma is a particular scalar. When I try to solve the question, the package gives me the below error.

```<code>Traceback (most recent call last):
  File "~\anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-23-c554382c1c69>", line 19, in <module>
    obj = cp.Maximize(sum(norm.logcdf(A @ a, scale=sigma)))
  File "~\anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py", line 1848, in logcdf
    cond1 = self._open_support_mask(x, *args) & (scale > 0)
  File "~\anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py", line 901, in _open_support_mask
    return (a < x) & (x < b)
  File "~\anaconda3/lib/python3.7/site-packages/cvxpy/expressions/expression.py", line 597, in __gt__
    raise NotImplementedError("Strict inequalities are not allowed.")
NotImplementedError: Strict inequalities are not allowed.
</code>```

But the problem itself contains no strict inequality... Seems like the SCIPY package has conflict with CVXPY, but have no idea how to resolve...

答:
There is a norm in cvxpy. So please change as below code:

```<code>from scipy.stats import stats
obj = cp.Maximize(sum(stats.logcdf(A @ a, scale=sigma)))
</code>```

functions

Body:
I was using the CVXPY library in Python, trying to solve a particular optimization problem.

import cvxpy as cp
import numpy as np
from scipy.stats import norm

(...)

a = cp.Variable([10, 1])

obj = cp.Maximize(sum(norm.logcdf(A @ a, scale=sigma)))
constraints = [a >= np.zeros([10, 1]), a <= np.ones([10, 1])]

prob = cp.Problem(objective=obj, constraints=constraints)

prob.solve()

Here A is a particular numpy Matrix, and sigma is a particular scalar. When I try to solve the question, the package gives me the below error.

Traceback (most recent call last):
  File "~\anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-23-c554382c1c69>", line 19, in <module>
    obj = cp.Maximize(sum(norm.logcdf(A @ a, scale=sigma)))
  File "~\anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py", line 1848, in logcdf
    cond1 = self._open_support_mask(x, *args) & (scale > 0)
  File "~\anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py", line 901, in _open_support_mask
    return (a < x) & (x < b)
  File "~\anaconda3/lib/python3.7/site-packages/cvxpy/expressions/expression.py", line 597, in __gt__
    raise NotImplementedError("Strict inequalities are not allowed.")
NotImplementedError: Strict inequalities are not allowed.

But the problem itself contains no strict inequality... Seems like the SCIPY package has conflict with CVXPY, but have no idea how to resolve...

Body:
There is a norm in cvxpy. So please change as below code:

from scipy.stats import stats
obj = cp.Maximize(sum(stats.logcdf(A @ a, scale=sigma)))

functions


问:
Using "KexAlgorithms diffie-hellman-group1-sha1" did not resolve "no matching key exchange method found" error
There's a lot of questions about the following error, but they all have same solution which did not have any effect:

```<code>$ git push
Unable to negotiate with 192.168.XXX.XXX: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

There is an article on openssh.com that didn't help. Particularly this was suggested:

... in the ~/.ssh/config file:

```<code>Host somehost.example.org
KexAlgorithms +diffie-hellman-group1-sha1
</code>```

I did exactly that. I assume that ~ resolves to %userprofile% on windows. My file is in C:\Users\MY_USERNAME\.ssh\config:

```<code>## use kex algorithm ##
Host 192.168.XXX.XXX
KexAlgorithms diffie-hellman-group1-sha1
</code>```

The result is that nothing changed. There is also suggestion to use ssh -o but I'm yet to find an answer that bothers to describe how exactly yo do that. I tried this:

```<code>$ ssh -oKexAlgorithms=+diffie-hellman-group1-sha1
usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
</code>```

I need to connect to that GIT repository. I am on windows. The repository uses Gerrit. I also use SourceTree and it has no problems pushing into the repository. So the repository works, but git or openSSH in my bash is broken.

What did I do wrong that this solution didn't work for me?

答:
I also faced the same issue.Please install the older version of "Git for Windows".
https://github.com/git-for-windows/git/releases/tag/v2.17.1.windows.1
This version will solve your issue.</p>

Body:
There's a lot of questions about the following error, but they all have same solution which did not have any effect:

$ git push
Unable to negotiate with 192.168.XXX.XXX: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

There is an article on openssh.com that didn't help. Particularly this was suggested:

... in the ~/.ssh/config file:

Host somehost.example.org
KexAlgorithms +diffie-hellman-group1-sha1

I did exactly that. I assume that ~ resolves to %userprofile% on windows. My file is in C:\Users\MY_USERNAME\.ssh\config:

## use kex algorithm ##
Host 192.168.XXX.XXX
KexAlgorithms diffie-hellman-group1-sha1

The result is that nothing changed. There is also suggestion to use ssh -o but I'm yet to find an answer that bothers to describe how exactly yo do that. I tried this:

$ ssh -oKexAlgorithms=+diffie-hellman-group1-sha1
usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]

I need to connect to that GIT repository. I am on windows. The repository uses Gerrit. I also use SourceTree and it has no problems pushing into the repository. So the repository works, but git or openSSH in my bash is broken.

What did I do wrong that this solution didn't work for me?


问:
Unable to add Azure AD admin user to Enterprise Admins group
I'm trying to find a way to add a Azure admin user to the Enterprise Admins group of a Azure AD domain to allow me to manage features of AD users which I can't manage via Azure AD.

Is this possible?

答:
as per the documentation

https://learn.microsoft.com/en-us/azure/active-directory-domain-services/faqs#do-i-have-domain-administrator-privileges-for-the-managed-domain-provided-by-azure-ad-domain-services

Do I have domain administrator privileges for the managed domain provided by Azure AD Domain Services?

No. You aren't granted administrative privileges on the managed
  domain. Domain Administrator and Enterprise Administrator privileges
  aren't available for you to use within the domain. Members of the
  domain administrator or enterprise administrator groups in your
  on-premises Active Directory are also not granted domain / enterprise
  administrator privileges on the managed domain.

So as per that, I would say this is probably not possible.


问:
Stop Android OS auto-update
We have a variety of devices for testing purposes, and now that Froyo is being pushed (to the Nexus One so far at least), we have to constantly dismiss upgrade requests.  There is no apparent "stop asking me" button.

So, is there any way I can disable OTA OS updates?  We want a number of these phones to stay on old OS versions.

答:
For XOOM running android 3 honeycomb. You have to remove Upgrader.apk (not SystemUpdater).

```<code>adb pull /system/app/Upgrader.apk C:/Path/to/your/desktop //Backup the file (just in case)
adb remount                                       //Remount the system partition to read-write
adb shell rm /system/app/Upgrader.apk              //Remove the apk
</code>```

Title: Stop Android OS auto-update

Body:
For XOOM running android 3 honeycomb. You have to remove Upgrader.apk (not SystemUpdater).

adb pull /system/app/Upgrader.apk C:/Path/to/your/desktop //Backup the file (just in case)
adb remount                                       //Remount the system partition to read-write
adb shell rm /system/app/Upgrader.apk              //Remove the apk


问:
Understanding splice or rather not understanding it?
```<code>let fish = [ "piranha", "barracuda", "koi", "eel" ];

// Remove two items, starting at index position 1
fish.splice(1, 2);

fish;
</code>```

Since the first digit 1 represents position "barracuda" within the array and 2 represents the items to be removed, Why doesn't this remove "koi" and "eel" (the 2 positions that follow) but instead removes "eel" and "piranha" (the 2nd and 3rd in rotation)?

答:
Why doesn't this remove "koi" and "eel" (the 2 positions that follow)

Why would it? Look at the array indexes and the values at these positions:

```<code>fish[0]    "piranha"
fish[1]    "barracuda"
fish[2]    "koi"
fish[3]    "eel"
</code>```

fish.splice(1, 2) says (as you yourself wrote) that starting with position 1 it should remove 2 elements.

So, at position 1 we have barracuda, which gets removed. But you said to remove 2 elements, not 1, so it removes another one: At position 1 we now have koi, which gets removed as well.

End result is that barracude and koi got removed, and we are left with ["piranha", "eel"] as expected.

You could imagine the way splice works like this:

// Define `remove` and `insert` primitives.
// Yes I know I'm now explaining `splice` with `splice`... but just think about
// those as basic ways to remove (and return) or insert one element at a given
// position.
const remove = (array, index) => array.splice(index, 1)
const insert = (array, index, el) => array.splice(index, 0, el)

// Our own implementation of `splice`, using only the remove/insert primitives.
// I'm adding the array itself as an additional parameter at the front.
function ourSplice (array, position, removeCount = null, ...newElements) {
  // Note: This does not simulate the behavior of splice(), splice(undefined),
  // splice(undefined, undefined) and similar things, which don't behave all the
  // same. It assumes at least a valid position.

  // Negative position means N elements from the *end* of the array.
  if (position < 0) position += array.length

  // Unspecified remove count means to remove all elements starting with the given
  // position (note that in the real splice function, this works only if the
  // argument is omitted, not when it is undefined or null)
  if (removeCount === null) removeCount = array.length - position

  // Remove the given number of elements starting at the given position
  const removed = []
  for (let i = 0; i < removeCount; i++) {
    removed.push(remove(array, position))
  }

  // Add any new elements given at the given position
  for (let i = 0; i < newElements.length; i++) {
    insert(array, position + i, newElements[i])
  }

  // Return the removed elements
  return removed
}
```

Body:
let fish = [ "piranha", "barracuda", "koi", "eel" ];

// Remove two items, starting at index position 1
fish.splice(1, 2);

fish;

Since the first digit 1 represents position "barracuda" within the array and 2 represents the items to be removed, Why doesn't this remove "koi" and "eel" (the 2 positions that follow) but instead removes "eel" and "piranha" (the 2nd and 3rd in rotation)?

Body:
Why doesn't this remove "koi" and "eel" (the 2 positions that follow)

Why would it? Look at the array indexes and the values at these positions:

fish[0]    "piranha"
fish[1]    "barracuda"
fish[2]    "koi"
fish[3]    "eel"

fish.splice(1, 2) says (as you yourself wrote) that starting with position 1 it should remove 2 elements.

So, at position 1 we have barracuda, which gets removed. But you said to remove 2 elements, not 1, so it removes another one: At position 1 we now have koi, which gets removed as well.

End result is that barracude and koi got removed, and we are left with ["piranha", "eel"] as expected.

You could imagine the way splice works like this:

// Define `remove` and `insert` primitives.
// Yes I know I'm now explaining `splice` with `splice`... but just think about
// those as basic ways to remove (and return) or insert one element at a given
// position.
const remove = (array, index) => array.splice(index, 1)
const insert = (array, index, el) => array.splice(index, 0, el)

// Our own implementation of `splice`, using only the remove/insert primitives.
// I'm adding the array itself as an additional parameter at the front.
function ourSplice (array, position, removeCount = null, ...newElements) {
  // Note: This does not simulate the behavior of splice(), splice(undefined),
  // splice(undefined, undefined) and similar things, which don't behave all the
  // same. It assumes at least a valid position.

  // Negative position means N elements from the *end* of the array.
  if (position < 0) position += array.length

  // Unspecified remove count means to remove all elements starting with the given
  // position (note that in the real splice function, this works only if the
  // argument is omitted, not when it is undefined or null)
  if (removeCount === null) removeCount = array.length - position

  // Remove the given number of elements starting at the given position
  const removed = []
  for (let i = 0; i < removeCount; i++) {
    removed.push(remove(array, position))
  }

  // Add any new elements given at the given position
  for (let i = 0; i < newElements.length; i++) {
    insert(array, position + i, newElements[i])
  }

  // Return the removed elements
  return removed
}


问:
Add LambdaFunctionAssociation to existing CloudFront distribution with CloudFormation
I want to add LambdaFunctionAssociation to my existing CloudFront which is created manually
lambdafunctionassociation

Thanks in advance.

答:
key point:

"LambdaFunctionARN" should be the Arn of the Lambda version, not the Lambda function

For example:

```<code>"LambdaFunctionAssociations": [
    {
         "EventType": "origin-request",
         "IncludeBody": true,
         "LambdaFunctionARN": {
             "Ref": "LambdaVersion"
         }
     }
]
</code>```

pointing to a Version resource :

```<code> "LambdaVersion": {
        "Type": "AWS::Lambda::Version",
        "Properties": {
           "Description": "v1",
          "FunctionName": {
             "Ref": "MyLambdaFunction"
             }
           }
         }
</code>```

Body:
key point:

"LambdaFunctionARN" should be the Arn of the Lambda version, not the Lambda function

For example:

"LambdaFunctionAssociations": [
    {
         "EventType": "origin-request",
         "IncludeBody": true,
         "LambdaFunctionARN": {
             "Ref": "LambdaVersion"
         }
     }
]

pointing to a Version resource :

 "LambdaVersion": {
        "Type": "AWS::Lambda::Version",
        "Properties": {
           "Description": "v1",
          "FunctionName": {
             "Ref": "MyLambdaFunction"
             }
           }
         }


问:
Click event is not working in HTML Jquery
I am developing a responsive website using html and css. I had to use Jquery to click my toggle menu. The click event is not working. The following is my code. </p>

```<code>JQuery :

$(document).ready(function(){

    $toggleCollapse = $('.toggle-collapse');

$toggleCollapse.click(function(){
    $toggleClass('collapse');

})
});

CSS :

.collapse {
    height: 30rem;
}
</code>```

答:
You need to use $(this).toggleClass('collapse'); to toggle given class.

Here is demo :

$(document).ready(function() {

  $toggleCollapse = $('.toggle-collapse');

  $toggleCollapse.click(function() {
    //use this
    $(this).toggleClass('collapse');

  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapse {
  height: 30rem;
}</code>```

<button class="toggle-collapse">SOMETHING </button>```

Body:
I am developing a responsive website using html and css. I had to use Jquery to click my toggle menu. The click event is not working. The following is my code.

JQuery :

$(document).ready(function(){

    $toggleCollapse = $('.toggle-collapse');

$toggleCollapse.click(function(){
    $toggleClass('collapse');

})
});

CSS :

.collapse {
    height: 30rem;
}

Body:
You need to use $(this).toggleClass('collapse'); to toggle given class.

Here is demo :

$(document).ready(function() {

  $toggleCollapse = $('.toggle-collapse');

  $toggleCollapse.click(function() {
    //use this
    $(this).toggleClass('collapse');

  })
});

.collapse {
  height: 30rem;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="toggle-collapse">SOMETHING </button>


问:
PHP script no longer receiving data from context stream
We have a "legacy" script that stopped working a little while back. Pretty sure it's because the endpoint it's connecting to changed from http to https, and the old http address now returns a 301.

I've never done anything other than tiny changes to PHP scripts, so am a little out of my depth here.

Note that our PHP version is old - 5.3.0. This may well be part of  the problem.

The script as-is (relevant bit anyway):

```<code>$uri = "http://www.imf.org/external/np/fin/data/rms_mth.aspx"
     ."?SelectDate=$date&reportType=CVSDR&tsvflag=Y";
$opts = array('http' => array(
                 'proxy' => 'tcp://internal.proxy.address:port',
                 'method' => 'GET',
                 'request_fulluri' => true)
              );
$ctx = stream_context_create($opts);
$lines = file($uri, false, $ctx);
foreach ($lines as $line)
...
</code>```

This returns nothing any more. The link btw is the IMF link for exchange rates, so that is open to all - if you open it you'll get a download with a rate table in it. The rest of the script basically parses this for the data we want.

Now, pretty sure our proxy is OK. Running some tests with curl gives the following results:

```<code>curl --proxy tcp://internal.proxy.address:port -v https://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y
</code>```

(specify https) works just fine.

```<code>curl --proxy tcp://internal.proxy.address:port -v http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y
</code>```

(specify http) does not work, and shows a 301 error

```<code>curl --proxy tcp://internal.proxy.address:port -v -L http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y
</code>```

(specify http with follow redirects) then works OK.

I've tried a few things after some googling. It seems I need opts for 'ssl' as well when using https. So I've made the following changes

```<code>$uri = "https://www.imf.org/external/np/fin/data/rms_mth.aspx"
     ."?SelectDate=$date&reportType=CVSDR&tsvflag=Y";
$opts = array('http' => array(
                 'proxy' => 'tcp://internal.proxy.address:port',
                 'method' => 'GET',
                 'request_fulluri' => true),
              'ssl' => array(
                 'verify_peer' => false,
                 'verify_peer_name' => false,
                 'SNI_enabled' => false)
              );
</code>```

Sadly, the SNI_enabled flag was introduced after 5.3.0, so I don't think this helps. There's also a follow_location context option for http, but that was introduced in 5.3.4, so also no use.

(BTW, I have little to no control over the version of PHP we have, so while I appreciate higher versions may offer better solutions, that's not a lot of use to me I'm afraid).

Basically, I am now stuck. No combination of these parameters or settings returns any data at all. I can see it works via curl and the proxy, so it's not a general connectivity issue.

Any and all suggestions gratefully received!

Update: After adding the lines to enable error reporting, the error code is for the stream connecting:

```<code>Warning: file(https://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y): failed to open stream: Cannot connect to HTTPS server through proxy in /usr/bass/apps/htdocs/BASS/mods/module.XSM.php on line 79
</code>```

(line 79 is the $lines = ... line)

So it doesn't connect in the php script, but running the same connection via the proxy in curl works fine. What's the difference in php that causes this?

答:
You can use php curl functions to get the response from your given url. And then you can use explode() function to break the response line by line.

```<code>$uri = "https://www.imf.org/external/np/fin/data/rms_mth.aspx"
     ."?SelectDate=$date&reportType=CVSDR&tsvflag=Y";

$opts = array(
    CURLOPT_URL            => $uri,
    CURLOPT_PROXY          => 'tcp://internal.proxy.address:port',
    CURLOPT_HEADER         => false,
    CURLOPT_RETURNTRANSFER => true
);

$ch = curl_init();
curl_setopt_array($ch, $opts);
$lines = curl_exec($ch);
curl_close($ch);

$lines = explode("\n", $lines);    // breaking the whole response string line by line

foreach ($lines as $line)
...
</code>```

Body:
We have a "legacy" script that stopped working a little while back. Pretty sure it's because the endpoint it's connecting to changed from http to https, and the old http address now returns a 301.

I've never done anything other than tiny changes to PHP scripts, so am a little out of my depth here.

Note that our PHP version is old - 5.3.0. This may well be part of  the problem.

The script as-is (relevant bit anyway):

$uri = "http://www.imf.org/external/np/fin/data/rms_mth.aspx"
     ."?SelectDate=$date&reportType=CVSDR&tsvflag=Y";
$opts = array('http' => array(
                 'proxy' => 'tcp://internal.proxy.address:port',
                 'method' => 'GET',
                 'request_fulluri' => true)
              );
$ctx = stream_context_create($opts);
$lines = file($uri, false, $ctx);
foreach ($lines as $line)
...

This returns nothing any more. The link btw is the IMF link for exchange rates, so that is open to all - if you open it you'll get a download with a rate table in it. The rest of the script basically parses this for the data we want.

Now, pretty sure our proxy is OK. Running some tests with curl gives the following results:

curl --proxy tcp://internal.proxy.address:port -v https://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y

(specify https) works just fine.

curl --proxy tcp://internal.proxy.address:port -v http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y

(specify http) does not work, and shows a 301 error

curl --proxy tcp://internal.proxy.address:port -v -L http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y

(specify http with follow redirects) then works OK.

I've tried a few things after some googling. It seems I need opts for 'ssl' as well when using https. So I've made the following changes

$uri = "https://www.imf.org/external/np/fin/data/rms_mth.aspx"
     ."?SelectDate=$date&reportType=CVSDR&tsvflag=Y";
$opts = array('http' => array(
                 'proxy' => 'tcp://internal.proxy.address:port',
                 'method' => 'GET',
                 'request_fulluri' => true),
              'ssl' => array(
                 'verify_peer' => false,
                 'verify_peer_name' => false,
                 'SNI_enabled' => false)
              );

Sadly, the SNI_enabled flag was introduced after 5.3.0, so I don't think this helps. There's also a follow_location context option for http, but that was introduced in 5.3.4, so also no use.

(BTW, I have little to no control over the version of PHP we have, so while I appreciate higher versions may offer better solutions, that's not a lot of use to me I'm afraid).

Basically, I am now stuck. No combination of these parameters or settings returns any data at all. I can see it works via curl and the proxy, so it's not a general connectivity issue.

Any and all suggestions gratefully received!

Update: After adding the lines to enable error reporting, the error code is for the stream connecting:

Warning: file(https://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=05/28/2020&reportType=CVSDR&tsvflag=Y): failed to open stream: Cannot connect to HTTPS server through proxy in /usr/bass/apps/htdocs/BASS/mods/module.XSM.php on line 79

(line 79 is the $lines = ... line)

So it doesn't connect in the php script, but running the same connection via the proxy in curl works fine. What's the difference in php that causes this?

Body:
You can use php curl functions to get the response from your given url. And then you can use explode() function to break the response line by line.

$uri = "https://www.imf.org/external/np/fin/data/rms_mth.aspx"
     ."?SelectDate=$date&reportType=CVSDR&tsvflag=Y";

$opts = array(
    CURLOPT_URL            => $uri,
    CURLOPT_PROXY          => 'tcp://internal.proxy.address:port',
    CURLOPT_HEADER         => false,
    CURLOPT_RETURNTRANSFER => true
);

$ch = curl_init();
curl_setopt_array($ch, $opts);
$lines = curl_exec($ch);
curl_close($ch);

$lines = explode("\n", $lines);    // breaking the whole response string line by line

foreach ($lines as $line)
...


问:
A remote access exception in DolphinDB,Can't find the object with name loadTable('dfs://zctestDB','trainInfoTable')
I want to remotely query the database in DolphinDB.The database is created on the server 38.124.2.173 with the following script in the server ,

```<code>tableSchema = table(100:0,`trainID`ts`tag01`tag02,`tag03,[INT,TIMESTAMP,FLOAT,FLOAT,FLOAT )

db1 = database("",VALUE,(today()-92)..(today()+60))
db2 = database("",RANGE,0..80*10+1)
db = database("dfs://zctestDB",COMPO,[db1,db2])
dfsTable = db.createPartitionedTable(tableSchema,"trainInfoTable",`ts`trainID)
</code>```

My query code as below,

```<code>def testParallelQuery( connVector,trainIDs,startTime, endTime ){
cols=`trainID`ts`tag01
whereConditions=[<trainID in trainIDs>,expr(sqlCol(`ts),between,startTime:endTime)]
script=sql(sqlCol(cols),"loadTable('dfs://zctestDB','trainInfoTable')",whereConditions)
return ploop(remoteRun{,script}, connVector)
}
host="38.124.2.173"
port=30599
connVector = loop(xdb, take(host, 10), port, "admin", "123456")
testParallelQuery( connVector,1..5,2019.06.14T00:00:00.000, 2019.06.14T01:00:00.000 )
</code>```

The following exception occurred after I ran it，

```<code>Error was raised when execution : Can't find the object with name loadTable('dfs://zctestDB','trainInfoTable')
</code>```

How can I solve this problem?

答:
Function sql helps one construct a sql statement dynamically. The parameter from accepts three types of data: (1) a table object, (2) an expression representing a table or a table join, (3) a variable associated with a table object.

In your particular case, please pass an expression to from as follows.

```<code>def runSQL(trainIDs, startTime, endTime){
    cols = `trainID`ts`tag01
    whereConditions = [<trainID in trainIDs>, expr(sqlCol(`ts), between, startTime:endTime)]
    return sql(sqlCol(cols), loadTable('dfs://zctestDB','trainInfoTable'), whereConditions).eval()
}

def testParallelQuery( connVector,trainIDs,startTime, endTime ){
    return ploop(remoteRun{,runSQL{trainIDs, startTime, endTime}}, connVector)
}

host="38.124.2.173"
port=30599
connVector = loop(xdb, take(host, 10), port, "admin", "123456")
testParallelQuery( connVector,1..5,2019.06.14T00:00:00.000, 2019.06.14T01:00:00.000 )
</code>```

Body:
I want to remotely query the database in DolphinDB.The database is created on the server 38.124.2.173 with the following script in the server ,

tableSchema = table(100:0,`trainID`ts`tag01`tag02,`tag03,[INT,TIMESTAMP,FLOAT,FLOAT,FLOAT )

db1 = database("",VALUE,(today()-92)..(today()+60))
db2 = database("",RANGE,0..80*10+1)
db = database("dfs://zctestDB",COMPO,[db1,db2])
dfsTable = db.createPartitionedTable(tableSchema,"trainInfoTable",`ts`trainID)

My query code as below,

def testParallelQuery( connVector,trainIDs,startTime, endTime ){
cols=`trainID`ts`tag01
whereConditions=[<trainID in trainIDs>,expr(sqlCol(`ts),between,startTime:endTime)]
script=sql(sqlCol(cols),"loadTable('dfs://zctestDB','trainInfoTable')",whereConditions)
return ploop(remoteRun{,script}, connVector)
}
host="38.124.2.173"
port=30599
connVector = loop(xdb, take(host, 10), port, "admin", "123456")
testParallelQuery( connVector,1..5,2019.06.14T00:00:00.000, 2019.06.14T01:00:00.000 )

The following exception occurred after I ran it，

Error was raised when execution : Can't find the object with name loadTable('dfs://zctestDB','trainInfoTable')

How can I solve this problem?

Body:
Function sql helps one construct a sql statement dynamically. The parameter from accepts three types of data: (1) a table object, (2) an expression representing a table or a table join, (3) a variable associated with a table object.

In your particular case, please pass an expression to from as follows.

def runSQL(trainIDs, startTime, endTime){
    cols = `trainID`ts`tag01
    whereConditions = [<trainID in trainIDs>, expr(sqlCol(`ts), between, startTime:endTime)]
    return sql(sqlCol(cols), loadTable('dfs://zctestDB','trainInfoTable'), whereConditions).eval()
}

def testParallelQuery( connVector,trainIDs,startTime, endTime ){
    return ploop(remoteRun{,runSQL{trainIDs, startTime, endTime}}, connVector)
}

host="38.124.2.173"
port=30599
connVector = loop(xdb, take(host, 10), port, "admin", "123456")
testParallelQuery( connVector,1..5,2019.06.14T00:00:00.000, 2019.06.14T01:00:00.000 )


问:
How to assign content their own height using grid?
https://codepen.io/daniel-brown/pen/QWjXpXw

I need this li, to have their own height and not someone else’s

Expected outcome

div {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

  <li>industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li>
  <li>Lorem ever since the 1500s, when an unknown </li>
  <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li>
  <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </li>
  <li> unknown </li>
  <li>Lorem Ipsum is simply dummy text of thver since the 1500s, when an unknown </li>
  <li>L printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li>
  <li>Lorem Ipsum is simply dummy text of the printing and typesettinry's standard dummy text ever since the 1500s, when an unknown </li>
  <li>Lorem Ipsum is simply dummy text of Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li>
  <li> when an unknown </li>
  <li>Lorem </li>

  </ul>

</div></code>```

答:
To do that use the css inline property to add height to the li element individually

```<code><li style="height:10px;"> text </li>
</code>```

But i would rather suggest using the bootstrap grid system, and then assign the height parameter using inline styling :

```<code><div class="container">
<div class="row">
<div class="col-sm">
  <ul>
  <li style="height:10px;"> text </li>
  <li> text </li>
  </ul>
</div>
<div class="col-sm">
  <ul>
  <li> text </li>
  <li> text </li>
  </ul>
</div>
<div class="col-sm">
  <ul>
  <li> text </li>
  <li> text </li>
  </ul>
</div>
</code>```

Body:
https://codepen.io/daniel-brown/pen/QWjXpXw

I need this li, to have their own height and not someone else’s

Expected outcome

div {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown

Lorem ever since the 1500s, when an unknown

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

 unknown

Lorem Ipsum is simply dummy text of thver since the 1500s, when an unknown

L printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown

Lorem Ipsum is simply dummy text of the printing and typesettinry's standard dummy text ever since the 1500s, when an unknown

Lorem Ipsum is simply dummy text of Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown

 when an unknown

Lorem

Body:
To do that use the css inline property to add height to the li element individually

<li style="height:10px;"> text </li>

But i would rather suggest using the bootstrap grid system, and then assign the height parameter using inline styling :

<div class="container">
<div class="row">
<div class="col-sm">
  <ul>
  <li style="height:10px;"> text </li>
  <li> text </li>
  </ul>
</div>
<div class="col-sm">
  <ul>
  <li> text </li>
  <li> text </li>
  </ul>
</div>
<div class="col-sm">
  <ul>
  <li> text </li>
  <li> text </li>
  </ul>
</div>


问:
Firebase authentication with multple providers
I'm trying to create a user authentication screen, so I decided to use Firebase.

However, I am facing a problem. Nowadays I have enabled 2 providers, which are:

```<code>1- E-mail/Password
2- Google
</code>```

Enabled providers

I can create users perfectly.

When I create a user with E-mail/password option and use the Gmail address guilherme.nunes@fover.com.br, Firebase creates the user normally.

After using email, I am trying to use the second option of Google provider, using the same email. Now the old user is replaced with the new provider in Firebase.

account created

After this, if I try to login with the first option (E-mail/Password) again, it says that the user does not exist.

I tried disabling the option to have 1 user per account, but then, Firebase creates 2 distinct users.

What I would like, is to link 1 account, with several providers.

Can someone help me, please?

答:
When you enable the option to allow only a single account per email address, Firebase has certain providers that are preferred for certain email domains. Most notably: the Google provider is the preferred provider for @gmail.com addresses.

So in your initial process, you:

Register a user something@gmail.com with a email+password account.

Register a user something@gmail.com with a google account.

In this case, the second registration replaces/overrides the initial account.

What you want to do is link the two accounts/providers as described in the documentation on account linking. With this approach you don't fully register an account in step 2, but instead link the credentials for that second account to the email+password account that was already created for the user.

The documentation has a step-by-step explanation on how to do this. If you're having trouble making this work, post a new question with the minimal, complete/standalone code that reproduces where you got stuck.

Body:
I'm trying to create a user authentication screen, so I decided to use Firebase.

However, I am facing a problem. Nowadays I have enabled 2 providers, which are:

1- E-mail/Password
2- Google

Enabled providers

I can create users perfectly.

When I create a user with E-mail/password option and use the Gmail address guilherme.nunes@fover.com.br, Firebase creates the user normally.

After using email, I am trying to use the second option of Google provider, using the same email. Now the old user is replaced with the new provider in Firebase.

account created

After this, if I try to login with the first option (E-mail/Password) again, it says that the user does not exist.

I tried disabling the option to have 1 user per account, but then, Firebase creates 2 distinct users.

What I would like, is to link 1 account, with several providers.

Can someone help me, please?


问:
Which callback does ActiveRecord use to record timestamp?
I'm just wondering here whether any of you guys know when ActiveRecord use it's "magic" to record the timestamp (e.g. created_at, updated_at).

What i mean when is, at which callback ? (if AR use callback at all).

I'm asking this because I want to create an auto-updating column (that record sequential number for each object) and I want to replicate AR way to do this as much as possible.

EDITED:
It seems that AR does it between after_validation and before_create/before_update. You can do some tests for this by creating a presence validation for created_at column and inserting new record with blank created_at, it would return an error.

答: I don't know where AR does it, but the proper place for what you describe sounds like before_create


问:
java GUI multiple buttons output display error?
I am beginner in Java. This is my first project.
The GUI of the code keeps changing every time I run the code.
Sometimes output doesn't even load completely.
This is the code for just initializing a chess board 8X8 jbuttons.

I have put down the images do checkout the hyperlinks below.

Is there any solution that shows the same output every time the code executes?

```<code>    package chess;
    import game.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;

    public class board{
    static JButton [][] spots =new  JButton [8][8];
    public static void main(String[] args){
    board b =new board();
    b.initializeboard(spots);
    }

    public void initializeboard(JButton [][] spots){
    JFrame f = new JFrame("CHESS");
    f.setVisible(true);
    f.setSize(800,800);

    GridLayout layout =new GridLayout(8,8,1,1);
    f.setLayout(layout);

    for(int ver=0;ver<8;ver++){
      for(int hor=0;hor<8;hor++){
           JButton button = new JButton();
           if((ver+hor)%2==0){
                    button.setBackground(Color.WHITE); }
           else{
                    button.setBackground(new Color(255,205,51)); }
           pieces p =new pieces();
           spots[ver][hor] = button;
           p.setButton(button);
           f.add(button);
           }
              }
                  } //initialize board
                       }  // close board
</code>```

Improper Execution

Correct Execution

Incomplete Execution

答:
I am beginner in Java.

First of all, class names SHOULD start with an upper case character. Have you even seen a class in the JDK that does not start with an upper case character? Learn by example from the code in your text book or tutorial.

Is there any solution that shows the same output every time the code executes?

All components should be added to the frame BEFORE the frame is made visible.

When the frame is made visible the layout manager is invoked and the components are given a size/location. If you add components to a visible panel, then you need to invoke revalidate() and repaint() on the panel to make sure the layout manager is invoked.

Must admit I'm not sure why you get this random behaviour. Some components are getting a size/location and other are not even though the layout manager is not invoked.

I would suggest you restructure your code something like:

```<code>JPanel chessboard = new JPanel( new GridLayout(8, 8,  1, 1) );
// add buttons to the panel

JFrame frame = new JFrame("CHESS")
frame.add(chessboard, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
</code>```

Other comments:

Don't set the size of the frame. Using 800 x 800 will not make each button 100 x 100. The frame size also include the title bar and borders, so each button size will be less than you expect.

Instead you can create a variable outside of your loops:

```<code>Dimension buttonSize = new Dimension(100, 100)
</code>```

Then when you create the button you use:

```<code>button.setPreferredSize( buttonSize );
</code>```

Now when pack() method is invoked is will size the frame at the preferred size of all the components added to the frame.

All Swing components should be create on the Event Dispatch Thread (EDT). Read the section from the Swing tutorial How to Make Frames. The FrameDemo.java code shows you one way to structure your class so that the invokeLater(…) method is used to make sure code executes on the EDT.

Don't make your variables static. This indicates incorrect class design. Check out the MenuLook.java example found in How to Use Menus for a slightly different design where your ChessBoard becomes a component created in another class. You can then define your instance variables in that class.

Body:
I am beginner in Java. This is my first project.
The GUI of the code keeps changing every time I run the code.
Sometimes output doesn't even load completely.
This is the code for just initializing a chess board 8X8 jbuttons.

I have put down the images do checkout the hyperlinks below.

Is there any solution that shows the same output every time the code executes?

    package chess;
    import game.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;

    public class board{
    static JButton [][] spots =new  JButton [8][8];
    public static void main(String[] args){
    board b =new board();
    b.initializeboard(spots);
    }

    public void initializeboard(JButton [][] spots){
    JFrame f = new JFrame("CHESS");
    f.setVisible(true);
    f.setSize(800,800);

    GridLayout layout =new GridLayout(8,8,1,1);
    f.setLayout(layout);

    for(int ver=0;ver<8;ver++){
      for(int hor=0;hor<8;hor++){
           JButton button = new JButton();
           if((ver+hor)%2==0){
                    button.setBackground(Color.WHITE); }
           else{
                    button.setBackground(new Color(255,205,51)); }
           pieces p =new pieces();
           spots[ver][hor] = button;
           p.setButton(button);
           f.add(button);
           }
              }
                  } //initialize board
                       }  // close board

Improper Execution

Correct Execution

Incomplete Execution

Body:
I am beginner in Java.

First of all, class names SHOULD start with an upper case character. Have you even seen a class in the JDK that does not start with an upper case character? Learn by example from the code in your text book or tutorial.

Is there any solution that shows the same output every time the code executes?

All components should be added to the frame BEFORE the frame is made visible.

When the frame is made visible the layout manager is invoked and the components are given a size/location. If you add components to a visible panel, then you need to invoke revalidate() and repaint() on the panel to make sure the layout manager is invoked.

Must admit I'm not sure why you get this random behaviour. Some components are getting a size/location and other are not even though the layout manager is not invoked.

I would suggest you restructure your code something like:

JPanel chessboard = new JPanel( new GridLayout(8, 8,  1, 1) );
// add buttons to the panel

JFrame frame = new JFrame("CHESS")
frame.add(chessboard, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );

Other comments:

Don't set the size of the frame. Using 800 x 800 will not make each button 100 x 100. The frame size also include the title bar and borders, so each button size will be less than you expect.

Instead you can create a variable outside of your loops:

Dimension buttonSize = new Dimension(100, 100)

Then when you create the button you use:

button.setPreferredSize( buttonSize );

Now when pack() method is invoked is will size the frame at the preferred size of all the components added to the frame.

All Swing components should be create on the Event Dispatch Thread (EDT). Read the section from the Swing tutorial How to Make Frames. The FrameDemo.java code shows you one way to structure your class so that the invokeLater(…) method is used to make sure code executes on the EDT.

Don't make your variables static. This indicates incorrect class design. Check out the MenuLook.java example found in How to Use Menus for a slightly different design where your ChessBoard becomes a component created in another class. You can then define your instance variables in that class.


问:
Detect if a Tcl script is run in a background process
I'm looking for a preferably cross-platform way to detect from within a Tcl script if the interpreter is running in a foreground or in a background process.

I've seen how to do it via ps (or /proc/$$/stat on Linux); is there a better way or do I have to hack something around that approach? I already have a utility library written in C so exposing the lowlevel API that ps also uses so I don't have to parse process output (or special file content) would be fine.

答:
Thanks to Donal I came up with the implementation below that should work on all POSIX Unix variants:</p>

```<code>/*
    processIsForeground

    synopsis: processIsForeground

    Returns true if the process is running in the foreground or false
    if in the background.
*/
int IsProcessForegroundCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    /* Check the arg count */
    if (objc != 1) {
        Tcl_WrongNumArgs(interp, 1, objv, NULL);
        return TCL_ERROR;
    }

    int fd;
    errno = 0;
    if ((fd = open("/dev/tty", O_RDONLY)) != -1) {
        const pid_t pgrp = getpgrp();
        const pid_t tcpgrp = tcgetpgrp(fd);
        if (pgrp != -1 && tcpgrp != -1) {
            Tcl_SetObjResult(interp, Tcl_NewBooleanObj(pgrp == tcpgrp));
            close(fd);
            return TCL_OK;
        }
        close(fd);
    }
    Tcl_SetErrno(errno);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, "processIsForeground: ", (char *)Tcl_PosixError(interp), NULL);
    return TCL_ERROR;
}

int Pextlib_Init(Tcl_Interp *interp)
{
    if (Tcl_InitStubs(interp, "8.4", 0) == NULL)
        return TCL_ERROR;
// SNIP
    Tcl_CreateObjCommand(interp, "processIsForeground", IsProcessForegroundCmd, NULL, NULL);

    if (Tcl_PkgProvide(interp, "Pextlib", "1.0") != TCL_OK)
        return TCL_ERROR;

    return TCL_OK;
}
</code>```

Body:
Thanks to Donal I came up with the implementation below that should work on all POSIX Unix variants:

/*
    processIsForeground

    synopsis: processIsForeground

    Returns true if the process is running in the foreground or false
    if in the background.
*/
int IsProcessForegroundCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    /* Check the arg count */
    if (objc != 1) {
        Tcl_WrongNumArgs(interp, 1, objv, NULL);
        return TCL_ERROR;
    }

    int fd;
    errno = 0;
    if ((fd = open("/dev/tty", O_RDONLY)) != -1) {
        const pid_t pgrp = getpgrp();
        const pid_t tcpgrp = tcgetpgrp(fd);
        if (pgrp != -1 && tcpgrp != -1) {
            Tcl_SetObjResult(interp, Tcl_NewBooleanObj(pgrp == tcpgrp));
            close(fd);
            return TCL_OK;
        }
        close(fd);
    }
    Tcl_SetErrno(errno);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, "processIsForeground: ", (char *)Tcl_PosixError(interp), NULL);
    return TCL_ERROR;
}

int Pextlib_Init(Tcl_Interp *interp)
{
    if (Tcl_InitStubs(interp, "8.4", 0) == NULL)
        return TCL_ERROR;
// SNIP
    Tcl_CreateObjCommand(interp, "processIsForeground", IsProcessForegroundCmd, NULL, NULL);

    if (Tcl_PkgProvide(interp, "Pextlib", "1.0") != TCL_OK)
        return TCL_ERROR;

    return TCL_OK;
}


问:
discord.py - Cannot get average colour of a user's avatar
So I have this function to return a user's avatar's average colour:

import discord
from discord.ext import commands
import asyncio
from PIL import Image
import requests
from io import BytesIO

class Bot(commands.Bot):

    ...

    @staticmethod
    async def get_average_colour(image_url, default=0x696969):
        try:
            resp = requests.get(image_url)
            assert resp.ok
            img = Image.open(BytesIO(resp.content))
            img2 = img.resize((1, 1), Image.ANTIALIAS)
            colour = img2.getpixel((0, 0))
            res = "{:02x}{:02x}{:02x}".format(*colour)
            return int(res, 16)
        except:
            return default

    ...
```

<p>This works, but the problem with this is that it uses <code>requests</code>, which is blocking. So I tried using <code>aiohttp</code> instead:</p>

<pre class="lang-py prettyprint-override"><code>import discord
from discord.ext import commands
import asyncio
from PIL import Image
import aiohttp
from io import BytesIO

class Bot(commands.Bot):

    ...

    @staticmethod
    async def get_average_colour(image_url, default=0x696969):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(image_url) as resp:
                    if resp.status != 200:
                        raise Exception
                    img = Image.open(BytesIO(await resp.read()))
            colour = img.resize((1, 1), Image.ANTIALIAS).getpixel((0, 0))
            return int("{:02x}{:02x}{:02x}".format(*colour), 16)
        except:
            return default

    ...
</code>```

When I tried to find the average colour of a random cat image link, the function works fine, but when I try to call this function with a user's avatar_url, the function always return the default value. Does anyone know what's wrong with that function?

答: A good way would be to convert image_url to a string. That way it will always remain a string, a not a discord.Asset object.

Body:
So I have this function to return a user's avatar's average colour:

import discord
from discord.ext import commands
import asyncio
from PIL import Image
import requests
from io import BytesIO

class Bot(commands.Bot):

    ...

    @staticmethod
    async def get_average_colour(image_url, default=0x696969):
        try:
            resp = requests.get(image_url)
            assert resp.ok
            img = Image.open(BytesIO(resp.content))
            img2 = img.resize((1, 1), Image.ANTIALIAS)
            colour = img2.getpixel((0, 0))
            res = "{:02x}{:02x}{:02x}".format(*colour)
            return int(res, 16)
        except:
            return default

    ...

This works, but the problem with this is that it uses requests, which is blocking. So I tried using aiohttp instead:

import discord
from discord.ext import commands
import asyncio
from PIL import Image
import aiohttp
from io import BytesIO

class Bot(commands.Bot):

    ...

    @staticmethod
    async def get_average_colour(image_url, default=0x696969):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(image_url) as resp:
                    if resp.status != 200:
                        raise Exception
                    img = Image.open(BytesIO(await resp.read()))
            colour = img.resize((1, 1), Image.ANTIALIAS).getpixel((0, 0))
            return int("{:02x}{:02x}{:02x}".format(*colour), 16)
        except:
            return default

    ...

When I tried to find the average colour of a random cat image link, the function works fine, but when I try to call this function with a user's avatar_url, the function always return the default value. Does anyone know what's wrong with that function?


问:
Graph cycle detection with Prolog
I am trying to write a prolog program that detects a cycle in an undirected graph.
I have already consulted this question: prolog graph depth first search

and have attempted to alter the dfs algorithm presented there, in order to detect cycles.
Here is my progress so far:

```<code>findCycle(Node, NextNode, Visited) :-
      ( member(NextNode, Visited), isNotParent(Node, NextNode) )
    ->
      writeln("found a cycle"), saveCycle(Node, NextNode), !
    ;
      writeln("end of findCycle").

saveCycle(Node, NextNode) :-
    % save to structure

dfs(Graph, StartNode) :-
    dfs(Graph, StartNode, []).

dfs(Graph, Node, Visited) :-
    writeln(Visited),
    \+ member(Node, Visited),
    write("visiting node "),
    write(Node), nl,
    member(NextNode, Graph.get(Node)),
    % \+ findCycle(Node, NextNode, Visited),
    dfs(Graph, NextNode, [Node|Visited]).
</code>```

The graph in my implementation will be represented as a dictionary, where every key is a vertex, and the corresponding value is a list of all its neighboring vertices.
Now, I have a few problems:

I need to be storing the "parent" of each vertex in a data structure, so that it can be used for cycle detection. I am not sure about how to do that. So far I have been testing the program with an example graph, whose edges I enter manually with individual terms. That is not, however, my end goal.

I also need to fix the dfs algorithm, because as it is right now, it causes stack overflow, due to the Visited list not storing all the vertices persistently. Ideally, Visited should be a dictionary instead of a list, so it can be accessed more efficiently.

Finally, if a cycle is detected, I would like to save all the vertices participating in it, into another data structure.

Though I know programming, and have written this program in C++ in the past, my grasp of prolog is at best rudimentary, so any help would be appreciated. Thanks!

答:
You're somewhat overengineering...

Just simplify your code to the bare needed, and you'll get what you're after... for instance:

find_cycle(G,Vs) :-
  member(V-_Edges,G), % don't care about starting point
  find_cycle(G,V,[],Vs).

find_cycle(_G,V,SeenVs,[V|SeenVs]) :-
  memberchk(V,SeenVs).
find_cycle(G,V,SeenVs,Cycle) :-
  \+memberchk(V,SeenVs),
  member(V-Es,G),
  member(Ve,Es),
  find_cycle(G,Ve,[V|SeenVs],Cycle).

?- G=[a-[b,c],b-[a,c],c-[]],find_cycle(G,C).
G = [a-[b, c], b-[a, c], c-[]],
C = [a, b, a] ;
G = [a-[b, c], b-[a, c], c-[]],
C = [b, a, b] ;
false.

```

<p>Or, to avoid the duplicate search in visited edges list:</p>

<pre class="lang-erlang prettyprint-override"><code>find_cycle(G,V,SeenVs,Cycle) :-
  (   memberchk(V,SeenVs)
  ->  Cycle=[V|SeenVs]
  ;   member(V-Es,G),
      member(Ve,Es),
      find_cycle(G,Ve,[V|SeenVs],Cycle)
  ).
</code>```

edit after comment...

For efficiency, note I used memberchk/2 in the test, not member/2. The implementation in SWI-Prolog it's very fast, since uses the low level representation of lists (skip list), done in C. So, you should have very long lists before you start to observe some improvements using some other data structure (there are some... like rbtrees, avltrees, ...). But if your lists are so big, then the whole algorithm should be improved. Again, there are some, you can start looking in library(ugraph).

Title: Graph cycle detection with Prolog

Body:
I am trying to write a prolog program that detects a cycle in an undirected graph.
I have already consulted this question: prolog graph depth first search

and have attempted to alter the dfs algorithm presented there, in order to detect cycles.
Here is my progress so far:

findCycle(Node, NextNode, Visited) :-
      ( member(NextNode, Visited), isNotParent(Node, NextNode) )
    ->
      writeln("found a cycle"), saveCycle(Node, NextNode), !
    ;
      writeln("end of findCycle").

saveCycle(Node, NextNode) :-
    % save to structure

dfs(Graph, StartNode) :-
    dfs(Graph, StartNode, []).

dfs(Graph, Node, Visited) :-
    writeln(Visited),
    \+ member(Node, Visited),
    write("visiting node "),
    write(Node), nl,
    member(NextNode, Graph.get(Node)),
    % \+ findCycle(Node, NextNode, Visited),
    dfs(Graph, NextNode, [Node|Visited]).

The graph in my implementation will be represented as a dictionary, where every key is a vertex, and the corresponding value is a list of all its neighboring vertices.
Now, I have a few problems:

I need to be storing the "parent" of each vertex in a data structure, so that it can be used for cycle detection. I am not sure about how to do that. So far I have been testing the program with an example graph, whose edges I enter manually with individual terms. That is not, however, my end goal.

I also need to fix the dfs algorithm, because as it is right now, it causes stack overflow, due to the Visited list not storing all the vertices persistently. Ideally, Visited should be a dictionary instead of a list, so it can be accessed more efficiently.

Finally, if a cycle is detected, I would like to save all the vertices participating in it, into another data structure.

Though I know programming, and have written this program in C++ in the past, my grasp of prolog is at best rudimentary, so any help would be appreciated. Thanks!

Body:
You're somewhat overengineering...

Just simplify your code to the bare needed, and you'll get what you're after... for instance:

find_cycle(G,Vs) :-
  member(V-_Edges,G), % don't care about starting point
  find_cycle(G,V,[],Vs).

find_cycle(_G,V,SeenVs,[V|SeenVs]) :-
  memberchk(V,SeenVs).
find_cycle(G,V,SeenVs,Cycle) :-
  \+memberchk(V,SeenVs),
  member(V-Es,G),
  member(Ve,Es),
  find_cycle(G,Ve,[V|SeenVs],Cycle).

?- G=[a-[b,c],b-[a,c],c-[]],find_cycle(G,C).
G = [a-[b, c], b-[a, c], c-[]],
C = [a, b, a] ;
G = [a-[b, c], b-[a, c], c-[]],
C = [b, a, b] ;
false.

Or, to avoid the duplicate search in visited edges list:

find_cycle(G,V,SeenVs,Cycle) :-
  (   memberchk(V,SeenVs)
  ->  Cycle=[V|SeenVs]
  ;   member(V-Es,G),
      member(Ve,Es),
      find_cycle(G,Ve,[V|SeenVs],Cycle)
  ).

edit after comment...

For efficiency, note I used memberchk/2 in the test, not member/2. The implementation in SWI-Prolog it's very fast, since uses the low level representation of lists (skip list), done in C. So, you should have very long lists before you start to observe some improvements using some other data structure (there are some... like rbtrees, avltrees, ...). But if your lists are so big, then the whole algorithm should be improved. Again, there are some, you can start looking in library(ugraph).


问:
Browser extension, - Accessing the images before rendering
I'm a photographer with a good IT background.

I'm looking to intercept the rendering of images in websites, possibly through a browser extension. My plan is to identify the use of my photos automatically when browsing the web.

So what I need to do - you tell me the best way how please:) - is to intercept the rendering of the image, read the image and possibly modify it.

Are extensions/addOns a good approach? Is there another way? Possibly using c#...

Cheers
Marc

答:
This is called Digital Rights Management (DRM).  You as well as Hollyweird would love to stop everyone from free viewing.  But once its on the web, only laywers can stop people viewing.

Here's a good place to start your research.  http://en.wikipedia.org/wiki/Digital_rights_management


问:
How to get more than 100 rows using Airtable API using offest?
I am really new to the Airtable API and for some reason connecting the API this way did not work.

```<code>at = airtable.Airtable('Base_Key', 'Airtable_Key')
</code>```

But I got it working this way -

```<code>get_url = ‘https://api.airtable.com/v0/BASE_ID/TABLE_NAME’
get_headers = {
‘Authorization’: ‘Bearer API_KEY’ }

Response = requests.get(get_url, headers=get_headers)
Response_Table = Response.json()
</code>```

However, this fetches only the first 100 records and am reading about offset and pagination but I am unable to figure how to incorporate it into this code.

Thank you for the time!

答:
After a lot of issues, I found this solution. Posting it for anyone else facing the same problem.</p>

```<code>global offset
offset = '0'
result = []

while True :
    url = "https://api.airtable.com/v0/BASE_ID/TABLE_NAME"
    querystring = {
        "view":"Published View",
        "api_key":"YOUR_KEY",
        "offset": offset}

    try :
        response= requests.get(url, params=querystring)
        response_Table = response.json()
        records = list(response_Table['records'])
        result.append(records)
        #print(records[0]['id'] , len(records))

        try :
            offset = response_Table['offset']
            #print(offset)

        except Exception as ex:
            #print(ex , offset)
            break

    except error as e:
        print(e)
</code>```

Body:
I am really new to the Airtable API and for some reason connecting the API this way did not work.

at = airtable.Airtable('Base_Key', 'Airtable_Key')

But I got it working this way -

get_url = ‘https://api.airtable.com/v0/BASE_ID/TABLE_NAME’
get_headers = {
‘Authorization’: ‘Bearer API_KEY’ }

Response = requests.get(get_url, headers=get_headers)
Response_Table = Response.json()

However, this fetches only the first 100 records and am reading about offset and pagination but I am unable to figure how to incorporate it into this code.

Thank you for the time!

Body:
After a lot of issues, I found this solution. Posting it for anyone else facing the same problem.

global offset
offset = '0'
result = []

while True :
    url = "https://api.airtable.com/v0/BASE_ID/TABLE_NAME"
    querystring = {
        "view":"Published View",
        "api_key":"YOUR_KEY",
        "offset": offset}

    try :
        response= requests.get(url, params=querystring)
        response_Table = response.json()
        records = list(response_Table['records'])
        result.append(records)
        #print(records[0]['id'] , len(records))

        try :
            offset = response_Table['offset']
            #print(offset)

        except Exception as ex:
            #print(ex , offset)
            break

    except error as e:
        print(e)


问:
How can I get the profile image of an Instagram user?
I have some codes that I found for profile picture (which works very well) However, how can I do it for the post picture. (Like: https://www.instagram.com/p/CAnkEFFnlC2/)

function getPhoto(a) {

  // validation for instagram usernames
  var regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/);
  var validation = regex.test(a);

  if (validation) {
    $.get("https://www.instagram.com/" + a + "/?__a=1")
      .done(function(data) {

        // getting the url
        var photoURL = data["graphql"]["user"]["profile_pic_url_hd"];

        // update img element
        $("#photoReturn").attr("src", photoURL)
      })
      .fail(function() {
        // code for 404 error
        console.log('Username was not found!')
      })
  } else {
    console.log('The username is invalid!')
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="" id="photoReturn">
<br><br>
<input type="text" id="usernameInput">
<button onclick="getPhoto($('#usernameInput').val().trim())">Get profile photo</button></code>```

How can I do it?

答:
Its really simple, add  /media?size=l at the end of your url.

Ex: https://www.instagram.com/p/CAnkEFFnlC2/media?size=l
(Parameters)   l,m,s,t stands for large,medium,small and thumbnail size.

Body:
I have some codes that I found for profile picture (which works very well) However, how can I do it for the post picture. (Like: https://www.instagram.com/p/CAnkEFFnlC2/)

function getPhoto(a) {

  // validation for instagram usernames
  var regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/);
  var validation = regex.test(a);

  if (validation) {
    $.get("https://www.instagram.com/" + a + "/?__a=1")
      .done(function(data) {

        // getting the url
        var photoURL = data["graphql"]["user"]["profile_pic_url_hd"];

        // update img element
        $("#photoReturn").attr("src", photoURL)
      })
      .fail(function() {
        // code for 404 error
        console.log('Username was not found!')
      })
  } else {
    console.log('The username is invalid!')
  }
}

<input type="text" id="usernameInput">
<button onclick="getPhoto($('#usernameInput').val().trim())">Get profile photo</button>

How can I do it?


问:
Visual Studio 2017 - How to fix error: We could not refresh the credentials for the account
My email address has changed and now I can't log into Visual Studio 2017.

The error is "We could not refresh the credentials for the account. Failed to refresh the access token".

How can I fix this?

答:
Very old thread but if someone is still having this issue, then try following in my footsteps:

I just deleted the entire .IdentityService folder, and launched visual studio again... It asks you to log in and works normally. (for me)


问:
How to access a classes attribute variable in other method
I am learning python3 and I want to know that how I can

```<code>class testit:
    def assigna():
        a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())
</code>```

How can I access a inside of geta as suggested in comments I tried to use self.a and it gives me an error.

Here is my Updated Code

```<code>class testit:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())
</code>```

and here is the error.

```<code>Traceback (most recent call last):
  File "test.py", line 44, in <module>
    print(test.geta())
TypeError: geta() missing 1 required positional argument: 'self'

</code>```

答:
when you pass self in argument of method it refers to an object so you have to assign a as object attribute before.

you also have to make an instance of this class with calling it like this classname().

```<code>class TestIt:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        return self.a

test = TestIt()
test.assigna()
test.geta()
print(test.geta())
</code>```

Body:
I am learning python3 and I want to know that how I can

class testit:
    def assigna():
        a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())

How can I access a inside of geta as suggested in comments I tried to use self.a and it gives me an error.

Here is my Updated Code

class testit:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())

and here is the error.

Traceback (most recent call last):
  File "test.py", line 44, in <module>
    print(test.geta())
TypeError: geta() missing 1 required positional argument: 'self'

Body:
when you pass self in argument of method it refers to an object so you have to assign a as object attribute before.

you also have to make an instance of this class with calling it like this classname().

class TestIt:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        return self.a

test = TestIt()
test.assigna()
test.geta()
print(test.geta())


问:
Unable to load pdo_sqlite.so extension
I'm trying to install the pdo-sqlite ext for the cli.

I have tried to run sudo apt-get install php5-sqlite and it says the ext is already up to date but when i run php -m it does not appear in the list.

In my /usr/lib/php/ folder I have 2 folders named 20131226 and 20160303. The latter one (20160303) contains pdo_sqlite.so but when i try to add this to the php.ini file i get the error

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20160303/pdo_sqlite.so' - /usr/lib/php/20160303/pdo_sqlite.so: undefined symbol: zend_fetch_resource2_ex in Unknown on line 0

I am running ubuntu 14.04 and php 5.6.

Is anyone able to help with this problem? Also is anyone able to explain why the php extensions are stored in these different numbered folders and how php knows which one to look in? Thanks.

答:
you can try install php version 5 :

```<code>sudo apt install php5-sqlite3
</code>```

or for another version :

PHP 7.1

```<code>sudo apt install php7.1-sqlite3
</code>```

PHP 7.2

```<code>sudo apt install php7.2-sqlite3
</code>```

PHP 7.3

```<code>sudo apt install php7.3-sqlite3
</code>```

and another version you want....

Title: Unable to load pdo_sqlite.so extension

Body:
you can try install php version 5 :

sudo apt install php5-sqlite3

or for another version :

PHP 7.1

sudo apt install php7.1-sqlite3

PHP 7.2

sudo apt install php7.2-sqlite3

PHP 7.3

sudo apt install php7.3-sqlite3

and another version you want....