问:
org.json.JSONException value type java.lang.String cannot be converted to JSONObject
I'm trying to make a login/register app and when i run the code i get this error and my code doesn't work. What am i doing wrong? how can i solve this?
If additional code is needed i can provide. Also if this question has a response already can you guide me to that response? I'm trying to find a solution to this problem since 2 days ago and can't seem to find what the problem is. I'm quite new to coding so any help is welcomed.

db_connect.php

```<code><?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "member"); // database name
define('DB_SERVER', "localhost"); // db server

$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);

// Check connection
if(mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

?>
</code>```

Function.php

```<code><?php
$random_salt_length = 32;
/**
* Queries the database and checks whether the user already exists
*
* @param $username
*
* @return
*/
function userExists($username){
 $query = "SELECT username FROM member WHERE username = ?";
 global $con;
 if($stmt = $con->prepare($query)){
 $stmt->bind_param("s",$username);
 $stmt->execute();
 $stmt->store_result();
 $stmt->fetch();
 if($stmt->num_rows == 1){
 $stmt->close();
 return true;
 }
 $stmt->close();
 }

 return false;
}

function concatPasswordWithSalt($password,$salt){
 global $random_salt_length;
 if($random_salt_length % 2 == 0){
 $mid = $random_salt_length / 2;
 }
 else{
 $mid = ($random_salt_length - 1) / 2;
 }

 return
 substr($salt,0,$mid - 1).$password.substr($salt,$mid,$random_salt_length - 1);

}
?>
</code>```

Login.php

```<code><?php
$response = array();
include 'db/db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON); //convert JSON into array
//Check for Mandatory parameters
if(isset($input->username) && isset($input->password)){
$username = $input->username;
$password = $input->password;
$query    = "SELECT full_name,password_hash, salt FROM member WHERE username = ?";
if($stmt = $con->prepare($query)){
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($fullName,$passwordHashDB,$salt);
if($stmt->fetch()){
//Validate the password
if(password_verify(concatPasswordWithSalt($password,$salt),$passwordHashDB)){
$response["status"] = 0;
$response["message"] = "Login successful";
$response["full_name"] = $fullName;
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
$stmt->close();
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
//Display the JSON response
echo json_encode($response);
?>
</code>```

Register.php

<?php
$response = array();
include 'db/db_connect.php';
include 'Functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) && isset($input['full_name'])){
$username = $input['username'];
$password = $input['password'];
$fullName = $input['full_name'];
//Check if user already exist
if(!userExists($username)){
//Get a unique Salt
$salt         = getSalt();
//Generate a unique password Hash
$passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);
//Query to register new user
$insertQuery  = "INSERT INTO member(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
}
else{
$response["status"] = 1;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>
```

<p>RegisterActivity.java</p>

<pre class="lang-java prettyprint-override"><code>package com.example.activitymanagement;

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

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

public class RegisterActivity extends AppCompatActivity {
    private static final String KEY_STATUS = "status";
    private static final String KEY_MESSAGE = "message";
    private static final String KEY_FULL_NAME = "full_name";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_EMPTY = "";
    private EditText etUsername;
    private EditText etPassword;
    private EditText etConfirmPassword;
    private EditText etFullName;
    private String username;
    private String password;
    private String confirmPassword;
    private String fullName;
    private ProgressDialog pDialog;
    private String register_url = "http://10.0.2.2/member/register.php";
    private SessionHandler session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        session = new SessionHandler(getApplicationContext());
        setContentView(R.layout.activity_register);

        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        etFullName = findViewById(R.id.etFullName);

        Button login = findViewById(R.id.btnRegisterLogin);
        Button register = findViewById(R.id.btnRegister);

        //Launch Login screen when Login Button is clicked
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Retrieve the data entered in the edit texts
                username = etUsername.getText().toString().toLowerCase().trim();
                password = etPassword.getText().toString().trim();
                confirmPassword = etConfirmPassword.getText().toString().trim();
                fullName = etFullName.getText().toString().trim();
                if (validateInputs()) {
                    registerUser();
                }

            }
        });

    }

    /**
     * Display Progress bar while registering
     */
    private void displayLoader() {
        pDialog = new ProgressDialog(RegisterActivity.this);
        pDialog.setMessage("Signing Up.. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    /**
     * Launch Dashboard Activity on Successful Sign Up
     */
    private void loadDashboard() {
        Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
        startActivity(i);
        finish();

    }

    private void registerUser() {
        displayLoader();
        JSONObject request = new JSONObject();
        try {
            //Populate the request parameters
            request.put(KEY_USERNAME, username);
            request.put(KEY_PASSWORD, password);
            request.put(KEY_FULL_NAME, fullName);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsArrayRequest = new JsonObjectRequest
                (Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        pDialog.dismiss();
                        try {
                            //Check if user got registered successfully
                            if (response.getInt(KEY_STATUS) == 0) {
                                //Set the user session
                                session.loginUser(username,fullName);
                                loadDashboard();

                            }else if(response.getInt(KEY_STATUS) == 1){
                                //Display error message if username is already existsing
                                etUsername.setError("Username already taken!");
                                etUsername.requestFocus();

                            }else{
                                Toast.makeText(getApplicationContext(),
                                        response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pDialog.dismiss();

                        //Display error message whenever an error occurs
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                });

        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
    }

    /**
     * Validates inputs and shows error if any
     * @return
     */
    private boolean validateInputs() {
        if (KEY_EMPTY.equals(fullName)) {
            etFullName.setError("Full Name cannot be empty");
            etFullName.requestFocus();
            return false;

        }
        if (KEY_EMPTY.equals(username)) {
            etUsername.setError("Username cannot be empty");
            etUsername.requestFocus();
            return false;
        }
        if (KEY_EMPTY.equals(password)) {
            etPassword.setError("Password cannot be empty");
            etPassword.requestFocus();
            return false;
        }

        if (KEY_EMPTY.equals(confirmPassword)) {
            etConfirmPassword.setError("Confirm Password cannot be empty");
            etConfirmPassword.requestFocus();
            return false;
        }
        if (!password.equals(confirmPassword)) {
            etConfirmPassword.setError("Password and Confirm Password does not match");
            etConfirmPassword.requestFocus();
            return false;
        }

        return true;
    }
}
</code>```

答:
please change below line in your php script for getting request params, because you are sending request param inside json object and getting in string format</p>

```<code> $input = json_decode($inputJSON);
 if(isset($input->username) && isset($input->password) && isset($input->full_name)){
$username = $input->username;
$password = $input->password;
$fullName = $input->full_name;
}
</code>```

Body:
I'm trying to make a login/register app and when i run the code i get this error and my code doesn't work. What am i doing wrong? how can i solve this?
If additional code is needed i can provide. Also if this question has a response already can you guide me to that response? I'm trying to find a solution to this problem since 2 days ago and can't seem to find what the problem is. I'm quite new to coding so any help is welcomed.

db_connect.php

<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "member"); // database name
define('DB_SERVER', "localhost"); // db server

$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);

// Check connection
if(mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

?>

Function.php

<?php
$random_salt_length = 32;
/**
* Queries the database and checks whether the user already exists
*
* @param $username
*
* @return
*/
function userExists($username){
 $query = "SELECT username FROM member WHERE username = ?";
 global $con;
 if($stmt = $con->prepare($query)){
 $stmt->bind_param("s",$username);
 $stmt->execute();
 $stmt->store_result();
 $stmt->fetch();
 if($stmt->num_rows == 1){
 $stmt->close();
 return true;
 }
 $stmt->close();
 }

 return false;
}

function concatPasswordWithSalt($password,$salt){
 global $random_salt_length;
 if($random_salt_length % 2 == 0){
 $mid = $random_salt_length / 2;
 }
 else{
 $mid = ($random_salt_length - 1) / 2;
 }

 return
 substr($salt,0,$mid - 1).$password.substr($salt,$mid,$random_salt_length - 1);

}
?>

Login.php

<?php
$response = array();
include 'db/db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON); //convert JSON into array
//Check for Mandatory parameters
if(isset($input->username) && isset($input->password)){
$username = $input->username;
$password = $input->password;
$query    = "SELECT full_name,password_hash, salt FROM member WHERE username = ?";
if($stmt = $con->prepare($query)){
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($fullName,$passwordHashDB,$salt);
if($stmt->fetch()){
//Validate the password
if(password_verify(concatPasswordWithSalt($password,$salt),$passwordHashDB)){
$response["status"] = 0;
$response["message"] = "Login successful";
$response["full_name"] = $fullName;
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
$stmt->close();
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
//Display the JSON response
echo json_encode($response);
?>

Register.php

<?php
$response = array();
include 'db/db_connect.php';
include 'Functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) && isset($input['full_name'])){
$username = $input['username'];
$password = $input['password'];
$fullName = $input['full_name'];
//Check if user already exist
if(!userExists($username)){
//Get a unique Salt
$salt         = getSalt();
//Generate a unique password Hash
$passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);
//Query to register new user
$insertQuery  = "INSERT INTO member(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
}
else{
$response["status"] = 1;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>

RegisterActivity.java

package com.example.activitymanagement;

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

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

public class RegisterActivity extends AppCompatActivity {
    private static final String KEY_STATUS = "status";
    private static final String KEY_MESSAGE = "message";
    private static final String KEY_FULL_NAME = "full_name";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_EMPTY = "";
    private EditText etUsername;
    private EditText etPassword;
    private EditText etConfirmPassword;
    private EditText etFullName;
    private String username;
    private String password;
    private String confirmPassword;
    private String fullName;
    private ProgressDialog pDialog;
    private String register_url = "http://10.0.2.2/member/register.php";
    private SessionHandler session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        session = new SessionHandler(getApplicationContext());
        setContentView(R.layout.activity_register);

        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        etFullName = findViewById(R.id.etFullName);

        Button login = findViewById(R.id.btnRegisterLogin);
        Button register = findViewById(R.id.btnRegister);

        //Launch Login screen when Login Button is clicked
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Retrieve the data entered in the edit texts
                username = etUsername.getText().toString().toLowerCase().trim();
                password = etPassword.getText().toString().trim();
                confirmPassword = etConfirmPassword.getText().toString().trim();
                fullName = etFullName.getText().toString().trim();
                if (validateInputs()) {
                    registerUser();
                }

            }
        });

    }

    /**
     * Display Progress bar while registering
     */
    private void displayLoader() {
        pDialog = new ProgressDialog(RegisterActivity.this);
        pDialog.setMessage("Signing Up.. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    /**
     * Launch Dashboard Activity on Successful Sign Up
     */
    private void loadDashboard() {
        Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
        startActivity(i);
        finish();

    }

    private void registerUser() {
        displayLoader();
        JSONObject request = new JSONObject();
        try {
            //Populate the request parameters
            request.put(KEY_USERNAME, username);
            request.put(KEY_PASSWORD, password);
            request.put(KEY_FULL_NAME, fullName);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsArrayRequest = new JsonObjectRequest
                (Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        pDialog.dismiss();
                        try {
                            //Check if user got registered successfully
                            if (response.getInt(KEY_STATUS) == 0) {
                                //Set the user session
                                session.loginUser(username,fullName);
                                loadDashboard();

                            }else if(response.getInt(KEY_STATUS) == 1){
                                //Display error message if username is already existsing
                                etUsername.setError("Username already taken!");
                                etUsername.requestFocus();

                            }else{
                                Toast.makeText(getApplicationContext(),
                                        response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pDialog.dismiss();

                        //Display error message whenever an error occurs
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                });

        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
    }

    /**
     * Validates inputs and shows error if any
     * @return
     */
    private boolean validateInputs() {
        if (KEY_EMPTY.equals(fullName)) {
            etFullName.setError("Full Name cannot be empty");
            etFullName.requestFocus();
            return false;

        }
        if (KEY_EMPTY.equals(username)) {
            etUsername.setError("Username cannot be empty");
            etUsername.requestFocus();
            return false;
        }
        if (KEY_EMPTY.equals(password)) {
            etPassword.setError("Password cannot be empty");
            etPassword.requestFocus();
            return false;
        }

        if (KEY_EMPTY.equals(confirmPassword)) {
            etConfirmPassword.setError("Confirm Password cannot be empty");
            etConfirmPassword.requestFocus();
            return false;
        }
        if (!password.equals(confirmPassword)) {
            etConfirmPassword.setError("Password and Confirm Password does not match");
            etConfirmPassword.requestFocus();
            return false;
        }

        return true;
    }
}

Body:
please change below line in your php script for getting request params, because you are sending request param inside json object and getting in string format

 $input = json_decode($inputJSON);
 if(isset($input->username) && isset($input->password) && isset($input->full_name)){
$username = $input->username;
$password = $input->password;
$fullName = $input->full_name;
}


来源: stackexchange

问:
Read list from a file
I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

```<code>"11","Arial","red","white","black","200x200","My Project"
</code>```

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)
```

<p>Here's the part that does not work:</p>

<pre class="lang-py prettyprint-override"><code>conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])
</code>```

This returns 1 instead of red

答:
You can use csv module.

```<code>import csv

def fread(file_name):
    with open(file_name) as f:
        return next(csv.reader(f))

print(fread("file.name"))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Read list from a file

Body:
I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

"11","Arial","red","white","black","200x200","My Project"

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)

Here's the part that does not work:

conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])

This returns 1 instead of red

Body:
You can use csv module.

import csv

def fread(file_name):
    with open(file_name) as f:
        return next(csv.reader(f))

print(fread("file.name"))


问:
How can I convert Google Maps plus codes to Lng & Lat coordinates
I'm working on a project and I'm using some old google maps stuff. It requires longitude and latitude gps coordinates to get the location of a hospital for example.

I can't find a way to retrieve that info in this format 'lng,lat'

For example:   (34.417514, 8.7518123)

The only thing the new google maps has is plus codes (used by https://plus.codes/)  which they use as the location coordinates.

Can you guys help me find out a way to convert them to lng lat format or a way to retrieve the lng and lat from Google Maps website directly.

Or an alternative by saving my geolocation in a plus codes format in android studio (in a database of course) instead of using lat lng

https://www.up-00.com/i/00125/m4kadq6c7aeb.png

答:
You can convert Plus Codes into lat/lng format via Plus codes API. If you have full (8-digits before "+" character, e.g. 8F6CCQCW+2F for your location) Plus Code, you can locally (without any internet request) use OpenLocationCode.decode() method this way:

```<code>...
OpenLocationCode olc = new OpenLocationCode("8F6CCQCW+2F");
Log.d(TAG, "Lat = " + olc.decode().getCenterLatitude() + "  Lng = " + olc.decode().getCenterLongitude());
...
</code>```

If you have short Plus Code (less than 8 digits before "+" character, e.g. CCQCW+2F Gafsa for your location, Gafsa is the area and it's used instead of using the full plus code) you can use HttpURLConnection with

```<code>`https://plus.codes/api?address=CCQCW%2B2F Gafsa&key=YOUR_GEOCODING_API_KEY`
</code>```

(%2B is for the for + symbol)

(NB! you need Geocoding API Key for geocode Gafsa part, which is the area, you need an area with a short plus code)
and get location.lat and location.lng tags from its JSON response:

```<code>{
  "plus_code": {
    "global_code": "8F6CCQJG+",
    "geometry": {
      "bounds": {
        "northeast": {
          "lat": 34.432500000000005,
          "lng": 8.777500000000003
        },
        "southwest": {
          "lat": 34.43000000000001,
          "lng": 8.775000000000006
        }
      },
      "location": {
        "lat": 34.431250000000006,
        "lng": 8.776250000000005
      }
    },
    "locality": {}
  },
  "status": "OK"
}
</code>```

For "alternative" (saving my geolocation in a plus codes format) you can (fully local) use encode() method of OpenLocationCode class:

```<code>OpenLocationCode.encode(34.43125, 8.77625)
</code>```

Body:
You can convert Plus Codes into lat/lng format via Plus codes API. If you have full (8-digits before "+" character, e.g. 8F6CCQCW+2F for your location) Plus Code, you can locally (without any internet request) use OpenLocationCode.decode() method this way:

...
OpenLocationCode olc = new OpenLocationCode("8F6CCQCW+2F");
Log.d(TAG, "Lat = " + olc.decode().getCenterLatitude() + "  Lng = " + olc.decode().getCenterLongitude());
...

If you have short Plus Code (less than 8 digits before "+" character, e.g. CCQCW+2F Gafsa for your location, Gafsa is the area and it's used instead of using the full plus code) you can use HttpURLConnection with

`https://plus.codes/api?address=CCQCW%2B2F Gafsa&key=YOUR_GEOCODING_API_KEY`

(%2B is for the for + symbol)

(NB! you need Geocoding API Key for geocode Gafsa part, which is the area, you need an area with a short plus code)
and get location.lat and location.lng tags from its JSON response:

{
  "plus_code": {
    "global_code": "8F6CCQJG+",
    "geometry": {
      "bounds": {
        "northeast": {
          "lat": 34.432500000000005,
          "lng": 8.777500000000003
        },
        "southwest": {
          "lat": 34.43000000000001,
          "lng": 8.775000000000006
        }
      },
      "location": {
        "lat": 34.431250000000006,
        "lng": 8.776250000000005
      }
    },
    "locality": {}
  },
  "status": "OK"
}

For "alternative" (saving my geolocation in a plus codes format) you can (fully local) use encode() method of OpenLocationCode class:

OpenLocationCode.encode(34.43125, 8.77625)


问:
ROW_NUMBER() equivalent function in mysql
Hey every one I want to generate surrogate key by getting Max() from one table in sql I did some thing like that

```<code>coalesce(max(INDVL_ID), 0) + ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
</code>```

now I have to do same thing in mysql so issue is that I am unable to get alternate of ROW_NUMBER() Any one have solution

答:
The answer here has been depreciated.   Please use the following in MySQL version 8: </p>

```<code>ROW_NUMBER() OVER ( ORDER BY someField) AS 'row_number'
</code>```

<p>EXAMPLE: </p>

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY s.Id) AS 'row_num',
    s.product,
    s.title
FROM supplies AS S
</code>```

Body:
Hey every one I want to generate surrogate key by getting Max() from one table in sql I did some thing like that

coalesce(max(INDVL_ID), 0) + ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

now I have to do same thing in mysql so issue is that I am unable to get alternate of ROW_NUMBER() Any one have solution

Body:
The answer here has been depreciated.   Please use the following in MySQL version 8:

ROW_NUMBER() OVER ( ORDER BY someField) AS 'row_number'

EXAMPLE:

SELECT
    ROW_NUMBER() OVER (ORDER BY s.Id) AS 'row_num',
    s.product,
    s.title
FROM supplies AS S


问:
Dataframe slicing on multiple conditions Python
I have a dataframe with 3 columns:

```<code>df:

x       y      z
334     290    3350.0
334     291    3350.5
334     292    3360.1
335     292    3360.1
335     292    3360.1
335     290    3351.0
335     290    3352.5
335     291    3333.1
335     291    3333.1
.
.
</code>```

I'd like to check and parse values of each row from row = n to row = n+7 into a new dataframe based on a couple of conditions:

df[n] != df[n+1]

df[n] != df[n+3]

df[n] != df[n+5]

df['x'][n] < df['x'][n+2]

df['x'][n] > df['x'][n+3]

If all of these are satisfied I want to write a new dataframe:

```<code>df_new = pd.concat([df[n], df[n+1], df[n+2], df[n+3],
df[n+4], df[n+5], df[n+6], df[n+7]])
</code>```

So the algorithm + output would look like:

```<code>for df[n] = 0:
1) [334     290    3350.0] != [334     291    3350.5]  True
2) [334     290    3350.0] != [335     292    3360.1]  True
3) [334     290    3350.0] != [335     290    3351.0]  True
4) 335 < 334  False
5) 335 > 335  False
</code>```

So in this case it would skip the first iteration until we've gone down the entire length of the dataframe and made matches.

df_new(first iteration) = df_new.concat([....]) = empty row values

Is there an easy way to do this with speed in Pandas?

答:
A. Get the appropriate shifts:

```<code>    n1 = df.shift(-1)
    n2 = df.shift(-2)
    n3 = df.shift(-3)
    n5 = df.shift(-5)
</code>```

B. Satisfy conditions 1, 2 and 3:

```<code>cond = (df != n1) & (df != n3) & (df != n5)
</code>```

C. Satisfy conditions 4, 5:

```<code> cond['holder'] = (df.x < n2.x) & (df.x < n3.x)
</code>```

D. Get bool series (we want any row with all 'True'):

```<code>boolidx = cond.all(axis=1)
</code>```

E. Use to get result:

```<code>df.loc[boolidx]
</code>```

Body:
I have a dataframe with 3 columns:

df:

x       y      z
334     290    3350.0
334     291    3350.5
334     292    3360.1
335     292    3360.1
335     292    3360.1
335     290    3351.0
335     290    3352.5
335     291    3333.1
335     291    3333.1
.
.

I'd like to check and parse values of each row from row = n to row = n+7 into a new dataframe based on a couple of conditions:

df[n] != df[n+1]

df[n] != df[n+3]

df[n] != df[n+5]

df['x'][n] < df['x'][n+2]

df['x'][n] > df['x'][n+3]

If all of these are satisfied I want to write a new dataframe:

df_new = pd.concat([df[n], df[n+1], df[n+2], df[n+3],
df[n+4], df[n+5], df[n+6], df[n+7]])

So the algorithm + output would look like:

for df[n] = 0:
1) [334     290    3350.0] != [334     291    3350.5]  True
2) [334     290    3350.0] != [335     292    3360.1]  True
3) [334     290    3350.0] != [335     290    3351.0]  True
4) 335 < 334  False
5) 335 > 335  False

So in this case it would skip the first iteration until we've gone down the entire length of the dataframe and made matches.

df_new(first iteration) = df_new.concat([....]) = empty row values

Is there an easy way to do this with speed in Pandas?

Body:
A. Get the appropriate shifts:

    n1 = df.shift(-1)
    n2 = df.shift(-2)
    n3 = df.shift(-3)
    n5 = df.shift(-5)

B. Satisfy conditions 1, 2 and 3:

cond = (df != n1) & (df != n3) & (df != n5)

C. Satisfy conditions 4, 5:

 cond['holder'] = (df.x < n2.x) & (df.x < n3.x)

D. Get bool series (we want any row with all 'True'):

boolidx = cond.all(axis=1)

E. Use to get result:

df.loc[boolidx]


问:
PHPUnit: Expected status code 200 but received 419 with Laravel
I want to test the delete method but I am not getting the expected results from PHPUnit. I receive this message when running the test:

```<code> Expected status code 200 but received 419. Failed asserting that false is true.
 /vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:77
 /tests/Unit/CategoriesControllerTest.php:70
</code>```

Laravel version: 5.5

Thank you for any help!

Controller constructor:

```<code>public function __construct()
{
    $this->middleware('auth');

    $this->middleware('categoryAccess')->except([
        'index',
        'create'
    ]);
}
</code>```

Controller method:

```<code>public function destroy($categoryId)
{
    Category::destroy($categoryId);

    session()->flash('alert-success', 'Category was successfully deleted.');

    return redirect()->action('CategoriesController@index');
}
</code>```

categoryAccess middleware:

```<code>public function handle($request, Closure $next)
{
    $category = Category::find($request->id);

    if (!($category->user_id == Auth::id())) {
        abort(404);
    }

    return $next($request);
}
</code>```

Category model:

```<code>protected $dispatchesEvents = [
    'deleted' => CategoryDeleted::class,
];
</code>```

Event listener

```<code>public function handle(ExpensesUpdated $event)
{
    $category_id = $event->expense->category_id;

    if (Category::find($category_id)) {
        $costs = Category::find($category_id)->expense->sum('cost');

        $category = Category::find($category_id);

        $category->total = $costs;

        $category->save();
    }
}
</code>```

PHPUnit delete test:

```<code>use RefreshDatabase;

protected $user;

public function setUp()
{
   parent::setUp();
   $this->user = factory(User::class)->create();
   $this->actingAs($this->user);
}

/** @test */
public function user_can_destroy()
{
    $category = factory(Category::class)->create([
        'user_id' => $this->user->id
    ]);

    $response = $this->delete('/category/' . $category->id);

    $response->assertStatus(200);

    $response->assertViewIs('category.index');
}
</code>```

答:
The message here is indeed related to the CSRF middleware. But there is a much better way of attacking this problem than disabling the middleware.

The middleware comes with code built-in that detects if it is being used in a test. This check looks for 2 things:

Am I being ran via a command line

Am I being ran in an environment type of testing

Default, proper setup of the software correctly causes both flags to be true when running PHP unit. However, the most likely culprit is the value in your APP_ENV. Common ways for this to to be incorrect include:

Misconfigured phpunit.xml file. It should contain <server name="APP_ENV" value="testing" />

A shell session that has an explicit value set in APP_ENV that overrides this value

A Docker/docker-compose/kubernetes session that has an explicit value set in APP_ENV. Seeing about getting this value set via the .env and/or phpunit.xml files is perhaps better if possible. Or ensuring the build/test process sets the value.

This one stumped me as well and I was not convinced that I would need the use of WithoutMiddleware since I did not for a different project, but it turned out I had experimented with something on the command line and overrode APP_ENV in bash.

ContentLicense: CC BY-SA 3.0

Body:
I want to test the delete method but I am not getting the expected results from PHPUnit. I receive this message when running the test:

 Expected status code 200 but received 419. Failed asserting that false is true.
 /vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:77
 /tests/Unit/CategoriesControllerTest.php:70

Laravel version: 5.5

Thank you for any help!

Controller constructor:

public function __construct()
{
    $this->middleware('auth');

    $this->middleware('categoryAccess')->except([
        'index',
        'create'
    ]);
}

Controller method:

public function destroy($categoryId)
{
    Category::destroy($categoryId);

    session()->flash('alert-success', 'Category was successfully deleted.');

    return redirect()->action('CategoriesController@index');
}

categoryAccess middleware:

public function handle($request, Closure $next)
{
    $category = Category::find($request->id);

    if (!($category->user_id == Auth::id())) {
        abort(404);
    }

    return $next($request);
}

Category model:

protected $dispatchesEvents = [
    'deleted' => CategoryDeleted::class,
];

Event listener

public function handle(ExpensesUpdated $event)
{
    $category_id = $event->expense->category_id;

    if (Category::find($category_id)) {
        $costs = Category::find($category_id)->expense->sum('cost');

        $category = Category::find($category_id);

        $category->total = $costs;

        $category->save();
    }
}

PHPUnit delete test:

use RefreshDatabase;

protected $user;

public function setUp()
{
   parent::setUp();
   $this->user = factory(User::class)->create();
   $this->actingAs($this->user);
}

/** @test */
public function user_can_destroy()
{
    $category = factory(Category::class)->create([
        'user_id' => $this->user->id
    ]);

    $response = $this->delete('/category/' . $category->id);

    $response->assertStatus(200);

    $response->assertViewIs('category.index');
}


问:
How to use javascript with php to obtain large content from mysql
i have combined javascript with php as shown in this code below. but is not working for me.
it doesn't display the content. but it display the id when is requested.</p>

```<code>function content24(){
          document.getElementById("dailypost_content").innerHTML = '<?php
          $query = "SELECT`dpost_content` FROM `daily_POST` WHERE `id`=
                   '24'";
          $query_run = mysqli_query($host_connection, $query);
          $query_row = mysqli_fetch_assoc($query_run);
          $content = $query_row['dpost_content'];
          echo '<span id "daily_caption"> <strong><u>Daily Inspiration</u>
          </strong><br></span>';
          echo $content;
          ?>';
    }
</code>```

答: During a single HTTP request, the PHP is executed first on the server side, and then the javascript is executed on the client side. Therefore PHP can generated Javascript, but Javascript cannot generate PHP.</p>

Body:
i have combined javascript with php as shown in this code below. but is not working for me.
it doesn't display the content. but it display the id when is requested.

function content24(){
          document.getElementById("dailypost_content").innerHTML = '<?php
          $query = "SELECT`dpost_content` FROM `daily_POST` WHERE `id`=
                   '24'";
          $query_run = mysqli_query($host_connection, $query);
          $query_row = mysqli_fetch_assoc($query_run);
          $content = $query_row['dpost_content'];
          echo ' Daily Inspiration

';
          echo $content;
          ?>';
    }


问:
How to include SFML source code into my visual studio 2017 c++ project and compile
I have been programming a game in c++ using the sfml library. However, I would like to adjust some of the code of that library, and use that altered code in my project.

So instead of linking the dll I would like to add the source code and then play with that source code. (e.g. for speed optimization).

I know that doing something like that is generally speaking a bad idea. Howeover, I want to learn by playing around a bit and trying different things.

So how would I add the sfml source code to my c++ project in MS visual studio. Note that I am a total noob. I already tried adding the sfml folder that I downloaded from git in the project properties page called "Additional Include Directories", but i am getting errors, of the form "Cannot open include file: 'SFML/Graphics/GLCheck.hpp': No such file or directory" so I guess that i have not yet done enough.

答:
If you want to modify the source code in the library, all you'd have to do is just navigate to where you have SFML installed and go into the code files with a text editor and edit them.

Then, you could link the library to your VS project the same way you would normally but that library is now modified by you.

Seeing as you have a search directory issue already in VS, you must fix that first. Fix that and then go and modify the library's .hpp, .h, .cpp, whatever files in-place.

To fix the search issue.... I don't use VS for graphics, I use CodeBlocks so I am not sure about their GUI to link libraries and change search directories... but, find out where you installed SFML. Check your /usr/include/, it's probably there. Specify that path in the search directories. Just go and find where that GLCheck.hpp file is located. For Example: Say it's full path is /usr/include/SFML/Graphics/GLCheck.hpp... then /usr/include/SFML/Graphics/ or just /usr/include/ (VS might handle it recursively) needs to be in the list of SEARCH DIRECTORIES.


问:
Why doesn't this attribute data get loaded to the vertex shader correctly?
I want add an array of integers to my vertex array object, to define, which image should be used for that specific vertex, but somehow, the data is getting corrupted on the way or isn't loaded correctly.

I've already tried loading a preset array and just selecting the correct index using the gl_VertexID, which worked, but I would prefer having all the data in the vertex array and not having to load a uniform integer array each frame.

The vertex shader

```<code>#version 330 core

layout (location = 0) in vec4 position;
layout (location = 1) in vec2 textureCoordinate;
//layout (location = 2) in vec3 normals;
layout (location = 3) in int textureIndex;
//layout (location = 4) in mat4 modelMatrix;

// ---------------Temporary--------------
uniform mat4 view;
uniform mat4 model;
// ---------------Temporary end----------

flat out int textureIndexOut;

out DATA {
    vec2 tc;
} vs_out;

void main() {
    mat4 mvp = view * model;
    gl_Position = mvp * position;
    vs_out.tc = textureCoordinate;
    textureIndexOut = textureIndex;
}
</code>```

The fragment shader

```<code>#version 330 core

layout (location = 0) out vec4 color;

flat in int textureIndexOut;

in DATA {
    vec2 tc;
} fs_in;

uniform sampler2D textureSamplers[32];

void main() {
    color = texture(textureSamplers[1], fs_in.tc);
}
</code>```

Creating a vertex array`

```<code>public static VertexArray createVAO(float[] vertices, int[] indices, float[] textureCoordinates,
            float[] normals, int[]textureIndices) {
        int count = indices.length;
        int indexBufferObject = createIndexBuffer(indices);
        int vertexArrayObject = laodVertexArrayObject();
        storeDataInAttributeList(ShaderProgram.VERTEX_ATTRIB, vertices, 3);
        storeDataInAttributeList(ShaderProgram.TEXTURECOORDINATE_ATTRIB, textureCoordinates, 2);
        storeDataInAttributeList(ShaderProgram.TEXTURE_INDEX_ATTRIB, textureIndices, 1);
        return new VertexArray(count, vertexArrayObject, indexBufferObject, indices, vertices, normals, textureCoordinates);
    }
</code>```

Creating a VAO

```<code>private static int laodVertexArrayObject() {
        int vertexArrayObjectID = glGenVertexArrays();
        vaos.add(vertexArrayObjectID);                                                          //Adding the VAO to the list of all VAOs
        glBindVertexArray(vertexArrayObjectID);
        return vertexArrayObjectID;
    }
</code>```

Creating a VBO

```<code>private static int createIndexBuffer(int[] indices) {
        int indexBufferObjectID = glGenBuffers();
        ibos.add(indexBufferObjectID);                                                          //Adding the IBO to the list of all IBOs
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectID);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createIntBuffer(indices), GL_STATIC_DRAW);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        return indexBufferObjectID;
    }
</code>```

The storeDataInAttributeList function

```<code>private static void storeDataInAttributeList(int attributeNumber, float[] data, int coordinateSize) {
        int vertexBufferObjectID = glGenBuffers();
        vbos.add(vertexBufferObjectID);                                                         //Adding the VBO to the list of all VBOs
        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjectID);
        glBufferData(GL_ARRAY_BUFFER, BufferUtils.createFloatBuffer(data), GL_STATIC_DRAW);
        glVertexAttribPointer(attributeNumber, coordinateSize, GL_FLOAT, false, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

private static void storeDataInAttributeList(int attributeNumber, int[] data, int coordinateSize) {
        int vertexBufferObjectID = glGenBuffers();
        vbos.add(vertexBufferObjectID);                                                         //Adding the VBO to the list of all VBOs
        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjectID);
        glBufferData(GL_ARRAY_BUFFER, BufferUtils.createIntBuffer(data), GL_STATIC_DRAW);
        glVertexAttribPointer(attributeNumber, coordinateSize, GL_INT, false, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }
</code>```

Rendering a batch

```<code>public void render() {
        // Final arrays
        float[] vertices = null;
        float[] textureCoordinates = null;
        float[] normals = null;
        int[] indices = null;
        int[] textureIndices = null;
        // The temporary array list of data
        ArrayList<Float> rawVertices = new ArrayList<Float>();
        ArrayList<Float> rawTextureCoordinates = new ArrayList<Float>();
        ArrayList<Float> rawNormals = new ArrayList<Float>();
        ArrayList<Integer> rawIndices = new ArrayList<Integer>();
        ArrayList<Integer> rawTextureIndices = new ArrayList<Integer>();
        // Adding all the data of all the vaos into the temporary array lists
        for(int j = 0; j < rawVAOs.size(); j++) {
            for(int i = 0; i < rawVAOs.get(j).getVertices().length; i++) {
                rawVertices.add(rawVAOs.get(j).getVertices()[i]);
            }
            for(int i = 0; i < rawVAOs.get(j).getIndices().length; i++) {
                if(j == 0) {
                    rawIndices.add(rawVAOs.get(j).getIndices()[i]);
                } else {
                    rawIndices.add(j*rawVAOs.get(j-1).getIndices().length + rawVAOs.get(j).getIndices()[i]);
                }
            }
            for(int i = 0; i < rawVAOs.get(j).getNormals().length; i++) {
                rawNormals.add(rawVAOs.get(j).getNormals()[i]);
            }
            for(int i = 0; i < rawVAOs.get(j).getTextureCoordinates().length; i++) {
                rawTextureCoordinates.add(rawVAOs.get(j).getTextureCoordinates()[i]);
            }
            for(int i = 0; i < rawVAOs.get(j).getTextureIndices().length; i++) {
                rawTextureIndices.add(rawVAOs.get(j).getTextureIndices()[i]);
            }
        }
        // Adding all the data from the temporaray array lists into the final arrays
        vertices = new float[rawVertices.size()];
        for(int i = 0; i < rawVertices.size(); i++) {
            vertices[i] = rawVertices.get(i);
        }
        indices = new int[rawIndices.size()];
        for(int i = 0; i < rawIndices.size(); i++) {
            indices[i] = rawIndices.get(i);
        }
        normals = new float[rawNormals.size()];
        for(int i = 0; i < rawNormals.size(); i++) {
            normals[i] = rawNormals.get(i);
        }
        textureCoordinates = new float[rawTextureCoordinates.size()];
        for(int i = 0; i < rawTextureCoordinates.size(); i++) {
            textureCoordinates[i] = rawTextureCoordinates.get(i);
        }
        textureIndices = new int[rawTextureIndices.size()];
        for(int i = 0; i < rawTextureIndices.size(); i++) {
            textureIndices[i] = rawTextureIndices.get(i);
        }
        // Creating the final vao and rendering it
        this.finalVAO = Loader.createVAO(vertices, indices, textureCoordinates, normals, textureIndices);
        Main.ShaderList.get(shaderIndex).prepare();
        //load transformation matrices
        for(int i = 0; i < texturePointers.size(); i++) {
            glActiveTexture(GL_TEXTURE0+i);
            Main.TextureBufferPointerList.get(texturePointers.get(i)).bind();
        }
        this.finalVAO.render();
        Main.ShaderList.get(shaderIndex).finish();
    }
</code>```

If I load up an integer array consisting of 0 for all the vertices of the first object and 1 for the all the vertices of the second object, i would expect the first object to be shaded in with the first texture and the second object to be shaded in with the second texture. It works if I add 0 for both objects, but once I add 1 for the any object, I get this giant error message:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffee7914d6e, pid=5992, tid=0x00000000000006bc
#
# JRE version: Java(TM) SE Runtime Environment (8.0_211-b12) (build 1.8.0_211-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.211-b12 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [ig9icd64.dll+0x24d6e]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x000000001f03c800):  JavaThread "renderer" [_thread_in_native, id=1724, stack(0x0000000020990000,0x0000000020a90000)]

siginfo: ExceptionCode=0xc0000005, reading address 0x0000000000000220

Registers:
RAX=0x0000000024f20080, RBX=0x00000000013ae000, RCX=0x00000000013ae000, RDX=0x000000002d611b10
RSP=0x0000000020a8ebb0, RBP=0x000000002d611a50, RSI=0x0000000000000000, RDI=0x0000000024f20080
R8 =0x0000000001221bc0, R9 =0x0000000000008000, R10=0x00000000ffffffff, R11=0x0000000000000000
R12=0x0000000000000000, R13=0x000000001ca43bd0, R14=0x0000000025042310, R15=0x0000000000000000
RIP=0x00007ffee7914d6e, EFLAGS=0x0000000000010246

Top of Stack: (sp=0x0000000020a8ebb0)
0x0000000020a8ebb0:   0000000000000001 0000000001387e50
0x0000000020a8ebc0:   00000000228e5360 00007ffee7a6171f
0x0000000020a8ebd0:   fffffffffffffffe 000000001ca43bd0
0x0000000020a8ebe0:   000000000137ff20 00007ffee79145cf
0x0000000020a8ebf0:   0000000001394720 0000000000000000
0x0000000020a8ec00:   00000000013ae000 000000002d611a50
0x0000000020a8ec10:   000000000000000e 00007ffee7e35300
0x0000000020a8ec20:   0000000000000000 0000000025042310
0x0000000020a8ec30:   0000000024f20080 00007ffee790b731
0x0000000020a8ec40:   0000000001394720 00000000ffffffff
0x0000000020a8ec50:   0000000000000000 00000000ffffffff
0x0000000020a8ec60:   000000000137ff20 00007ffee7b0f4e2
0x0000000020a8ec70:   0000000000000000 00000000ffffffff
0x0000000020a8ec80:   0000000024f20080 000000000137ff20
0x0000000020a8ec90:   fffffffffffffffe 0000000025042310
0x0000000020a8eca0:   0000000000000000 0000000025042310

Instructions: (pc=0x00007ffee7914d6e)
0x00007ffee7914d4e:   02 00 00 83 e6 01 0f 1f 40 00 0f 1f 84 00 00 00
0x00007ffee7914d5e:   00 00 4c 8b 9f 70 42 03 00 48 8d 95 c0 00 00 00
0x00007ffee7914d6e:   41 8b 8b 20 02 00 00 85 f6 0f 84 81 00 00 00 83
0x00007ffee7914d7e:   f9 10 73 06 48 6b c1 38 eb 5b 44 8d 41 f0 41 8b

Register to memory mapping:

RAX=0x0000000024f20080 is an unknown value
RBX=0x00000000013ae000 is an unknown value
RCX=0x00000000013ae000 is an unknown value
RDX=0x000000002d611b10 is an unknown value
RSP=0x0000000020a8ebb0 is pointing into the stack for thread: 0x000000001f03c800
RBP=0x000000002d611a50 is an unknown value
RSI=0x0000000000000000 is an unknown value
RDI=0x0000000024f20080 is an unknown value
R8 =0x0000000001221bc0 is an unknown value
R9 =0x0000000000008000 is an unknown value
R10=0x00000000ffffffff is an unknown value
R11=0x0000000000000000 is an unknown value
R12=0x0000000000000000 is an unknown value
R13={method} {0x000000001ca43bd8} 'invokeV' '(J)V' in 'org/lwjgl/system/JNI'
R14=0x0000000025042310 is an unknown value
R15=0x0000000000000000 is an unknown value

Stack: [0x0000000020990000,0x0000000020a90000],  sp=0x0000000020a8ebb0,  free space=1018k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [ig9icd64.dll+0x24d6e]
C  [ig9icd64.dll+0x245cf]
C
</code>```

答:
Integral attributes have to be specified by glVertexAttribIPointer - focus on I:

glVertexAttribIPointer(attributeNumber, coordinateSize, GL_INT, 0, 0);
```

<p>See OpenGL 4.6 API Core Profile Specification; 10.2.1 Current Generic Attributes
, page 349:  </p>

<blockquote>
  <p>When values for a vertex shader attribute variable are sourced from an enabled generic vertex attribute array,
  the array must be specified by a command compatible with the data type of the variable.
  The values loaded into a shader attribute variable bound to generic attribute index are undefined if the array for index was not specified by:</p>

  <ul>
  <li><code>VertexAttribFormat</code>, for floating-point base type attributes;</li>
  <li><strong><code>VertexAttribIFormat</code> with type <code>BYTE</code>, <code>SHORT</code>, or <code>INT</code> for signed integer base type attributes;</strong> or</li>
  <li><code>VertexAttribIFormat</code> with type <code>UNSIGNED_BYTE</code>, <code>UNSIGNED_SHORT</code>, or <code>UNSIGNED_INT</code> for unsigned integer base type attributes.</li>
  </ul>
</blockquote>

<hr>

<p>Further note that the Index buffer is stated in the Vertex Array Object. If no Vertex Array Object is bound, then no index buffer can be bound. (In a compatibility profile context there is the default vertex array object 0).  </p>

<p>So the vertex array object has to be created and bound before the index buffer.  </p>

<pre class="lang-java prettyprint-override"><code>int vertexArrayObject = laodVertexArrayObject();
int count = indices.length;
int indexBufferObject = createIndexBuffer(indices);
</code>```

Of course the association to the VAO must not be broken by glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);:

private static int createIndexBuffer(int[] indices) {
    int indexBufferObjectID = glGenBuffers();
    ibos.add(indexBufferObjectID);
    //Adding the IBO to the list of all IBOs
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createIntBuffer(indices), GL_STATIC_DRAW);

    // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); <----- delete

    return indexBufferObjectID;
}
```

Body:
I want add an array of integers to my vertex array object, to define, which image should be used for that specific vertex, but somehow, the data is getting corrupted on the way or isn't loaded correctly.

I've already tried loading a preset array and just selecting the correct index using the gl_VertexID, which worked, but I would prefer having all the data in the vertex array and not having to load a uniform integer array each frame.

The vertex shader

#version 330 core

layout (location = 0) in vec4 position;
layout (location = 1) in vec2 textureCoordinate;
//layout (location = 2) in vec3 normals;
layout (location = 3) in int textureIndex;
//layout (location = 4) in mat4 modelMatrix;

// ---------------Temporary--------------
uniform mat4 view;
uniform mat4 model;
// ---------------Temporary end----------

flat out int textureIndexOut;

out DATA {
    vec2 tc;
} vs_out;

void main() {
    mat4 mvp = view * model;
    gl_Position = mvp * position;
    vs_out.tc = textureCoordinate;
    textureIndexOut = textureIndex;
}

The fragment shader

#version 330 core

layout (location = 0) out vec4 color;

flat in int textureIndexOut;

in DATA {
    vec2 tc;
} fs_in;

uniform sampler2D textureSamplers[32];

void main() {
    color = texture(textureSamplers[1], fs_in.tc);
}

Creating a vertex array`

public static VertexArray createVAO(float[] vertices, int[] indices, float[] textureCoordinates,
            float[] normals, int[]textureIndices) {
        int count = indices.length;
        int indexBufferObject = createIndexBuffer(indices);
        int vertexArrayObject = laodVertexArrayObject();
        storeDataInAttributeList(ShaderProgram.VERTEX_ATTRIB, vertices, 3);
        storeDataInAttributeList(ShaderProgram.TEXTURECOORDINATE_ATTRIB, textureCoordinates, 2);
        storeDataInAttributeList(ShaderProgram.TEXTURE_INDEX_ATTRIB, textureIndices, 1);
        return new VertexArray(count, vertexArrayObject, indexBufferObject, indices, vertices, normals, textureCoordinates);
    }

Creating a VAO

private static int laodVertexArrayObject() {
        int vertexArrayObjectID = glGenVertexArrays();
        vaos.add(vertexArrayObjectID);                                                          //Adding the VAO to the list of all VAOs
        glBindVertexArray(vertexArrayObjectID);
        return vertexArrayObjectID;
    }

Creating a VBO

private static int createIndexBuffer(int[] indices) {
        int indexBufferObjectID = glGenBuffers();
        ibos.add(indexBufferObjectID);                                                          //Adding the IBO to the list of all IBOs
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectID);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createIntBuffer(indices), GL_STATIC_DRAW);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        return indexBufferObjectID;
    }

The storeDataInAttributeList function

private static void storeDataInAttributeList(int attributeNumber, float[] data, int coordinateSize) {
        int vertexBufferObjectID = glGenBuffers();
        vbos.add(vertexBufferObjectID);                                                         //Adding the VBO to the list of all VBOs
        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjectID);
        glBufferData(GL_ARRAY_BUFFER, BufferUtils.createFloatBuffer(data), GL_STATIC_DRAW);
        glVertexAttribPointer(attributeNumber, coordinateSize, GL_FLOAT, false, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

private static void storeDataInAttributeList(int attributeNumber, int[] data, int coordinateSize) {
        int vertexBufferObjectID = glGenBuffers();
        vbos.add(vertexBufferObjectID);                                                         //Adding the VBO to the list of all VBOs
        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjectID);
        glBufferData(GL_ARRAY_BUFFER, BufferUtils.createIntBuffer(data), GL_STATIC_DRAW);
        glVertexAttribPointer(attributeNumber, coordinateSize, GL_INT, false, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

Rendering a batch

public void render() {
        // Final arrays
        float[] vertices = null;
        float[] textureCoordinates = null;
        float[] normals = null;
        int[] indices = null;
        int[] textureIndices = null;
        // The temporary array list of data
        ArrayList<Float> rawVertices = new ArrayList<Float>();
        ArrayList<Float> rawTextureCoordinates = new ArrayList<Float>();
        ArrayList<Float> rawNormals = new ArrayList<Float>();
        ArrayList<Integer> rawIndices = new ArrayList<Integer>();
        ArrayList<Integer> rawTextureIndices = new ArrayList<Integer>();
        // Adding all the data of all the vaos into the temporary array lists
        for(int j = 0; j < rawVAOs.size(); j++) {
            for(int i = 0; i < rawVAOs.get(j).getVertices().length; i++) {
                rawVertices.add(rawVAOs.get(j).getVertices()[i]);
            }
            for(int i = 0; i < rawVAOs.get(j).getIndices().length; i++) {
                if(j == 0) {
                    rawIndices.add(rawVAOs.get(j).getIndices()[i]);
                } else {
                    rawIndices.add(j*rawVAOs.get(j-1).getIndices().length + rawVAOs.get(j).getIndices()[i]);
                }
            }
            for(int i = 0; i < rawVAOs.get(j).getNormals().length; i++) {
                rawNormals.add(rawVAOs.get(j).getNormals()[i]);
            }
            for(int i = 0; i < rawVAOs.get(j).getTextureCoordinates().length; i++) {
                rawTextureCoordinates.add(rawVAOs.get(j).getTextureCoordinates()[i]);
            }
            for(int i = 0; i < rawVAOs.get(j).getTextureIndices().length; i++) {
                rawTextureIndices.add(rawVAOs.get(j).getTextureIndices()[i]);
            }
        }
        // Adding all the data from the temporaray array lists into the final arrays
        vertices = new float[rawVertices.size()];
        for(int i = 0; i < rawVertices.size(); i++) {
            vertices[i] = rawVertices.get(i);
        }
        indices = new int[rawIndices.size()];
        for(int i = 0; i < rawIndices.size(); i++) {
            indices[i] = rawIndices.get(i);
        }
        normals = new float[rawNormals.size()];
        for(int i = 0; i < rawNormals.size(); i++) {
            normals[i] = rawNormals.get(i);
        }
        textureCoordinates = new float[rawTextureCoordinates.size()];
        for(int i = 0; i < rawTextureCoordinates.size(); i++) {
            textureCoordinates[i] = rawTextureCoordinates.get(i);
        }
        textureIndices = new int[rawTextureIndices.size()];
        for(int i = 0; i < rawTextureIndices.size(); i++) {
            textureIndices[i] = rawTextureIndices.get(i);
        }
        // Creating the final vao and rendering it
        this.finalVAO = Loader.createVAO(vertices, indices, textureCoordinates, normals, textureIndices);
        Main.ShaderList.get(shaderIndex).prepare();
        //load transformation matrices
        for(int i = 0; i < texturePointers.size(); i++) {
            glActiveTexture(GL_TEXTURE0+i);
            Main.TextureBufferPointerList.get(texturePointers.get(i)).bind();
        }
        this.finalVAO.render();
        Main.ShaderList.get(shaderIndex).finish();
    }

If I load up an integer array consisting of 0 for all the vertices of the first object and 1 for the all the vertices of the second object, i would expect the first object to be shaded in with the first texture and the second object to be shaded in with the second texture. It works if I add 0 for both objects, but once I add 1 for the any object, I get this giant error message:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffee7914d6e, pid=5992, tid=0x00000000000006bc
#
# JRE version: Java(TM) SE Runtime Environment (8.0_211-b12) (build 1.8.0_211-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.211-b12 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [ig9icd64.dll+0x24d6e]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x000000001f03c800):  JavaThread "renderer" [_thread_in_native, id=1724, stack(0x0000000020990000,0x0000000020a90000)]

siginfo: ExceptionCode=0xc0000005, reading address 0x0000000000000220

Registers:
RAX=0x0000000024f20080, RBX=0x00000000013ae000, RCX=0x00000000013ae000, RDX=0x000000002d611b10
RSP=0x0000000020a8ebb0, RBP=0x000000002d611a50, RSI=0x0000000000000000, RDI=0x0000000024f20080
R8 =0x0000000001221bc0, R9 =0x0000000000008000, R10=0x00000000ffffffff, R11=0x0000000000000000
R12=0x0000000000000000, R13=0x000000001ca43bd0, R14=0x0000000025042310, R15=0x0000000000000000
RIP=0x00007ffee7914d6e, EFLAGS=0x0000000000010246

Top of Stack: (sp=0x0000000020a8ebb0)
0x0000000020a8ebb0:   0000000000000001 0000000001387e50
0x0000000020a8ebc0:   00000000228e5360 00007ffee7a6171f
0x0000000020a8ebd0:   fffffffffffffffe 000000001ca43bd0
0x0000000020a8ebe0:   000000000137ff20 00007ffee79145cf
0x0000000020a8ebf0:   0000000001394720 0000000000000000
0x0000000020a8ec00:   00000000013ae000 000000002d611a50
0x0000000020a8ec10:   000000000000000e 00007ffee7e35300
0x0000000020a8ec20:   0000000000000000 0000000025042310
0x0000000020a8ec30:   0000000024f20080 00007ffee790b731
0x0000000020a8ec40:   0000000001394720 00000000ffffffff
0x0000000020a8ec50:   0000000000000000 00000000ffffffff
0x0000000020a8ec60:   000000000137ff20 00007ffee7b0f4e2
0x0000000020a8ec70:   0000000000000000 00000000ffffffff
0x0000000020a8ec80:   0000000024f20080 000000000137ff20
0x0000000020a8ec90:   fffffffffffffffe 0000000025042310
0x0000000020a8eca0:   0000000000000000 0000000025042310

Instructions: (pc=0x00007ffee7914d6e)
0x00007ffee7914d4e:   02 00 00 83 e6 01 0f 1f 40 00 0f 1f 84 00 00 00
0x00007ffee7914d5e:   00 00 4c 8b 9f 70 42 03 00 48 8d 95 c0 00 00 00
0x00007ffee7914d6e:   41 8b 8b 20 02 00 00 85 f6 0f 84 81 00 00 00 83
0x00007ffee7914d7e:   f9 10 73 06 48 6b c1 38 eb 5b 44 8d 41 f0 41 8b

Register to memory mapping:

RAX=0x0000000024f20080 is an unknown value
RBX=0x00000000013ae000 is an unknown value
RCX=0x00000000013ae000 is an unknown value
RDX=0x000000002d611b10 is an unknown value
RSP=0x0000000020a8ebb0 is pointing into the stack for thread: 0x000000001f03c800
RBP=0x000000002d611a50 is an unknown value
RSI=0x0000000000000000 is an unknown value
RDI=0x0000000024f20080 is an unknown value
R8 =0x0000000001221bc0 is an unknown value
R9 =0x0000000000008000 is an unknown value
R10=0x00000000ffffffff is an unknown value
R11=0x0000000000000000 is an unknown value
R12=0x0000000000000000 is an unknown value
R13={method} {0x000000001ca43bd8} 'invokeV' '(J)V' in 'org/lwjgl/system/JNI'
R14=0x0000000025042310 is an unknown value
R15=0x0000000000000000 is an unknown value

Stack: [0x0000000020990000,0x0000000020a90000],  sp=0x0000000020a8ebb0,  free space=1018k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [ig9icd64.dll+0x24d6e]
C  [ig9icd64.dll+0x245cf]
C

Body:
Integral attributes have to be specified by glVertexAttribIPointer - focus on I:

glVertexAttribIPointer(attributeNumber, coordinateSize, GL_INT, 0, 0);

See OpenGL 4.6 API Core Profile Specification; 10.2.1 Current Generic Attributes
, page 349:

When values for a vertex shader attribute variable are sourced from an enabled generic vertex attribute array,
  the array must be specified by a command compatible with the data type of the variable.
  The values loaded into a shader attribute variable bound to generic attribute index are undefined if the array for index was not specified by:

VertexAttribFormat, for floating-point base type attributes;

VertexAttribIFormat with type BYTE, SHORT, or INT for signed integer base type attributes; or

VertexAttribIFormat with type UNSIGNED_BYTE, UNSIGNED_SHORT, or UNSIGNED_INT for unsigned integer base type attributes.

Further note that the Index buffer is stated in the Vertex Array Object. If no Vertex Array Object is bound, then no index buffer can be bound. (In a compatibility profile context there is the default vertex array object 0).

So the vertex array object has to be created and bound before the index buffer.

int vertexArrayObject = laodVertexArrayObject();
int count = indices.length;
int indexBufferObject = createIndexBuffer(indices);

Of course the association to the VAO must not be broken by glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);:

private static int createIndexBuffer(int[] indices) {
    int indexBufferObjectID = glGenBuffers();
    ibos.add(indexBufferObjectID);
    //Adding the IBO to the list of all IBOs
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObjectID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createIntBuffer(indices), GL_STATIC_DRAW);

    // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); <----- delete

    return indexBufferObjectID;
}


问:
pymongo - Message length is larger than server max message size
the line for doc in collection.find({'is_timeline_valid': True}): is giving the Message Length error. How can I get all the collection without the error? I know about the find().limit() but I don't know how to use it.

Code:

```<code>from openpyxl import load_workbook
import pymongo
import os

wb = load_workbook('concilia.xlsx')
ws = wb.active
client = pymongo.MongoClient('...')
db = client['...']
collection = db['...']

r = 2
for doc in collection.find({'is_timeline_valid': True}):
   for dic in doc['timeline']['datas']:
     if 'concilia' in dic['tramite'].lower():
        ws.cell(row = r, column = 1).value = doc['id_process_unformatted']
        ws.cell(row = r, column = 2).value = dic['data']
        ws.cell(row = r, column = 3).value = dic['tramite']
        wb.save('concilia.xlsx')
        print('*****************************')
        print(dic['tramite'])
        # print('check!')
        r += 1
</code>```

答:
I ran into this problem today, and it turns out it has to do with the size of a particular document within the collection exceeding the max_bson_size limit. When adding documents to the collection, make sure the document size doesn't exceed max_bson_size size.

```<code>document_size_limit = client.max_bson_size
assert len(json.dumps(data)) < document_size_limit
</code>```

I'm currently investigating why the collection allowed a document larger than max_bson_size in the first place.

Body:
the line for doc in collection.find({'is_timeline_valid': True}): is giving the Message Length error. How can I get all the collection without the error? I know about the find().limit() but I don't know how to use it.

Code:

from openpyxl import load_workbook
import pymongo
import os

wb = load_workbook('concilia.xlsx')
ws = wb.active
client = pymongo.MongoClient('...')
db = client['...']
collection = db['...']

r = 2
for doc in collection.find({'is_timeline_valid': True}):
   for dic in doc['timeline']['datas']:
     if 'concilia' in dic['tramite'].lower():
        ws.cell(row = r, column = 1).value = doc['id_process_unformatted']
        ws.cell(row = r, column = 2).value = dic['data']
        ws.cell(row = r, column = 3).value = dic['tramite']
        wb.save('concilia.xlsx')
        print('*****************************')
        print(dic['tramite'])
        # print('check!')
        r += 1

Body:
I ran into this problem today, and it turns out it has to do with the size of a particular document within the collection exceeding the max_bson_size limit. When adding documents to the collection, make sure the document size doesn't exceed max_bson_size size.

document_size_limit = client.max_bson_size
assert len(json.dumps(data)) < document_size_limit

I'm currently investigating why the collection allowed a document larger than max_bson_size in the first place.


问:
Rstudio show only the first 50 columns
I have a problem on RStudio in my data view, I can see only the first 50 columns for all dataframes. Is it possible to increase the number of view columns? </p>

答:
I do not believe you can increase the number of columns to view at a time.  But you can click the little arrow at the top to scroll across to more columns.

I'm using RStudio 1.2.1335 and not sure which version of RStudio first implemented this feature.

Title: Rstudio show only the first 50 columns


问:
Code for image manipulation produces no result/output
I am working on a project that where I am required to use classes and objects to manipulate an image in Python using PIL.

I have eliminated formatted the path to the file correctly so there must be something in the code itself.

```<code>class image_play(object):
    def __init__(self,im_name):
        self.im_name = im_name

    def rgb_to_gray_image(self):
        im = Image.open(self.im_name)
        im = im.convert('LA')
        return im

    # editing pixels of image to white
    def loop_over_image(self):
        im = Image.open(self.im_name)
        width, height = im.size
        # nested loop over all pixels of image
        temp = []
        for i in range(width):
          for j in range(height):
            temp.append((255,255,255)) # append tuple for the RGB values for each pixel

        image_out = Image.new(im.mode,im.size)  #create new image using PIl
        image_out.putdata(temp) #use the temp list to create the image
        return image_out

pic = image_play('test.png')

picGray = pic.rgb_to_gray_image()

picWhite = pic.loop_over_image()
</code>```

答: I simply added picGray.show() and picWhite.show() an now I have view-able output. Hmmmm...</p>

Body:
I am working on a project that where I am required to use classes and objects to manipulate an image in Python using PIL.

I have eliminated formatted the path to the file correctly so there must be something in the code itself.

class image_play(object):
    def __init__(self,im_name):
        self.im_name = im_name

    def rgb_to_gray_image(self):
        im = Image.open(self.im_name)
        im = im.convert('LA')
        return im

    # editing pixels of image to white
    def loop_over_image(self):
        im = Image.open(self.im_name)
        width, height = im.size
        # nested loop over all pixels of image
        temp = []
        for i in range(width):
          for j in range(height):
            temp.append((255,255,255)) # append tuple for the RGB values for each pixel

        image_out = Image.new(im.mode,im.size)  #create new image using PIl
        image_out.putdata(temp) #use the temp list to create the image
        return image_out

pic = image_play('test.png')

picGray = pic.rgb_to_gray_image()

picWhite = pic.loop_over_image()


问:
How to handle expiring refresh tokens in spring boot rest template client
I'm working on integrating a third party API in my spring boot application.

How the third party API authentication works:

After initial authorisation, I'm provided with refresh token and
access token that expires after a given time

After the access token expires I use the refresh token to get a new access token AND a new refresh token

With the current access token I can make calls to the API.

Is there a way to seamlessly handle such case using RestTemplate?

I've tried handling this case manually, so if I got 401 back from the API I sent a refresh token request, rewrote the keys I got back and retried the request, not really sure how to handle storing the api keys in case I need to restart the server.

答:
This is easily done with a ClientHttpRequestInterceptor in which you can replace a requests header if e.g. a 401 occured:

```<code>@Override
public ClientHttpResponse intercept(
  HttpRequest request,
  byte[] body,
  ClientHttpRequestExecution execution) throws IOException {

    ClientHttpResponse response = execution.execute(request, body);
    if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
       request.getHeaders().replace("Auth-Header", getNewToken());
       return execution.execute(request, body);
    }
    return response;
}
</code>```

See here for further guidance.

Body:
This is easily done with a ClientHttpRequestInterceptor in which you can replace a requests header if e.g. a 401 occured:

@Override
public ClientHttpResponse intercept(
  HttpRequest request,
  byte[] body,
  ClientHttpRequestExecution execution) throws IOException {

    ClientHttpResponse response = execution.execute(request, body);
    if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
       request.getHeaders().replace("Auth-Header", getNewToken());
       return execution.execute(request, body);
    }
    return response;
}

See here for further guidance.


问:
Are there any functions in MySQL like dense_rank() and row_number() like Oracle?
Are there any functions in MySQL like dense_rank() and row_number() like those provided by Oracle and other DBMS?

I want to generate an id within the query, but in MySQL these functions are not there. Is there an alternative?

答:
MySQL version 8 now has ROW_NUMBER.
Documentation

EXAMPLE:

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY s.Id) AS 'row_num',
    s.product,
    s.title
FROM supplies AS S
</code>```

Body:
MySQL version 8 now has ROW_NUMBER.
Documentation

EXAMPLE:

SELECT
    ROW_NUMBER() OVER (ORDER BY s.Id) AS 'row_num',
    s.product,
    s.title
FROM supplies AS S


问:
How to use telethon in a thread
I want to run a function in background. so I use Threading in my code.

but return error ValueError: signal only works in main thread and don't know about two things:

what is the main thread

how to solve this problem :)

views.py

```<code>def callback(update):
    print('I received', update)

def message_poll_start():
    try:
        client = TelegramClient('phone', api_id, api_hash,
            update_workers=1, spawn_read_thread=False)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass

def message_poll_start_thread(request):
    t = threading.Thread(target=message_poll_start, args=(), kwargs={})
    t.setDaemon(True)
    t.start()
    return HttpResponse("message polling started")
</code>```

urls.py

```<code>urlpatterns = [
    path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"),
]
</code>```

trace

```<code>[12/Jan/2018 11:24:38] "GET /messages/message_poll_start HTTP/1.1" 200 23
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/teletogram/telethogram/messagemanager/views.py", line 123, in message_poll_start
    client0.idle()
  File "/home/teletogram/.env/lib/python3.5/site-packages/telethon/telegram_bare_client.py", line 825, in idle
    signal(sig, self._signal_handler)
  File "/usr/lib/python3.5/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
</code>```

答:
1) A python script runs in the main thread by default. If you spawn a new thread using threading.Thread, that will create a new thread which runs separately from the main one. When I began learning about threading I spent a lot of time reading before it started to click. The official threading docs are decent for basic functionality, and I like this tutorial for a deeper dive.

2) The internals of Telethon rely on asyncio. In asyncio each thread needs its own asynchronous event loop, and thus spawned threads need an explicitly created event loop. Like threading, asyncio is a large topic, some of which is covered in the Telethon docs.

Something like this should work:

```<code>import asyncio
def message_poll_start():
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = TelegramClient('phone', api_id, api_hash, loop=loop)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass
</code>```

Title: How to use telethon in a thread

Body:
I want to run a function in background. so I use Threading in my code.

but return error ValueError: signal only works in main thread and don't know about two things:

what is the main thread

how to solve this problem :)

views.py

def callback(update):
    print('I received', update)

def message_poll_start():
    try:
        client = TelegramClient('phone', api_id, api_hash,
            update_workers=1, spawn_read_thread=False)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass

def message_poll_start_thread(request):
    t = threading.Thread(target=message_poll_start, args=(), kwargs={})
    t.setDaemon(True)
    t.start()
    return HttpResponse("message polling started")

urls.py

urlpatterns = [
    path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"),
]

trace

[12/Jan/2018 11:24:38] "GET /messages/message_poll_start HTTP/1.1" 200 23
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/teletogram/telethogram/messagemanager/views.py", line 123, in message_poll_start
    client0.idle()
  File "/home/teletogram/.env/lib/python3.5/site-packages/telethon/telegram_bare_client.py", line 825, in idle
    signal(sig, self._signal_handler)
  File "/usr/lib/python3.5/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

Body:
1) A python script runs in the main thread by default. If you spawn a new thread using threading.Thread, that will create a new thread which runs separately from the main one. When I began learning about threading I spent a lot of time reading before it started to click. The official threading docs are decent for basic functionality, and I like this tutorial for a deeper dive.

2) The internals of Telethon rely on asyncio. In asyncio each thread needs its own asynchronous event loop, and thus spawned threads need an explicitly created event loop. Like threading, asyncio is a large topic, some of which is covered in the Telethon docs.

Something like this should work:

import asyncio
def message_poll_start():
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = TelegramClient('phone', api_id, api_hash, loop=loop)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass


问:
Multiple Upload tool, script or plugin?

I'm trying to make an upload function in this website I'm working on, but till now no succes.

I tried using Plupload, but can't get it to work. Same goes for Uploadify, can't find any tutorial or good explanation in how to install these plugins in your webpage.

Does anybody know a good and easy to use multiple upload tool I can easily implement in the page?

Thanks in advance!

答:
I like to use this little thingy.

it is very easy to implement and works very well for me.

it uses the Dojo toolkit - i think you should check it out

Title: Multiple Upload tool, script or plugin?


问:
Why isn't this code executing the stored procedure and inserting data?
I have a controller listed here which should be calling the Dapper method, however I cannot get it to execute. It's not throwing any exceptions and it is redirecting under the try catch however the procedure doesn't seem to be running as no new users are ever created.

The connection set up works with simple inline .Query methods however as soon as I attempt to do this with a stored procedure, it fails.

Model:

    public class User
    {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Boolean ActiveB { get; set; }
    }
```

<p>View:</p>

```@model ScaleBase.Models.FullUser

@{
    ViewData["Title"] = "Create";
}

Create

User

        <form asp-action="Create">

                <input asp-for="OrganisationID" class="form-control" />

                <input asp-for="ClientID" class="form-control" />

                <input asp-for="TeamID" class="form-control" />

                <input asp-for="Email" class="form-control" />

                <input asp-for="Username" class="form-control" />

                <input asp-for="Password" type="password" class="form-control" />

                <input asp-for="FirstName" class="form-control" />

                <input asp-for="LastName" class="form-control" />

                        <input asp-for="ActiveB" /> @Html.DisplayNameFor(model => model.ActiveB)

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

```

<p>Controller:</p>

```public ActionResult Create(IFormCollection collection)
{
        try
        {
            DynamicParameters parameters = new DynamicParameters();

            parameters.Add("@Organisation", collection["OrganisationID"]);
            parameters.Add("@ClientID1", collection["ClientID"]);
            parameters.Add("@Team", collection["TeamID"]);
            parameters.Add("@Email", collection["Email"]);
            parameters.Add("@UserName", collection["UserName"]);
            parameters.Add("@Password", collection["Password"]);
            parameters.Add("@FirstName", collection["FirstName"]);
            parameters.Add("@LastName", collection["LastName"]);

            var affectedRows = _dapperRepo.CreateUser(parameters);

            return RedirectToAction(nameof(Index));
        }
        catch (Exception)
        {
            throw;
        }
    }
```

<p>Dapper repo:</p>

```    public async Task<User> CreateUser(DynamicParameters parameters)
    {
        using (IDbConnection conn = Connection)
        {
            string sproc = "EXEC sproc_NewUser @Organisation, @Client1, @Team, @Email  @UserName, @Password, @FirstName, @LastName";
            conn.Open();
            var result = await conn.QueryAsync(sproc, parameters, commandType: CommandType.StoredProcedure);
            return result.FirstOrDefault();
        }
    }
```

<p>Stored procedure:</p>

```BEGIN TRY
    BEGIN TRANSACTION NewUser
        DECLARE @salt UNIQUEIDENTIFIER = NEWID()

        INSERT INTO [dbo].[User] (Username, Email, FirstName, LastName, Password, Salt, Active)
        VALUES (@UserName, @Email, @FirstName, @LastName, HASHBYTES('SHA2_512', @Password+CAST(@salt AS NVARCHAR(36))), @salt, 1)

        INSERT INTO [dbo].[UserOrganisations] (UserID, OrganisationID)
        VALUES (IDENT_CURRENT('User'), @Organisation)

        INSERT INTO [dbo].[UserClients] (UserID, ClientID)
        VALUES (IDENT_CURRENT('User'), @Client1)

        IF @Client2 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client2)
        END

        IF @Client3 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client3)
        END

        IF @Client4 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client4)
        END

        IF @Client5 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client5)
        END

        INSERT INTO [dbo].[UserTeams] (UserID, TeamID)
        VALUES (IDENT_CURRENT('User'), @Team)

        INSERT INTO [dbo].[UserPermission] (UserID, HolidayCount, HolidayUsed, TemplateID, ConfigState1, ConfigState2, ConfigState3, ConfigState4, ConfigState5)
        VALUES (IDENT_CURRENT('User'), @Holiday, 0, 1, 255, null, null, null, null)

        INSERT INTO [dbo].[UserTime] (UserID, Scale, StartTime, EndTime)
        VALUES (IDENT_CURRENT('User'), 1, @StartTime, @EndTime)

        COMMIT TRANSACTION NewUser

        PRINT 'Success'

        SELECT
            [UserID], [Username], [Email], [Firstname], [Lastname], [Active]
        FROM
            [User]
        WHERE
            [UserID] = IDENT_CURRENT('User')
END TRY
BEGIN CATCH
    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRANSACTION NewUser
        PRINT 'Failed'
    END

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage

        RETURN 'Error'
END CATCH
```

答:
When using commandType: CommandType.StoredProcedure you only need to specify the stored procedure name - so instead of

```<code>string sproc = "EXEC sproc_NewUser @Organisation, @Client1, @Team, @Email  @UserName, @Password, @FirstName, @LastName";
</code>```

Just write

```<code>string sproc = "sproc_NewUser";
</code>```

Body:
I have a controller listed here which should be calling the Dapper method, however I cannot get it to execute. It's not throwing any exceptions and it is redirecting under the try catch however the procedure doesn't seem to be running as no new users are ever created.

The connection set up works with simple inline .Query methods however as soon as I attempt to do this with a stored procedure, it fails.

Model:

    public class User
    {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Boolean ActiveB { get; set; }
    }

View:

@model ScaleBase.Models.FullUser

@{
    ViewData["Title"] = "Create";
}

Create

User

        <form asp-action="Create">

                <input asp-for="OrganisationID" class="form-control" />

                <input asp-for="ClientID" class="form-control" />

                <input asp-for="TeamID" class="form-control" />

                <input asp-for="Email" class="form-control" />

                <input asp-for="Username" class="form-control" />

                <input asp-for="Password" type="password" class="form-control" />

                <input asp-for="FirstName" class="form-control" />

                <input asp-for="LastName" class="form-control" />

                        <input asp-for="ActiveB" /> @Html.DisplayNameFor(model => model.ActiveB)

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

Controller:

public ActionResult Create(IFormCollection collection)
{
        try
        {
            DynamicParameters parameters = new DynamicParameters();

            parameters.Add("@Organisation", collection["OrganisationID"]);
            parameters.Add("@ClientID1", collection["ClientID"]);
            parameters.Add("@Team", collection["TeamID"]);
            parameters.Add("@Email", collection["Email"]);
            parameters.Add("@UserName", collection["UserName"]);
            parameters.Add("@Password", collection["Password"]);
            parameters.Add("@FirstName", collection["FirstName"]);
            parameters.Add("@LastName", collection["LastName"]);

            var affectedRows = _dapperRepo.CreateUser(parameters);

            return RedirectToAction(nameof(Index));
        }
        catch (Exception)
        {
            throw;
        }
    }

Dapper repo:

    public async Task<User> CreateUser(DynamicParameters parameters)
    {
        using (IDbConnection conn = Connection)
        {
            string sproc = "EXEC sproc_NewUser @Organisation, @Client1, @Team, @Email  @UserName, @Password, @FirstName, @LastName";
            conn.Open();
            var result = await conn.QueryAsync(sproc, parameters, commandType: CommandType.StoredProcedure);
            return result.FirstOrDefault();
        }
    }

Stored procedure:

BEGIN TRY
    BEGIN TRANSACTION NewUser
        DECLARE @salt UNIQUEIDENTIFIER = NEWID()

        INSERT INTO [dbo].[User] (Username, Email, FirstName, LastName, Password, Salt, Active)
        VALUES (@UserName, @Email, @FirstName, @LastName, HASHBYTES('SHA2_512', @Password+CAST(@salt AS NVARCHAR(36))), @salt, 1)

        INSERT INTO [dbo].[UserOrganisations] (UserID, OrganisationID)
        VALUES (IDENT_CURRENT('User'), @Organisation)

        INSERT INTO [dbo].[UserClients] (UserID, ClientID)
        VALUES (IDENT_CURRENT('User'), @Client1)

        IF @Client2 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client2)
        END

        IF @Client3 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client3)
        END

        IF @Client4 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client4)
        END

        IF @Client5 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client5)
        END

        INSERT INTO [dbo].[UserTeams] (UserID, TeamID)
        VALUES (IDENT_CURRENT('User'), @Team)

        INSERT INTO [dbo].[UserPermission] (UserID, HolidayCount, HolidayUsed, TemplateID, ConfigState1, ConfigState2, ConfigState3, ConfigState4, ConfigState5)
        VALUES (IDENT_CURRENT('User'), @Holiday, 0, 1, 255, null, null, null, null)

        INSERT INTO [dbo].[UserTime] (UserID, Scale, StartTime, EndTime)
        VALUES (IDENT_CURRENT('User'), 1, @StartTime, @EndTime)

        COMMIT TRANSACTION NewUser

        PRINT 'Success'

        SELECT
            [UserID], [Username], [Email], [Firstname], [Lastname], [Active]
        FROM
            [User]
        WHERE
            [UserID] = IDENT_CURRENT('User')
END TRY
BEGIN CATCH
    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRANSACTION NewUser
        PRINT 'Failed'
    END

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage

        RETURN 'Error'
END CATCH

Body:
When using commandType: CommandType.StoredProcedure you only need to specify the stored procedure name - so instead of

string sproc = "EXEC sproc_NewUser @Organisation, @Client1, @Team, @Email  @UserName, @Password, @FirstName, @LastName";

Just write

string sproc = "sproc_NewUser";


问:
Have a way to just show the last item from my db, in a view with @foreach?
Have a way to just show the last item added on my db, to my home with @foreach?</p>

```<code>@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
                                    <div class="fs-rp-item">
                                        <div class="entry-image">
                                            <!--<a href="#"><img src="/holy/images/blog/fs-thumb.jpg" alt="recent post"></a>-->
                                            <a href="#"><img src="/uploads/post/{{$post->id}}/image/{{$post->file_1}}" alt="recent post"></a>
                                        </div>
                                        <div class="entry-rp">
                                            <h4>
                                                <a href="#">{{$post->title}}</a>
                                            </h4>
                                            <p class="read-more">
                                                <a href="#">read the article</a>
                                            </p>
                                        </div>
                                    </div>
                                    @endforeach
</code>```

答:
I don't quite understand your question. To me it does not make sense to iterate over a loop in order to show just the last item.

Anyhow, this is the approach for doing so:

```<code>@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
     @if($loop->last)
         // the end of the loop is reached at this point
     @endif
@endforeach
</code>```

A better approach would be to get the latest item from the post within your controller and pass that to the view, and print just its data:

```<code>use App\Models\Post; // at the top of your class

// your controller
public function index()
{
    $post = Post::latest()->first();
    return view('index', compact('post'));
}
</code>```

Then in the view you just use the latest post for example:

```<code><h4>
    <a href="#">{{$post->title}}</a>
</h4>
</code>```

Body:
Have a way to just show the last item added on my db, to my home with @foreach?

@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)

                                            id}}/image/{{$post->file_1}}" alt="recent post">

                                                {{$post->title}}

                                                read the article

                                    @endforeach

Body:
I don't quite understand your question. To me it does not make sense to iterate over a loop in order to show just the last item.

Anyhow, this is the approach for doing so:

@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
     @if($loop->last)
         // the end of the loop is reached at this point
     @endif
@endforeach

A better approach would be to get the latest item from the post within your controller and pass that to the view, and print just its data:

use App\Models\Post; // at the top of your class

// your controller
public function index()
{
    $post = Post::latest()->first();
    return view('index', compact('post'));
}

Then in the view you just use the latest post for example:

<h4>
    <a href="#">{{$post->title}}</a>
</h4>