问:
PHP $_POST not being recognized
Just recently picked up PHP for a project, currently I'm trying to get PHP to recognize when the submit button has been hit and to print "Success" using the code below (Ignore the fetchIntervals() that calls a javascript function):

```<code><button class = "button" type = "submit" name = "submit" onclick = "fetchIntervals()" method = "POST">Submit</button>
    <?php
        echo("Test"); //Prints out successfully
        if($_SERVER['REQUEST_METHOD'] == "POST"){
            echo("Post"); //Does not print
            if(isset($_GET["submit"])){
                echo("Success");
            }
        }
        if($_SERVER['REQUEST_METHOD'] == "GET"){
            echo("Get"); //Prints successfully even though I'm using POST method
            if(isset($_GET["submit"])){
                echo("Success"); //doesn't print at all when button is pressed
            }
        }
    ?>
</code>```

As said in the code I know it's entering into the PHP block since "Test" successfully prints out, but even though I'm using method = "POST" for my button the $_SERVER['REQUEST_METHOD'] == "GET" is returning true and it's not even registering the button being clicked.

答:
It is not clear from your code if the button element is wrapped inside a form element.

If it is not, the button should not be doing anything (i.e. it doesn't start a request to the server).

If it is, and the form has not got an attribute method="POST", it will send the form with the GET method (by default). If you want to set the method in the button element, the attribute name is formmethod and not method (Button specs).

When you first load the page, you are sending a GET request to the server. That is why the if($_SERVER['REQUEST_METHOD'] == "GET") test is true and the echo("Get"); is executed.

A possible modification could be adding a form tag as a parent of the button element and set its attribute method="POST". Setting the method on the button itself is usually not necessary, unless you have more submit buttons.

As a side note, echo is a language construct and not a function. Although it is allowed to call it with parenthesis, it is (wide) common practice to use it without.

Example: echo "Get";.

Title: PHP $_POST not being recognized

Body:
Just recently picked up PHP for a project, currently I'm trying to get PHP to recognize when the submit button has been hit and to print "Success" using the code below (Ignore the fetchIntervals() that calls a javascript function):

<button class = "button" type = "submit" name = "submit" onclick = "fetchIntervals()" method = "POST">Submit</button>
    <?php
        echo("Test"); //Prints out successfully
        if($_SERVER['REQUEST_METHOD'] == "POST"){
            echo("Post"); //Does not print
            if(isset($_GET["submit"])){
                echo("Success");
            }
        }
        if($_SERVER['REQUEST_METHOD'] == "GET"){
            echo("Get"); //Prints successfully even though I'm using POST method
            if(isset($_GET["submit"])){
                echo("Success"); //doesn't print at all when button is pressed
            }
        }
    ?>

As said in the code I know it's entering into the PHP block since "Test" successfully prints out, but even though I'm using method = "POST" for my button the $_SERVER['REQUEST_METHOD'] == "GET" is returning true and it's not even registering the button being clicked.


来源: stackexchange

问:
DataInputStream.readInt() returns EOFException when connection is made immediately and no data has been transferred
I'm implementing a 2-way file transfer between the server (Java FX) application and the client (A mobile application). File transfer from the JavaFX to the mobile app is successful, however when I tried to send files from the mobile app to the JavaFX application, I get an EOFException immediately I connect even when no files have been sent from the mobile app.

However, whenever I commented out the function used for receiving files from the JavaFX application, no error is thrown. I don't know, but it seems both inputStreams and outputStreams of both applications seem to clash or maybe there's something I am missing. I have googled this error all to no avail.

Minimal reproducible example of Server Code:

```<code>import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {
    DataOutputStream dataOutputStream;
    DataInputStream dataInputStream;

    public Server(){
        try{
            int port = 19051;
            ServerSocket serverSocket = new ServerSocket(port);

            while (true){

                Socket socket = serverSocket.accept();

                dataInputStream = new DataInputStream(socket.getInputStream());
                dataOutputStream = new DataOutputStream(socket.getOutputStream());

                MyThread myThread = new MyThread();
                new Thread(myThread).start();
            }
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
    }

    class MyThread implements Runnable{

        @Override
        public void run() {
            receiveFilesFromClient();
        }
    }

    public void receiveFilesFromClient(){
        try {
            int fileCount = dataInputStream.readInt();

            for (int i = 0; i < fileCount; ++i) {
                String filename;
                byte[] fileContentBytes;

                int fileNameLength = dataInputStream.readInt();
                if (fileNameLength > 0) {
                    byte[] fileNameBytes = new byte[fileNameLength];
                    dataInputStream.readFully(fileNameBytes, 0, fileNameLength);
                    filename = new String(fileNameBytes, StandardCharsets.UTF_8);

                    int fileContentLength = dataInputStream.readInt();
                    if (fileContentLength > 0) {
                        fileContentBytes = new byte[fileContentLength];
                        dataInputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
                    }
                }
            }
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
    }
}

</code>```

Minimal reproducible example for the mobile app:

```<code>import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StrictMode
import android.provider.OpenableColumns
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import java.io.*
import java.net.InetSocketAddress
import java.net.Socket

private const val REQUEST_EXTERNAL_STORAGE = 1
private const val CHOOSE_FILES = 1000
private const val TAG = "SendReceiveFileActivity"
class SendReceiveFileActivity : AppCompatActivity() {
    private var ip: String? = null
    private var port: Int? = null
    var clientSocket: Socket? = null
    private lateinit var myThread: MyThread
    private lateinit var sendButton: Button
    private var dataInputStream: DataInputStream? = null
    private var dataOutputStream: DataOutputStream? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_send_receive_file)

        val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)

        ip = intent.getStringExtra("ip")
        port = intent.getStringExtra("port")?.toInt()

        verifyStoragePermissions(this)

        sendButton = findViewById(R.id.btnSend)

        sendButton.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "*/*"
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            startActivityForResult(Intent.createChooser(intent, "Choose Files"), CHOOSE_FILES)
        }

        myThread = MyThread()
        Thread(myThread).start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CHOOSE_FILES) {
            if (resultCode == RESULT_OK) {
                if (data!!.clipData != null) {
                    val count = data.clipData!!.itemCount
                    var currentItem = 0
                    dataOutputStream?.writeInt(count)
                    while (currentItem < count) {
                        val uri = data.clipData!!.getItemAt(currentItem).uri
                        val fileInfo = getDataFromUri(uri)
                        sendFiles(uri, fileInfo)

                        currentItem += 1
                    }
                }
                else if (data.data != null) {
                    val uri = data.data!!
                    val fileInfo = getDataFromUri(uri)
                    sendFiles(uri, fileInfo)
                }
            }
        }
    }

    private fun getDataFromUri(uri: Uri): Pair<String, Long>{
        val cursor = contentResolver.query(uri, null, null,
            null, null)
        val nameIndex = cursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME)!!
        val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
        cursor.moveToFirst()
        val name = cursor.getString(nameIndex)
        val size = cursor.getLong(sizeIndex)
        cursor.close()
        return Pair(name, size)
    }

    private fun sendFiles(uri: Uri, fileInfo: Pair<String, Long>){
        try {
            val inputStream = contentResolver.openInputStream(uri)
            val fileName = fileInfo.first
            Log.d(TAG, "File $fileName sent")
            val fileNameBytes = fileName.toByteArray(Charsets.UTF_8)
            val fileContentBytes = ByteArray(fileInfo.second.toInt())
            inputStream!!.read(fileContentBytes)
            dataOutputStream?.writeInt(fileNameBytes.size)
            dataOutputStream?.write(fileNameBytes)
            dataOutputStream?.writeInt(fileContentBytes.size)
            dataOutputStream?.write(fileContentBytes)
            dataOutputStream?.flush()

        } catch (exception: IOException) {
            exception.printStackTrace()
        }
    }

    inner class MyThread: Runnable {

        override fun run() {
            clientSocket = Socket()
            clientSocket?.connect(port?.let { InetSocketAddress(ip, it) }, 5000)
            Log.d(TAG, "Socket Connected")

            dataInputStream = DataInputStream(clientSocket?.getInputStream())
            dataOutputStream = DataOutputStream(clientSocket?.getOutputStream())

            while (true){
                val fileNameLength = dataInputStream?.readInt()

                if (fileNameLength!! > 0){
                    val fileNameBytes = ByteArray(fileNameLength)
                    dataInputStream?.readFully(fileNameBytes, 0, fileNameLength)
                    val filename = String(fileNameBytes)

                    val fileContentLength = dataInputStream?.readInt()
                    if (fileContentLength!! > 0){
                        val fileContent = ByteArray(fileContentLength)
                        dataInputStream?.readFully(fileContent, 0, fileContentLength)
                        //downloadFile(filename, fileContent)
                    }
                }
            }
        }
    }
}

</code>```

The error message which is continually displayed in the logcat because of the loop is this:

```<code>java.io.EOFException
    at java.base/java.io.DataInputStream.readInt(DataInputStream.java:397)
    at com.sirdave.Controller.receiveFileFromClient(Controller.java:208)
    at com.sirdave.Controller$MyThread.run(Controller.java:174)
    at java.base/java.lang.Thread.run(Thread.java:834)
java.io.EOFException
</code>```

答:
Your client is sending only 1 file (but the function name is plural!). Does it disconnect afterward?

The server is looping endlessly to read multiple files (but the function name is singular!).

If the client disconnects after sending, it makes perfect sense why the receiving code would then throw an EOF error.

If you want to leave the connection open, either:

get rid of the reading loop in the server and just read 1 file at a time, to match the client sending 1 file at a time:

server:

public void receiveFileFromClient(){
    try {
        String filename;
        byte[] fileContentBytes;

        int fileNameLength = dataInputStream.readInt();
        if (fileNameLength > 0) {
            byte[] fileNameBytes = new byte[fileNameLength];
            dataInputStream.readFully(fileNameBytes, 0, fileNameLength);
            filename = new String(fileNameBytes, StandardCharset.UTF_8);
        }

        int fileContentLength = dataInputStream.readInt();
        if (fileContentLength > 0) {
            fileContentBytes = new byte[fileContentLength];
            dataInputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
        }

        System.out.println("File name received is " + filename);
        //downloadFile(filename, fileContentBytes);
    }
    catch (IOException exception){
        exception.printStackTrace();
    }
}
```
<p>client:</p>
```private fun sendFile(uri: Uri, fileInfo: Pair<String, Long>){
    try {
        val inputStream = contentResolver.openInputStream(uri)
        //val fileInputStream = FileInputStream(file.absolutePath)
        val fileName = fileInfo.first
        val fileNameBytes = fileName.toByteArray(Charsets.UTF_8)
        val fileContentBytes = ByteArray(fileInfo.second.toInt())
        //val num: Int = fileInputStream.read(fileContentBytes)
        inputStream!!.read(fileContentBytes)
        dataOutputStream?.writeInt(fileNameBytes.size)
        dataOutputStream?.write(fileNameBytes)
        dataOutputStream?.writeInt(fileContentBytes.size)
        dataOutputStream?.write(fileContentBytes)
        dataOutputStream?.flush()
    } catch (exception: IOException) {
        exception.printStackTrace()
    }
}
```
</li>
<li><p>have the client send an integer first indicating the number of files being sent, before then sending their datas, so the server knows when the stop looping:</p>
<p>server:</p>
<pre class="lang-java prettyprint-override"><code>public void receiveFilesFromClient(){
    try {
        int fileCount = dataInputStream.readInt();
        for (int i = 0; i < fileCount; ++i) {
            String filename;
            byte[] fileContentBytes;

            int fileNameLength = dataInputStream.readInt();
            if (fileNameLength > 0) {
                byte[] fileNameBytes = new byte[fileNameLength];
                dataInputStream.readFully(fileNameBytes, 0, fileNameLength);
                filename = new String(fileNameBytes, StandardCharset.UTF_8);
            }

            int fileContentLength = dataInputStream.readInt();
            if (fileContentLength > 0) {
                fileContentBytes = new byte[fileContentLength];
                dataInputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
            }

            System.out.println("File name received is " + filename);
            //downloadFile(filename, fileContentBytes);
        }
    }
    catch (IOException exception){
        exception.printStackTrace();
    }
}
</code>```

client:

```<code>private fun sendFile(uri: Uri, fileInfo: Pair<String, Long>){
    try {
        val inputStream = contentResolver.openInputStream(uri)
        //val fileInputStream = FileInputStream(file.absolutePath)
        val fileName = fileInfo.first
        val fileNameBytes = fileName.toByteArray(Charsets.UTF_8)
        val fileContentBytes = ByteArray(fileInfo.second.toInt())
        //val num: Int = fileInputStream.read(fileContentBytes)
        inputStream!!.read(fileContentBytes)
        dataOutputStream?.writeInt(1)
        dataOutputStream?.writeInt(fileNameBytes.size)
        dataOutputStream?.write(fileNameBytes)
        dataOutputStream?.writeInt(fileContentBytes.size)
        dataOutputStream?.write(fileContentBytes)
        dataOutputStream?.flush()
    } catch (exception: IOException) {
        exception.printStackTrace()
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm implementing a 2-way file transfer between the server (Java FX) application and the client (A mobile application). File transfer from the JavaFX to the mobile app is successful, however when I tried to send files from the mobile app to the JavaFX application, I get an EOFException immediately I connect even when no files have been sent from the mobile app.

However, whenever I commented out the function used for receiving files from the JavaFX application, no error is thrown. I don't know, but it seems both inputStreams and outputStreams of both applications seem to clash or maybe there's something I am missing. I have googled this error all to no avail.

Minimal reproducible example of Server Code:

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {
    DataOutputStream dataOutputStream;
    DataInputStream dataInputStream;

    public Server(){
        try{
            int port = 19051;
            ServerSocket serverSocket = new ServerSocket(port);

            while (true){

                Socket socket = serverSocket.accept();

                dataInputStream = new DataInputStream(socket.getInputStream());
                dataOutputStream = new DataOutputStream(socket.getOutputStream());

                MyThread myThread = new MyThread();
                new Thread(myThread).start();
            }
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
    }

    class MyThread implements Runnable{

        @Override
        public void run() {
            receiveFilesFromClient();
        }
    }

    public void receiveFilesFromClient(){
        try {
            int fileCount = dataInputStream.readInt();

            for (int i = 0; i < fileCount; ++i) {
                String filename;
                byte[] fileContentBytes;

                int fileNameLength = dataInputStream.readInt();
                if (fileNameLength > 0) {
                    byte[] fileNameBytes = new byte[fileNameLength];
                    dataInputStream.readFully(fileNameBytes, 0, fileNameLength);
                    filename = new String(fileNameBytes, StandardCharsets.UTF_8);

                    int fileContentLength = dataInputStream.readInt();
                    if (fileContentLength > 0) {
                        fileContentBytes = new byte[fileContentLength];
                        dataInputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
                    }
                }
            }
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
    }
}

Minimal reproducible example for the mobile app:

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StrictMode
import android.provider.OpenableColumns
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import java.io.*
import java.net.InetSocketAddress
import java.net.Socket

private const val REQUEST_EXTERNAL_STORAGE = 1
private const val CHOOSE_FILES = 1000
private const val TAG = "SendReceiveFileActivity"
class SendReceiveFileActivity : AppCompatActivity() {
    private var ip: String? = null
    private var port: Int? = null
    var clientSocket: Socket? = null
    private lateinit var myThread: MyThread
    private lateinit var sendButton: Button
    private var dataInputStream: DataInputStream? = null
    private var dataOutputStream: DataOutputStream? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_send_receive_file)

        val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)

        ip = intent.getStringExtra("ip")
        port = intent.getStringExtra("port")?.toInt()

        verifyStoragePermissions(this)

        sendButton = findViewById(R.id.btnSend)

        sendButton.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "*/*"
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            startActivityForResult(Intent.createChooser(intent, "Choose Files"), CHOOSE_FILES)
        }

        myThread = MyThread()
        Thread(myThread).start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CHOOSE_FILES) {
            if (resultCode == RESULT_OK) {
                if (data!!.clipData != null) {
                    val count = data.clipData!!.itemCount
                    var currentItem = 0
                    dataOutputStream?.writeInt(count)
                    while (currentItem < count) {
                        val uri = data.clipData!!.getItemAt(currentItem).uri
                        val fileInfo = getDataFromUri(uri)
                        sendFiles(uri, fileInfo)

                        currentItem += 1
                    }
                }
                else if (data.data != null) {
                    val uri = data.data!!
                    val fileInfo = getDataFromUri(uri)
                    sendFiles(uri, fileInfo)
                }
            }
        }
    }

    private fun getDataFromUri(uri: Uri): Pair<String, Long>{
        val cursor = contentResolver.query(uri, null, null,
            null, null)
        val nameIndex = cursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME)!!
        val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
        cursor.moveToFirst()
        val name = cursor.getString(nameIndex)
        val size = cursor.getLong(sizeIndex)
        cursor.close()
        return Pair(name, size)
    }

    private fun sendFiles(uri: Uri, fileInfo: Pair<String, Long>){
        try {
            val inputStream = contentResolver.openInputStream(uri)
            val fileName = fileInfo.first
            Log.d(TAG, "File $fileName sent")
            val fileNameBytes = fileName.toByteArray(Charsets.UTF_8)
            val fileContentBytes = ByteArray(fileInfo.second.toInt())
            inputStream!!.read(fileContentBytes)
            dataOutputStream?.writeInt(fileNameBytes.size)
            dataOutputStream?.write(fileNameBytes)
            dataOutputStream?.writeInt(fileContentBytes.size)
            dataOutputStream?.write(fileContentBytes)
            dataOutputStream?.flush()

        } catch (exception: IOException) {
            exception.printStackTrace()
        }
    }

    inner class MyThread: Runnable {

        override fun run() {
            clientSocket = Socket()
            clientSocket?.connect(port?.let { InetSocketAddress(ip, it) }, 5000)
            Log.d(TAG, "Socket Connected")

            dataInputStream = DataInputStream(clientSocket?.getInputStream())
            dataOutputStream = DataOutputStream(clientSocket?.getOutputStream())

            while (true){
                val fileNameLength = dataInputStream?.readInt()

                if (fileNameLength!! > 0){
                    val fileNameBytes = ByteArray(fileNameLength)
                    dataInputStream?.readFully(fileNameBytes, 0, fileNameLength)
                    val filename = String(fileNameBytes)

                    val fileContentLength = dataInputStream?.readInt()
                    if (fileContentLength!! > 0){
                        val fileContent = ByteArray(fileContentLength)
                        dataInputStream?.readFully(fileContent, 0, fileContentLength)
                        //downloadFile(filename, fileContent)
                    }
                }
            }
        }
    }
}

The error message which is continually displayed in the logcat because of the loop is this:

java.io.EOFException
    at java.base/java.io.DataInputStream.readInt(DataInputStream.java:397)
    at com.sirdave.Controller.receiveFileFromClient(Controller.java:208)
    at com.sirdave.Controller$MyThread.run(Controller.java:174)
    at java.base/java.lang.Thread.run(Thread.java:834)
java.io.EOFException

Body:
Your client is sending only 1 file (but the function name is plural!). Does it disconnect afterward?

The server is looping endlessly to read multiple files (but the function name is singular!).

If the client disconnects after sending, it makes perfect sense why the receiving code would then throw an EOF error.

If you want to leave the connection open, either:

get rid of the reading loop in the server and just read 1 file at a time, to match the client sending 1 file at a time:

server:

public void receiveFileFromClient(){
    try {
        String filename;
        byte[] fileContentBytes;

        int fileNameLength = dataInputStream.readInt();
        if (fileNameLength > 0) {
            byte[] fileNameBytes = new byte[fileNameLength];
            dataInputStream.readFully(fileNameBytes, 0, fileNameLength);
            filename = new String(fileNameBytes, StandardCharset.UTF_8);
        }

        int fileContentLength = dataInputStream.readInt();
        if (fileContentLength > 0) {
            fileContentBytes = new byte[fileContentLength];
            dataInputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
        }

        System.out.println("File name received is " + filename);
        //downloadFile(filename, fileContentBytes);
    }
    catch (IOException exception){
        exception.printStackTrace();
    }
}

client:

private fun sendFile(uri: Uri, fileInfo: Pair<String, Long>){
    try {
        val inputStream = contentResolver.openInputStream(uri)
        //val fileInputStream = FileInputStream(file.absolutePath)
        val fileName = fileInfo.first
        val fileNameBytes = fileName.toByteArray(Charsets.UTF_8)
        val fileContentBytes = ByteArray(fileInfo.second.toInt())
        //val num: Int = fileInputStream.read(fileContentBytes)
        inputStream!!.read(fileContentBytes)
        dataOutputStream?.writeInt(fileNameBytes.size)
        dataOutputStream?.write(fileNameBytes)
        dataOutputStream?.writeInt(fileContentBytes.size)
        dataOutputStream?.write(fileContentBytes)
        dataOutputStream?.flush()
    } catch (exception: IOException) {
        exception.printStackTrace()
    }
}

have the client send an integer first indicating the number of files being sent, before then sending their datas, so the server knows when the stop looping:

server:

public void receiveFilesFromClient(){
    try {
        int fileCount = dataInputStream.readInt();
        for (int i = 0; i < fileCount; ++i) {
            String filename;
            byte[] fileContentBytes;

            int fileNameLength = dataInputStream.readInt();
            if (fileNameLength > 0) {
                byte[] fileNameBytes = new byte[fileNameLength];
                dataInputStream.readFully(fileNameBytes, 0, fileNameLength);
                filename = new String(fileNameBytes, StandardCharset.UTF_8);
            }

            int fileContentLength = dataInputStream.readInt();
            if (fileContentLength > 0) {
                fileContentBytes = new byte[fileContentLength];
                dataInputStream.readFully(fileContentBytes, 0, fileContentBytes.length);
            }

            System.out.println("File name received is " + filename);
            //downloadFile(filename, fileContentBytes);
        }
    }
    catch (IOException exception){
        exception.printStackTrace();
    }
}

client:

private fun sendFile(uri: Uri, fileInfo: Pair<String, Long>){
    try {
        val inputStream = contentResolver.openInputStream(uri)
        //val fileInputStream = FileInputStream(file.absolutePath)
        val fileName = fileInfo.first
        val fileNameBytes = fileName.toByteArray(Charsets.UTF_8)
        val fileContentBytes = ByteArray(fileInfo.second.toInt())
        //val num: Int = fileInputStream.read(fileContentBytes)
        inputStream!!.read(fileContentBytes)
        dataOutputStream?.writeInt(1)
        dataOutputStream?.writeInt(fileNameBytes.size)
        dataOutputStream?.write(fileNameBytes)
        dataOutputStream?.writeInt(fileContentBytes.size)
        dataOutputStream?.write(fileContentBytes)
        dataOutputStream?.flush()
    } catch (exception: IOException) {
        exception.printStackTrace()
    }
}


问:
Blogger Form Creater
I actually don't know how to explain what I need, but I will try.
I want to create a form in my post, and when a user will fill that form and click submit, some text will be shown in the box below that will be allowed to copy. In this text, the details added in the form will be used.
If you visit this post.

https://hackerthylord.blogspot.com/2021/04/privacy-policy-generator.html

You will see it's a privacy policy generator. When you fill out the form and click on generate button. Some code shows below with the value I given in the form below.

I want to create a form like that with just 1 input box.
How is this possible?

答:
yes, a simple and basic solution is you use a javascript function for create passage (code) and fill it with entered data. something like this:

```<code><script>
    function createPassage(companyName){
        var passage = "<a href='www.site.com'>"+companyName+"</a>";
        return passage;
    }
</script>
</code>```

then you put rendered passage (code) every where you want (See below).

How to show javascript code in HTML

Display HTML snippets in HTML

and at last you need a button for copy passage.

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

note: you can use highlightjs and prismjs for better experience

Title: Blogger Form Creater

Body:
yes, a simple and basic solution is you use a javascript function for create passage (code) and fill it with entered data. something like this:

<script>
    function createPassage(companyName){
        var passage = "<a href='www.site.com'>"+companyName+"</a>";
        return passage;
    }
</script>

then you put rendered passage (code) every where you want (See below).

How to show javascript code in HTML

Display HTML snippets in HTML

and at last you need a button for copy passage.

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

note: you can use highlightjs and prismjs for better experience


问:
Rails: Param is missing or the value is empty in ManagerController#addtoproject
I have been trying to add project_id and user_id to the following

```<code> create_table "project_users", force: :cascade do |t|
    t.integer "project_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
</code>```

Model project_user.rb

```<code>class ProjectUser < ApplicationRecord
  has_many :users
  has_many :projects
end
</code>```

This is my controller that is supposed to add data in the table:

```<code>def addtoproject
    @emp_id = params[:eid]
    @project_id = params[:pid]

    @add_user = ProjectUser.new(params.require(:projectuser).permit(:project_id, :user_id))
    @add_user.project_id = @project_id
    @add_user.user_id = @emp_id
    @add_user.save
  end
</code>```

@emp_id and @project_id both contain valid values.
Rails is throwing the error on the line

```<code>@add_user = ProjectUser.new(params.require(:projectuser).permit(:project_id, :user_id))
</code>```

Error screenshot:

Any clues how this error can be fixed? As the table name is "project_users", I reckon I maybe missing an "_" somewhere?

Update 1
Clicking Add to Project invokes the method addtoproject inside controller.

addusers.html.erb:

```<code><table id='employee-table' class="table table-hover">
    <thead  class="thead-light">
      <tr>
        <th>Employee ID</th>
        <th>Name</th>
        <th>Role</th>
        <th colspan="2"></th>
      </tr>
    </thead>

    <tbody>
      <% @employees.each_with_index do |employee, index| %>
        <tr>
          <td><%= employee.id %></td>
          <td><%= employee.firstname + ' ' + employee.lastname %></td>
          <td><%= employee.user_type %></td>
          <td><%= link_to "Add to Project", add_to_project_path(eid: employee, pid: @project_id), :class => "btn btn-success", :style => "float:right"%></td>
        </tr>
      <% end %>
    </tbody>
  </table>
</code>```

答:
It's complaining because you're doing

```<code>params.require(:projectuser)
</code>```

This means that :projectuser doesn't exist in params. You can see the parameters that are being sent to your controller further down in that screenshot. Only a pid and eid are present.

If you're using a form, you may need to change it to use something like form_for so your parameters are namespaced to the model.

```<code><%= form_for @project_user do |f| %>
  <%= f.number_field :pid %>
  <%= f.number_field :eid %>
</code>```

You'll also face errors with the `permit section since you specify

```<code>permit(:project_id, :user_id)
</code>```

But the params passed are pid and uid. Use the name of your model fields in your inputs:

```<code><%= form_for @project_user do |f| %>
  <%= f.number_field :project_id %>
  <%= f.number_field :user_id %>
</code>```

Body:
I have been trying to add project_id and user_id to the following

 create_table "project_users", force: :cascade do |t|
    t.integer "project_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

Model project_user.rb

class ProjectUser < ApplicationRecord
  has_many :users
  has_many :projects
end

This is my controller that is supposed to add data in the table:

def addtoproject
    @emp_id = params[:eid]
    @project_id = params[:pid]

    @add_user = ProjectUser.new(params.require(:projectuser).permit(:project_id, :user_id))
    @add_user.project_id = @project_id
    @add_user.user_id = @emp_id
    @add_user.save
  end

@emp_id and @project_id both contain valid values.
Rails is throwing the error on the line

@add_user = ProjectUser.new(params.require(:projectuser).permit(:project_id, :user_id))

Error screenshot:

Any clues how this error can be fixed? As the table name is "project_users", I reckon I maybe missing an "_" somewhere?

Update 1
Clicking Add to Project invokes the method addtoproject inside controller.

addusers.html.erb:

        Employee ID
        Name
        Role

      <% @employees.each_with_index do |employee, index| %>

          <%= employee.id %>
          <%= employee.firstname + ' ' + employee.lastname %>
          <%= employee.user_type %>
          <%= link_to "Add to Project", add_to_project_path(eid: employee, pid: @project_id), :class => "btn btn-success", :style => "float:right"%>

      <% end %>

Body:
It's complaining because you're doing

params.require(:projectuser)

This means that :projectuser doesn't exist in params. You can see the parameters that are being sent to your controller further down in that screenshot. Only a pid and eid are present.

If you're using a form, you may need to change it to use something like form_for so your parameters are namespaced to the model.

<%= form_for @project_user do |f| %>
  <%= f.number_field :pid %>
  <%= f.number_field :eid %>

You'll also face errors with the `permit section since you specify

permit(:project_id, :user_id)

But the params passed are pid and uid. Use the name of your model fields in your inputs:

<%= form_for @project_user do |f| %>
  <%= f.number_field :project_id %>
  <%= f.number_field :user_id %>


问:
Passing List of class objects to config file
I have got class:

```<code>class Region{
String name;
List<String> BlockPlayers = new ArrayList<>();
}
</code>```

Then I made a List of objects in my program like this

```<code>List<Region> playersRegions = new ArrayList<>();
</code>```

Now I need to make a function that will pass objects from playersRegions list to config file. Then I need to make function that will load everything from config file and pass to playersRegions list

I have made something like this

```<code>private void save_regions_inConfig()
{
getConfig().set("locs", playersRegions);
saveConfig();
}
</code>```

But I have no idea how to load it from file to playersRegions. I just want to keep everything after I close the program and open it once more.

答:
You should define a way to format the region.

Let assume method are on your JavaPlugin class and everything else is well made (plugin.yml valid etc)

To write them, use something like this:

public void saveRegion(List<Region> regions) {
   FileConfiguration config = getConfig();
   int i = 0;
   for(Region r : regions) {
       config.set("regions." + i + ".name", r.name);
       config.set("regions." + i + ".blockplayers", r.BlockPlayers);

       i++;
   }
   saveConfig();
}
```
<p>The config file will be like this:</p>
<pre class="lang-yaml prettyprint-override"><code>regions:
   0:
      name: "Region 1"
      blockplayers:
      - "Something"
</code>```

Now, to read it, you should do something like that:

public List<Region> getRegion() {
   ConfigurationSection config = getConfig().getConfigurationSection("regions");
   if(config == null) // no region set yet
       return new ArrayList<>();
   List<Region> list = new ArrayList<>();
   for(String keys : config.getKeys(false)) {
       ConfigurationSection regionConfig = config.getConfigurationSection(keys);
       list.add(new Region(regionConfig.getString("name"), region.getStringList("blockplayers")));
   }
   return list;
}
```
<p>Note: you should define a constructor in your <code>Region</code> object like that:</p>
<pre class="lang-java prettyprint-override"><code>public class Region{
    String name;
    List<String> blockPlayers = new ArrayList<>();

    public Region(String name, List<String> blockPlayers) {
        this.name = name;
        this.blockPlayers = blockPlayers;
    }
}
</code>```

Finally, some of your name (method or variable) doesn't meet the Java convention. Specially about method, but that's a detail.

Body:
I have got class:

class Region{
String name;
List<String> BlockPlayers = new ArrayList<>();
}

Then I made a List of objects in my program like this

List<Region> playersRegions = new ArrayList<>();

Now I need to make a function that will pass objects from playersRegions list to config file. Then I need to make function that will load everything from config file and pass to playersRegions list

I have made something like this

private void save_regions_inConfig()
{
getConfig().set("locs", playersRegions);
saveConfig();
}

But I have no idea how to load it from file to playersRegions. I just want to keep everything after I close the program and open it once more.

Body:
You should define a way to format the region.

Let assume method are on your JavaPlugin class and everything else is well made (plugin.yml valid etc)

To write them, use something like this:

public void saveRegion(List<Region> regions) {
   FileConfiguration config = getConfig();
   int i = 0;
   for(Region r : regions) {
       config.set("regions." + i + ".name", r.name);
       config.set("regions." + i + ".blockplayers", r.BlockPlayers);

       i++;
   }
   saveConfig();
}

The config file will be like this:

regions:
   0:
      name: "Region 1"
      blockplayers:
      - "Something"

Now, to read it, you should do something like that:

public List<Region> getRegion() {
   ConfigurationSection config = getConfig().getConfigurationSection("regions");
   if(config == null) // no region set yet
       return new ArrayList<>();
   List<Region> list = new ArrayList<>();
   for(String keys : config.getKeys(false)) {
       ConfigurationSection regionConfig = config.getConfigurationSection(keys);
       list.add(new Region(regionConfig.getString("name"), region.getStringList("blockplayers")));
   }
   return list;
}

Note: you should define a constructor in your Region object like that:

public class Region{
    String name;
    List<String> blockPlayers = new ArrayList<>();

    public Region(String name, List<String> blockPlayers) {
        this.name = name;
        this.blockPlayers = blockPlayers;
    }
}

Finally, some of your name (method or variable) doesn't meet the Java convention. Specially about method, but that's a detail.


问:
how to change the text direction of the error message for the TextFormField to make it right to left
InputDecoration  has the property for changing it's style but can't find anything about it's direction

text form error

答:
Wrap your TextFormField inside Directionality Widget and set the direction to rtl like this :</p>
```<code>Directionality(
        textDirection: TextDirection.rtl,
        child: TextFormField()
     )
</code>```

Body:
Wrap your TextFormField inside Directionality Widget and set the direction to rtl like this :

Directionality(
        textDirection: TextDirection.rtl,
        child: TextFormField()
     )


问:
impossible open excel file through getOpenFilename
I'm trying to open in another application an excel file through a dialog window an excel.
I found this code in another post. However I don't get to open the file.
I think the issues are in these lines of the code:If sFilePath = False Then and Set wb = excelApp.Workbooks.Open(sFilePath, False)
I'm also trying to open a file .xlsx

```<code>Sub OpenFile()

' Create Excel object
'    On Error Resume Next
    Dim excelApp As Excel.Application
    Set excelApp = GetObject(, "Excel.Application")

    ' Prompt user to select Excel file to read from
    ' Alternatively, you could hard code the filepath like this:
    Dim sFilePath As String
    sFilePath = excelApp.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", Title:="Select excel file")
'    ' Open Excel file invisibly
    If sFilePath = False Then
        Exit Sub
    Else
        Set wb = excelApp.Workbooks.Open(sFilePath, False)
    End If

   End Sub
</code>```

答:
Use Excel From Another Application

The Mistakes

Set xlApp = GetObject(, "Excel.Application") or Set xlApp = Excel.Application will reference an existing instance of Excel. If Excel isn't open (there is no instance), an error will occur.

.GetOpenFileName will return the file path (a string) or the boolean False. If you use a string variable, the boolean False will be converted to the string "False" so you can use the string to test if the dialog was canceled.

First Solution (Early Binding)

For example, if you want to open an Excel file from Word, you can create a reference to the Excel library and develop your macro almost as if you were in Excel e.g. all the objects from Excel will be available in the Word's IntelliSense.

To reference a new instance of the Excel Application object using early binding, you will use:

```<code>Set xlApp = New Excel.Application
</code>```

Second Solution (Late Binding)

If you don't want to create a reference to the Excel library and/or you want to send the file to someone and you don't want to bother him/her with the details on how to create a reference, you will use late binding when you won't have access to the Excel objects' IntelliSense.

To reference a new instance of the Excel Application object using late binding, you will use:

```<code>Set xlApp = CreateObject("Excel.Application")
</code>```

A Few Details

Whether Excel is already open or not, these codes will create a new instance that you will want to close after you're done.

To do this correctly, you have to account for possible errors occurring which is done by using an error-handling routine.

So whatever happens, in the end, the new Excel instance needs to get closed.

The Codes

```<code>Option Explicit

Sub OpenFileUsingExcelReference()
' Needs a reference to 'VBE>Tools>References>Microsoft Excel 16.0 Object Library'
    Const ProcName As String = "OpenFile"

    Dim xlApp As Excel.Application
    Dim wb As Workbook

    On Error GoTo ClearError

    Const FileFilterString As String = "Excel Files (*.xls*),*.xls*"
    Const TitleString As String = "Select Excel file"

    ' Reference a new invisible Excel application object.
    Set xlApp = New Excel.Application ' CreateObject("Excel.Application")
    xlApp.Visible = True ' when done developing, out-comment this line

    ' Prompt user to select Excel file to read from
    Dim sFilePath As String
    sFilePath = xlApp.GetOpenFilename( _
        FileFilter:=FileFilterString, Title:=TitleString)
    If sFilePath = "False" Then
        Err.Raise 1004, , "You canceled the dialog."
        'MsgBox "You canceled."
    End If

    Set wb = xlApp.Workbooks.Open(sFilePath, False)

    ' Continue, e.g.:
    Debug.Print "The workbook '" & wb.Name & "' has " _
        & wb.Sheets.Count & " sheet(s)."

SafeExit:

    ' Close the workbook and quit.
    If Not wb Is Nothing Then wb.Close SaveChanges:=False
    If Not xlApp Is Nothing Then xlApp.Quit

    Exit Sub

ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume SafeExit
End Sub

Sub OpenFileWithoutExcelReference()
' No reference needed (*** indicates the differences)
    Const ProcName As String = "OpenFile"

    Dim xlApp As Object '***
    Dim wb As Object '***

    On Error GoTo ClearError

    Const FileFilterString As String = "Excel Files (*.xls*),*.xls*"
    Const TitleString As String = "Select Excel file"

    ' Reference a new invisible Excel application object.
    Set xlApp = CreateObject("Excel.Application") '***
    xlApp.Visible = True ' when done developing, out-comment this line

    ' Prompt user to select Excel file to read from
    Dim sFilePath As String
    sFilePath = xlApp.GetOpenFilename( _
        FileFilter:=FileFilterString, Title:=TitleString)
    If sFilePath = "False" Then
        Err.Raise 1004, , "You canceled the dialog."
        'MsgBox "You canceled."
    End If

    Set wb = xlApp.Workbooks.Open(sFilePath, False)

    ' Continue
    Debug.Print "The workbook '" & wb.Name & "' has " _
        & wb.Sheets.Count & " sheet(s)."

SafeExit:

    ' Close the workbook and quit.
    If Not wb Is Nothing Then wb.Close SaveChanges:=False
    If Not xlApp Is Nothing Then xlApp.Quit

    Exit Sub

ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume SafeExit
End Sub
</code>```

Body:
I'm trying to open in another application an excel file through a dialog window an excel.
I found this code in another post. However I don't get to open the file.
I think the issues are in these lines of the code:If sFilePath = False Then and Set wb = excelApp.Workbooks.Open(sFilePath, False)
I'm also trying to open a file .xlsx

Sub OpenFile()

' Create Excel object
'    On Error Resume Next
    Dim excelApp As Excel.Application
    Set excelApp = GetObject(, "Excel.Application")

    ' Prompt user to select Excel file to read from
    ' Alternatively, you could hard code the filepath like this:
    Dim sFilePath As String
    sFilePath = excelApp.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", Title:="Select excel file")
'    ' Open Excel file invisibly
    If sFilePath = False Then
        Exit Sub
    Else
        Set wb = excelApp.Workbooks.Open(sFilePath, False)
    End If

   End Sub

Body:
Use Excel From Another Application

The Mistakes

Set xlApp = GetObject(, "Excel.Application") or Set xlApp = Excel.Application will reference an existing instance of Excel. If Excel isn't open (there is no instance), an error will occur.

.GetOpenFileName will return the file path (a string) or the boolean False. If you use a string variable, the boolean False will be converted to the string "False" so you can use the string to test if the dialog was canceled.

First Solution (Early Binding)

For example, if you want to open an Excel file from Word, you can create a reference to the Excel library and develop your macro almost as if you were in Excel e.g. all the objects from Excel will be available in the Word's IntelliSense.

To reference a new instance of the Excel Application object using early binding, you will use:

Set xlApp = New Excel.Application

Second Solution (Late Binding)

If you don't want to create a reference to the Excel library and/or you want to send the file to someone and you don't want to bother him/her with the details on how to create a reference, you will use late binding when you won't have access to the Excel objects' IntelliSense.

To reference a new instance of the Excel Application object using late binding, you will use:

Set xlApp = CreateObject("Excel.Application")

A Few Details

Whether Excel is already open or not, these codes will create a new instance that you will want to close after you're done.

To do this correctly, you have to account for possible errors occurring which is done by using an error-handling routine.

So whatever happens, in the end, the new Excel instance needs to get closed.

The Codes

Option Explicit

Sub OpenFileUsingExcelReference()
' Needs a reference to 'VBE>Tools>References>Microsoft Excel 16.0 Object Library'
    Const ProcName As String = "OpenFile"

    Dim xlApp As Excel.Application
    Dim wb As Workbook

    On Error GoTo ClearError

    Const FileFilterString As String = "Excel Files (*.xls*),*.xls*"
    Const TitleString As String = "Select Excel file"

    ' Reference a new invisible Excel application object.
    Set xlApp = New Excel.Application ' CreateObject("Excel.Application")
    xlApp.Visible = True ' when done developing, out-comment this line

    ' Prompt user to select Excel file to read from
    Dim sFilePath As String
    sFilePath = xlApp.GetOpenFilename( _
        FileFilter:=FileFilterString, Title:=TitleString)
    If sFilePath = "False" Then
        Err.Raise 1004, , "You canceled the dialog."
        'MsgBox "You canceled."
    End If

    Set wb = xlApp.Workbooks.Open(sFilePath, False)

    ' Continue, e.g.:
    Debug.Print "The workbook '" & wb.Name & "' has " _
        & wb.Sheets.Count & " sheet(s)."

SafeExit:

    ' Close the workbook and quit.
    If Not wb Is Nothing Then wb.Close SaveChanges:=False
    If Not xlApp Is Nothing Then xlApp.Quit

    Exit Sub

ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume SafeExit
End Sub

Sub OpenFileWithoutExcelReference()
' No reference needed (*** indicates the differences)
    Const ProcName As String = "OpenFile"

    Dim xlApp As Object '***
    Dim wb As Object '***

    On Error GoTo ClearError

    Const FileFilterString As String = "Excel Files (*.xls*),*.xls*"
    Const TitleString As String = "Select Excel file"

    ' Reference a new invisible Excel application object.
    Set xlApp = CreateObject("Excel.Application") '***
    xlApp.Visible = True ' when done developing, out-comment this line

    ' Prompt user to select Excel file to read from
    Dim sFilePath As String
    sFilePath = xlApp.GetOpenFilename( _
        FileFilter:=FileFilterString, Title:=TitleString)
    If sFilePath = "False" Then
        Err.Raise 1004, , "You canceled the dialog."
        'MsgBox "You canceled."
    End If

    Set wb = xlApp.Workbooks.Open(sFilePath, False)

    ' Continue
    Debug.Print "The workbook '" & wb.Name & "' has " _
        & wb.Sheets.Count & " sheet(s)."

SafeExit:

    ' Close the workbook and quit.
    If Not wb Is Nothing Then wb.Close SaveChanges:=False
    If Not xlApp Is Nothing Then xlApp.Quit

    Exit Sub

ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume SafeExit
End Sub


问:
minecraft clickgui is broken
so i was following the tutorial but it bugs

the tutorial: https://www.youtube.com/watch?v=clonDGFq49Y\
The bug:

The bug is when i want to have long name in the hack it disappears

Please help

i will shot the code:\

package sonikhack.render;

import java.io.IOException;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import sonikhack.Client;
import sonikhack.module.Module;
import sonikhack.module.Category;

public class ClickGui extends GuiScreen{

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        drawDefaultBackground();
        drawRect(150, 2, 220, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Combat", 152, 4, 0xffffffff);
        drawRect(250, 2, 322, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Movement", 252, 4, 0xffffffff);
        drawRect(350, 2, 432, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Render", 352, 4, 0xffffffff);
        drawRect(450, 2, 506, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Misc", 452, 4, 0xffffffff);
        super.drawScreen(mouseX, mouseY, partialTicks);
    }

    @Override
    public boolean doesGuiPauseGame() {
        return false;
    }

    public int placeForHackY(Module m) {

        if(m.getCategory().equals(Category.COMBAT)) return Category.placeInListCombat(m) * 14;
        if(m.getCategory().equals(Category.MOVEMENT)) return Category.placeInListMovement(m) * 14;
        if(m.getCategory().equals(Category.RENDER)) return Category.placeInListRender(m) * 14;
        if(m.getCategory().equals(Category.MISC)) return Category.placeInListMisc(m) * 14;

        return 0;
    }

    public int placeForHackX(Module m) {

        if(m.getCategory().equals(Category.COMBAT)) return 150;
        if(m.getCategory().equals(Category.MOVEMENT)) return 250;
        if(m.getCategory().equals(Category.RENDER)) return 350;
        if(m.getCategory().equals(Category.MISC)) return 450;

        return 0;
    }

    public void initGui() {
            for(int i = 1; i < Client.modules.size(); i++) {
                Module m = Client.modules.get(i);
                buttonList.add(new GuiButton(i, placeForHackX(m), placeForHackY(m), 25 + (m.getName().length() * 3) + m.getName().length(), 14, m.getName()));
            }
    }

    @Override
    protected void actionPerformed(GuiButton button) throws IOException {
        for(int i= 1; i < Client.modules.size(); i++) {
            if(button.id == i) {
                Client.getModules().get(i).toggle();
            }
        }
    }
}
```
<p>This is the clickgui<br />
now category:</p>
<pre class="lang-java prettyprint-override"><code>package sonikhack.module;

import sonikhack.Client;

    public enum Category {
        COMBAT("Combat"),
        MOVEMENT("Movement"),
        RENDER("Render"),
        MISC("Misc");

        public String name;
        public int moduleIndex;

        Category(String name) {
            this.name = name;
        }

    public static int size(Category cat) {

        int i = 0;

        for(Module m : Client.getModules()) {
            if(m.getCategory().equals(cat)) {
                i++;
            }
        }

        return 0;
    }

    public static int placeInListRender(Module m) {

        int i = 0;

        for(Module mod : Client.getModules()) {
            if(mod.getCategory().equals(RENDER) && !mod.equals(m)) {
                i++;
                continue;
            }

            if(mod.getCategory().equals(RENDER) && mod.equals(m)) {
                return i;
            }

        }

        return 0;
    }
    public static int placeInListMovement(Module m) {

        int i = 1;

        for(Module mod : Client.getModules()) {
            if(mod.getCategory().equals(MOVEMENT) && !mod.equals(m)) {
                i++;
                continue;
            }

            if(mod.getCategory().equals(MOVEMENT) && mod.equals(m)) {
                return i;
            }

        }

        return 0;
    }
    public static int placeInListCombat(Module m) {

    int i = 1;

    for(Module mod : Client.getModules()) {
        if(mod.getCategory().equals(COMBAT) && !mod.equals(m)) {
            i++;
            continue;
        }

        if(mod.getCategory().equals(COMBAT) && mod.equals(m)) {
            return i;
        }

    }

    return 0;
}
    public static int placeInListMisc(Module m) {

    int i = 1;

    for(Module mod : Client.getModules()) {
        if(mod.getCategory().equals(MISC) && !mod.equals(m)) {
            i++;
            continue;
        }

        if(mod.getCategory().equals(MISC) && mod.equals(m)) {
            return i;
        }

    }

    return 0;
}

}
</code>```

And the gui:

package sonikhack.render;

import org.lwjgl.input.Keyboard;

import sonikhack.module.Category;
import sonikhack.module.Module;

public class Gui extends Module{

    public Gui() {
        super("ClickGui", Keyboard.KEY_RSHIFT, Category.RENDER);
    }

    public void onEnable() {
        mc.displayGuiScreen(new ClickGui());
        toggle();
    }

}
```

答: The only suggestable solution is to either make the text shorter or to try to fix it yourself. This is not a place where you can just post your code and expect someone to fix the issue. Maybe you should try learning java before coding a client. (And maybe not a hack client tbh)</p>

Title: minecraft clickgui is broken

Body:
so i was following the tutorial but it bugs

the tutorial: https://www.youtube.com/watch?v=clonDGFq49Y\
The bug:

The bug is when i want to have long name in the hack it disappears

Please help

i will shot the code:\

package sonikhack.render;

import java.io.IOException;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import sonikhack.Client;
import sonikhack.module.Module;
import sonikhack.module.Category;

public class ClickGui extends GuiScreen{

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        drawDefaultBackground();
        drawRect(150, 2, 220, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Combat", 152, 4, 0xffffffff);
        drawRect(250, 2, 322, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Movement", 252, 4, 0xffffffff);
        drawRect(350, 2, 432, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Render", 352, 4, 0xffffffff);
        drawRect(450, 2, 506, 14, 0xffff6052);
        mc.fontRendererObj.drawString("Misc", 452, 4, 0xffffffff);
        super.drawScreen(mouseX, mouseY, partialTicks);
    }

    @Override
    public boolean doesGuiPauseGame() {
        return false;
    }

    public int placeForHackY(Module m) {

        if(m.getCategory().equals(Category.COMBAT)) return Category.placeInListCombat(m) * 14;
        if(m.getCategory().equals(Category.MOVEMENT)) return Category.placeInListMovement(m) * 14;
        if(m.getCategory().equals(Category.RENDER)) return Category.placeInListRender(m) * 14;
        if(m.getCategory().equals(Category.MISC)) return Category.placeInListMisc(m) * 14;

        return 0;
    }

    public int placeForHackX(Module m) {

        if(m.getCategory().equals(Category.COMBAT)) return 150;
        if(m.getCategory().equals(Category.MOVEMENT)) return 250;
        if(m.getCategory().equals(Category.RENDER)) return 350;
        if(m.getCategory().equals(Category.MISC)) return 450;

        return 0;
    }

    public void initGui() {
            for(int i = 1; i < Client.modules.size(); i++) {
                Module m = Client.modules.get(i);
                buttonList.add(new GuiButton(i, placeForHackX(m), placeForHackY(m), 25 + (m.getName().length() * 3) + m.getName().length(), 14, m.getName()));
            }
    }

    @Override
    protected void actionPerformed(GuiButton button) throws IOException {
        for(int i= 1; i < Client.modules.size(); i++) {
            if(button.id == i) {
                Client.getModules().get(i).toggle();
            }
        }
    }
}

This is the clickgui

now category:

package sonikhack.module;

import sonikhack.Client;

    public enum Category {
        COMBAT("Combat"),
        MOVEMENT("Movement"),
        RENDER("Render"),
        MISC("Misc");

        public String name;
        public int moduleIndex;

        Category(String name) {
            this.name = name;
        }

    public static int size(Category cat) {

        int i = 0;

        for(Module m : Client.getModules()) {
            if(m.getCategory().equals(cat)) {
                i++;
            }
        }

        return 0;
    }

    public static int placeInListRender(Module m) {

        int i = 0;

        for(Module mod : Client.getModules()) {
            if(mod.getCategory().equals(RENDER) && !mod.equals(m)) {
                i++;
                continue;
            }

            if(mod.getCategory().equals(RENDER) && mod.equals(m)) {
                return i;
            }

        }

        return 0;
    }
    public static int placeInListMovement(Module m) {

        int i = 1;

        for(Module mod : Client.getModules()) {
            if(mod.getCategory().equals(MOVEMENT) && !mod.equals(m)) {
                i++;
                continue;
            }

            if(mod.getCategory().equals(MOVEMENT) && mod.equals(m)) {
                return i;
            }

        }

        return 0;
    }
    public static int placeInListCombat(Module m) {

    int i = 1;

    for(Module mod : Client.getModules()) {
        if(mod.getCategory().equals(COMBAT) && !mod.equals(m)) {
            i++;
            continue;
        }

        if(mod.getCategory().equals(COMBAT) && mod.equals(m)) {
            return i;
        }

    }

    return 0;
}
    public static int placeInListMisc(Module m) {

    int i = 1;

    for(Module mod : Client.getModules()) {
        if(mod.getCategory().equals(MISC) && !mod.equals(m)) {
            i++;
            continue;
        }

        if(mod.getCategory().equals(MISC) && mod.equals(m)) {
            return i;
        }

    }

    return 0;
}

}

And the gui:

package sonikhack.render;

import org.lwjgl.input.Keyboard;

import sonikhack.module.Category;
import sonikhack.module.Module;

public class Gui extends Module{

    public Gui() {
        super("ClickGui", Keyboard.KEY_RSHIFT, Category.RENDER);
    }

    public void onEnable() {
        mc.displayGuiScreen(new ClickGui());
        toggle();
    }

}


问:
WinForms - changing the bindingsource/datasource of a control at runtime?
I have a Winforms app with a BindingSource component and its DataSource is set to a DataSource that I created for a custom data object.  Also on the form are several controls that are bound to various properties of the object exposed through the BindingSource.  Many of these controls are comboboxes and will display values with a backing enum so I'm setting the DataSource for these controls like this:

```<code>        comboBox1.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.EnumValues)), null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";
</code>```

This is all working well enough but I have two comboboxes which I need to be able to change at runtime to display other values (with a different back enum).  In these two cases, I'm creating the initial bindings and datasource in code like this:

```<code>        comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName1", true));
        comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.FirstSetOfEnumValues)), null);
        comboBox2.DisplayMember = "Value";
        comboBox2.ValueMember = "Key";
</code>```

...and then when I need comboBox2 to bind to and display different values, I do this:

```<code>        comboBox2.DataBindings.Clear();
        comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName2", true));
        comboBox2.DataSource = null;
        comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.SecondSetOfEnumValues)), null);
        comboBox2.DisplayMember = "Value";
        comboBox2.ValueMember = "Key";
</code>```

As best I can tell, this is working properly, but it's ugly and there has got to be a much better way to do this, right?  If you know what it is, I'd love to hear it!  Thanks very much!

答:
If this was a web form, I might suggest having ComboBox2 as two separate ComboBoxes and hide/show the one you need.  Although I appreciate this isn't quite so easy for a WinForm project, unless you're using a flowing layout?

You could add a function to return your data source, based on your enumeration type...  I don't think you need to re-set your DisplayMember and ValueMember properties after calling Clear() (but I may be wrong).

Other than that, I don't think you can simplify it much more.  Although I'd be happy to hear if someone has a better solution :)

ContentLicense: CC BY-SA 3.0

Body:
I have a Winforms app with a BindingSource component and its DataSource is set to a DataSource that I created for a custom data object.  Also on the form are several controls that are bound to various properties of the object exposed through the BindingSource.  Many of these controls are comboboxes and will display values with a backing enum so I'm setting the DataSource for these controls like this:

        comboBox1.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.EnumValues)), null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";

This is all working well enough but I have two comboboxes which I need to be able to change at runtime to display other values (with a different back enum).  In these two cases, I'm creating the initial bindings and datasource in code like this:

        comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName1", true));
        comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.FirstSetOfEnumValues)), null);
        comboBox2.DisplayMember = "Value";
        comboBox2.ValueMember = "Key";

...and then when I need comboBox2 to bind to and display different values, I do this:

        comboBox2.DataBindings.Clear();
        comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName2", true));
        comboBox2.DataSource = null;
        comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.SecondSetOfEnumValues)), null);
        comboBox2.DisplayMember = "Value";
        comboBox2.ValueMember = "Key";

As best I can tell, this is working properly, but it's ugly and there has got to be a much better way to do this, right?  If you know what it is, I'd love to hear it!  Thanks very much!


问:
Dynamically create divs and add to DOM based on array retrieved through Axios API
I would like to iteratively create divs using an array I retrieved through axios.

I would like each array element to be represented by a different div such that the array

```<code>['one','two','three']
</code>```

Would return

```<code><div class="parent">
    <div class="one">one</div>
    <div class="one">two</div>
    <div class="one">three</div>
</div>
</code>```

This is what I have written

```<code>//call back function
function creatingDiv (input) {
  return Object.assign(document.createElement('div'), {className: 'tab', textContent: input});
}

const tabTopics = (topics) => {
  const divTopics = Object.assign(document.createElement('div'), {className: 'topics'});
  divTopics.appendChild(topics);
  return divTopics
}
const cssSelector = document.querySelector('.parent')
axios.get('http://localhost:5000/api/topics')
  .then((resp) => {
    const topicsData = tabTopics(creatingDiv(resp.data.topics))
    cssSelector.appendChild(topicsData)
})
</code>```

This is the structure of data in my url

```<code>{"topics":["javascript","bootstrap","technology","jquery","node.js"]}
</code>```

My solution returns one div with each element comma separated.

答:
Can you try this way? Because the data you receive is transmitted to the function as an array, but the working structure was not suitable for array.

function creatingDiv(input) {
  const divArr = []
  for (let i = 0; i < input.length; i++) {
    divArr.push(Object.assign(document.createElement('div'), {
      className: input[i],
      textContent: input[i]
    }))
  }
  return divArr
}

const tabTopics = (topics) => {
  const divTopics = Object.assign(document.createElement('div'), {
    className: 'topics'
  });
  for (let i = 0; i < topics.length; i++) {
    divTopics.appendChild(topics[i]);
  }

  return divTopics
}
const cssSelector = document.querySelector('.parent')

axios.get('http://localhost:5000/api/topics')
  .then((resp) => {
    const topicsData = tabTopics(creatingDiv(resp.data.topics))
    cssSelector.appendChild(topicsData)
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent"></div></code>```

Body:
I would like to iteratively create divs using an array I retrieved through axios.

I would like each array element to be represented by a different div such that the array

['one','two','three']

Would return

one

two

three

This is what I have written

//call back function
function creatingDiv (input) {
  return Object.assign(document.createElement('div'), {className: 'tab', textContent: input});
}

const tabTopics = (topics) => {
  const divTopics = Object.assign(document.createElement('div'), {className: 'topics'});
  divTopics.appendChild(topics);
  return divTopics
}
const cssSelector = document.querySelector('.parent')
axios.get('http://localhost:5000/api/topics')
  .then((resp) => {
    const topicsData = tabTopics(creatingDiv(resp.data.topics))
    cssSelector.appendChild(topicsData)
})

This is the structure of data in my url

{"topics":["javascript","bootstrap","technology","jquery","node.js"]}

My solution returns one div with each element comma separated.

Body:
Can you try this way? Because the data you receive is transmitted to the function as an array, but the working structure was not suitable for array.

function creatingDiv(input) {
  const divArr = []
  for (let i = 0; i < input.length; i++) {
    divArr.push(Object.assign(document.createElement('div'), {
      className: input[i],
      textContent: input[i]
    }))
  }
  return divArr
}

const tabTopics = (topics) => {
  const divTopics = Object.assign(document.createElement('div'), {
    className: 'topics'
  });
  for (let i = 0; i < topics.length; i++) {
    divTopics.appendChild(topics[i]);
  }

  return divTopics
}
const cssSelector = document.querySelector('.parent')

axios.get('http://localhost:5000/api/topics')
  .then((resp) => {
    const topicsData = tabTopics(creatingDiv(resp.data.topics))
    cssSelector.appendChild(topicsData)
  })

<div class="parent"></div>


问:
How to click on element which contains a credit card number that changes each time with Selenium Python
I have a problem to find element on credit card payment form, which contains a number that changes each time, so please help me to find the way to do it.

This is the element:

```<code><input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">
</code>```

答:
This HTML...

```<code><input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">
</code>```

...indicates a Creditcard Number field.

Generally Creditcard Number fields are within an . Hence to access the Creditcard Number field you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following locator strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe_css")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-fieldtype='encryptedCardNumber'][aria-label='Champ du numéro de carte']"))).send_keys("1234567890")
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"iframe_xpath")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-fieldtype='encryptedCardNumber' and @aria-label='Champ du numéro de carte']"))).send_keys("1234567890")
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a couple of relevant discussions in:

How to enter date in the credit card number field using Selenium and Python?

Switch to an iframe through Selenium and python

Body:
I have a problem to find element on credit card payment form, which contains a number that changes each time, so please help me to find the way to do it.

This is the element:

<input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">

Body:
This HTML...

<input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">

...indicates a Creditcard Number field.

Generally Creditcard Number fields are within an <iframe>. Hence to access the Creditcard Number field you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following locator strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe_css")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-fieldtype='encryptedCardNumber'][aria-label='Champ du numéro de carte']"))).send_keys("1234567890")

Using XPATH:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"iframe_xpath")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-fieldtype='encryptedCardNumber' and @aria-label='Champ du numéro de carte']"))).send_keys("1234567890")

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

How to enter date in the credit card number field using Selenium and Python?

Switch to an iframe through Selenium and python


问:
HTML5 video fallback when all types unsupported
In the HTML5 spec, it suggests you put fallback material in the <video> tag for older browsers that do not support it.

```<code><video width="400" controls>
    <source src="mov_bbb.mp4" type="video/mp4">
    <source src="mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
</video>
</code>```

However, I cannot find anything for fallbacks when all source types are unsupported. For instance, my Chromium browser cannot play video/mp4, but it can play video/ogg. So I would expect this to render the fallback text.

```<code><video width="400" controls>
    <source src="mov_bbb.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
</video>
</code>```

Instead, I just get a video player with nothing in it because it can't load the mp4 file.

Is there a way to have a fallback in HTML 5 video when there is no usable video source? I am aware that the fallback I was attempting is only for old browsers, but I still need a fallback for no available source.

答:
It's mentioned in the specs a way to fallback.

"listen to the error event on the last source element and trigger fallback behavior"

```<code><div>
 <video width="400" controls>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg"
         onerror="parentNode.parentElement.innerText = 'Your browser does not support the video codec' ">
 </video>
</div>
</code>```

Body:
In the HTML5 spec, it suggests you put fallback material in the <video> tag for older browsers that do not support it.

<video width="400" controls>
    <source src="mov_bbb.mp4" type="video/mp4">
    <source src="mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
</video>

However, I cannot find anything for fallbacks when all source types are unsupported. For instance, my Chromium browser cannot play video/mp4, but it can play video/ogg. So I would expect this to render the fallback text.

<video width="400" controls>
    <source src="mov_bbb.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
</video>

Instead, I just get a video player with nothing in it because it can't load the mp4 file.

Is there a way to have a fallback in HTML 5 video when there is no usable video source? I am aware that the fallback I was attempting is only for old browsers, but I still need a fallback for no available source.

Body:
It's mentioned in the specs a way to fallback.

"listen to the error event on the last source element and trigger fallback behavior"

<div>
 <video width="400" controls>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg"
         onerror="parentNode.parentElement.innerText = 'Your browser does not support the video codec' ">
 </video>
</div>


问:
How to add to eventListener (which deletes item) function that shows the text of this item somewhere else on the page?(JavaScript)
I would like to ask how to add to the eventListener
which deletes item (by accesing its class)
the function that makes this item visible in the other
place on the website.

Code:

const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');

const generateTemplate = todo => {
  const html = `

    ${todo}

`;
  list.innerHTML += html;
};

addForm.addEventListener('submit', e => {
  e.preventDefault();
  const todo = addForm.add.value.trim();
  if (todo.length) {
    generateTemplate(todo);
    addForm.reset();
  }
});

list.addEventListener('click', e => {
  console.log(e);
  if (e.target.classList.contains('delete')) {
    // how to add here the function which apart from deleting the item
    //can show in the other place (somewhere below)
    e.target.parentElement.remove();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #2a0fd7;
  ;
}

.container {
  max-width: 400px;
}

input[type=text],
input[type=text]:focus {
  color: #fff;
  border: none;
  background: rgba(0, 0, 0, 0.2);
  max-width: 400px;
}

.todos li {
  background: #6c6788;
}

.delete {
  cursor: pointer;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">

        play mariokart

    <form class="add text-center my-4">
      Add a new todo...
      <input class="form-control m-auto" type="text" name="add" />
    </form>

```

答:
You are missing the closing tag
 just before

Body:
I would like to ask how to add to the eventListener
which deletes item (by accesing its class)
the function that makes this item visible in the other
place on the website.

Code:

const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');

const generateTemplate = todo => {
  const html = `

    ${todo}

`;
  list.innerHTML += html;
};

addForm.addEventListener('submit', e => {
  e.preventDefault();
  const todo = addForm.add.value.trim();
  if (todo.length) {
    generateTemplate(todo);
    addForm.reset();
  }
});

list.addEventListener('click', e => {
  console.log(e);
  if (e.target.classList.contains('delete')) {
    // how to add here the function which apart from deleting the item
    //can show in the other place (somewhere below)
    e.target.parentElement.remove();
  }
});

body {
  background: #2a0fd7;
  ;
}

.container {
  max-width: 400px;
}

input[type=text],
input[type=text]:focus {
  color: #fff;
  border: none;
  background: rgba(0, 0, 0, 0.2);
  max-width: 400px;
}

.todos li {
  background: #6c6788;
}

.delete {
  cursor: pointer;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">

        play mariokart

    <form class="add text-center my-4">
      Add a new todo...
      <input class="form-control m-auto" type="text" name="add" />
    </form>

Body: You are missing the closing tag </div> just before <script src="app.js"></script>


问:
Reduce Calls to Details API
if i developed API that return list of offers(v1/offers), or it return details for specific offer(v1/offers/12345), is it a good practice to return all offers details when calling /offers list to mobile? to Reduce calls for Offer Details API?, so instead of calling v1/offers/12345, all details for 12345 will be returned when calling v1/offers
thanks</p>

答:
REST does not dictate how to solve this.

It is perfectly okay for a REST API to declare a query parameter or HTTP header by which the API client can declare the required level of detail (e.g. minimal / compact / detailed).

This prevents underfetching (where the client first gets the list of offer IDs and then has to fetch every individual offer) as well as overfetching (returning details of each offer that the client wasn't even interested in) but it requires the API client to take this decision. Whether that is "good" or not depends on how many API clients you have and how different their usage requirements are.

Title: Reduce Calls to Details API


问:
Typescript interface extends two component types
So this will output an <input> element - everything works perfectly:

```<code>interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  error?: FieldError;
  icon?: string;
  id: string;
  register?: UseFormRegisterReturn;
}

const StyledInputComponent = styled.input`
...
`

const MyComponent = ({
  error,
  icon,
  id,
  register,
  onChange,
  ...props
}: InputProps) => {
  return (
    <StyledInputComponent
     hasError={!!error}
     id={id}
     onChange={onChange}
     placeholder={placeholder}
     type={type}
     {...register}
     {...props}
    />
  });
};
</code>```

I now need to be able to have the consuming component choose between an <input> and a <textarea>.

The problem I have is that (I think) I need to extend the interface further like this:

```<code>interface InputProps extends React.InputHTMLAttributes<HTMLInputElement>, React.InputHTMLAttributes<HTMLTextAreaElement> {
  error?: FieldError;
  icon?: string;
  id: string;
  inputType?: "input" | "textarea";
  register?: UseFormRegisterReturn;
}
</code>```

And I'm just using the new inputType prop to switch between outputted components:

```<code>{ inputType === "input" &&
  <StyledInputComponent
   hasError={!!error}
   id={id}
   onChange={onChange}
   placeholder={placeholder}
   type={type}
   {...register}
   {...props}
  />
}
{ inputType === "textarea" &&
 <StyledTextAreaComponent
  hasError={!!error}
  id={id}
  onChange={onChange}
  placeholder={placeholder}
  rows={4}
  {...register}
  {...props}
 />
}
</code>```

However, trying to extend the interface for both an <input> and a <textarea> has lead to numerous errors, all along these lines:

What's the right way to go about resolving this?

答:
I've tried your solution, but I have some problems when returning an input text or a textarea

```<code>function MyComponent<T extends 'input' | 'textarea'>(props: InputProps<T>) {
  const {inputType, ...rest} = props;

  if (inputType === "input") {
    return <input
//          ^error
      type={"text"}
      {...rest}
    />
  }

  if (inputType === "textarea") {
    return <textarea
//          ^error
      {...rest}
    />
  }

  return null
}
</code>```

This are the returned errors:

```<code>Type '{ type: "text"; } & Omit<InputProps<T>, "inputType">' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
  Type '{ type: "text"; } & Omit<InputProps<T>, "inputType">' is not assignable to type 'ClassAttributes<HTMLInputElement>'.
    Types of property 'ref' are incompatible.
      Type 'InputProps<T>["ref"] | undefined' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
</code>```

playground with error

I can solve the problem if the rest variable is casted to JSX.IntrinsicElements["input"] or JSX.IntrinsicElements["textarea"]... but I don't think is the best solution... Any alternative?

playground solved casting the rest variable

Body:
So this will output an <input> element - everything works perfectly:

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  error?: FieldError;
  icon?: string;
  id: string;
  register?: UseFormRegisterReturn;
}

const StyledInputComponent = styled.input`
...
`

const MyComponent = ({
  error,
  icon,
  id,
  register,
  onChange,
  ...props
}: InputProps) => {
  return (

Body:
I've tried your solution, but I have some problems when returning an input text or a textarea

function MyComponent<T extends 'input' | 'textarea'>(props: InputProps<T>) {
  const {inputType, ...rest} = props;

  if (inputType === "input") {
    return <input
//          ^error
      type={"text"}
      {...rest}
    />
  }

  if (inputType === "textarea") {
    return <textarea
//          ^error
      {...rest}
    />
  }

  return null
}

This are the returned errors:

Type '{ type: "text"; } & Omit<InputProps<T>, "inputType">' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
  Type '{ type: "text"; } & Omit<InputProps<T>, "inputType">' is not assignable to type 'ClassAttributes<HTMLInputElement>'.
    Types of property 'ref' are incompatible.
      Type 'InputProps<T>["ref"] | undefined' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.

<a href="https://www.typescriptlang.org/play?ssl=13&ssc=1&pln=14&pc=1#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wChSYBPMJOASQDswBXGABRzAGcAeAFThIAHjCQMAJlwLAmrfHAA%20BUSJREU%20AHxwAvHADepOHBksYfakgD8ALjh8A3KQC%20cAGRwAUgGUAGgDpGGCgZLmA0AFEAGyQQMRguAG0%20AF1yTGYGDGAIBjgAWUoAYVxIBnj%20QRExSWlZGHklfBUYNVQtAAowTi47RjMOCG5%20TQBKAyM4NFyueH1TVgsaABo4f3WiWdc9bqGuJ0ngTDgOhfNLXR09ACIz6-HDY2MiGGYoPJ4zyae4KhodfTXFrXZzfJ76db%20TYwUE-AD0mkmoMOx1O9SWtCuNxabRQ9wMxjBLzeHxx6jBxghGyQWzBCKRk0mxPecAYzCiURc5DhcNZEF%20FyQUBwUC4pGmDFmvxpMH6rF0cB4hRK4Fy8RM6MsOnwZ3kaAAFkg0ABrJDiOD0iVS0SzPjCVrqBVK4qlNUMeBnDHasntOA4ADuXABAEYAAyuemkHkCmiCYXQVZoFAMZpwZhcWhnOC7MBwXJwFDS1Tkq3wG0wABCKHEg24TuVrvK7o1Zi9zXtuL1hpNZotiOjP0HQ%20HI9HY-HcAAejHaEKRUA" rel="nofollow noreferrer">playground with error

I can solve the problem if the rest variable is casted to JSX.IntrinsicElements["input"] or JSX.IntrinsicElements["textarea"]... but I don't think is the best solution... Any alternative?

<a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wChSYBPMJOASQDswBXGABRzAGcAeAFThIAHjCQMAJlwLAmrfHAA%20BUSJREU%20AHxwAvHADepOHBksYfakgD8ALjh8A3KQC%20cAGRwAUgGUAGgDpGGCgZLmA0AFEAGyQQMRguAG0%20AF1yTGYGDGAIBjgAWUoAYVxIBnj%20QRExSWlZGHklfBUYNVQtAAowTi47RjMOCG5%20TQBKAyM4NFyueH1TVgsaABo4f3WiWdc9bqGuJ0ngTDgOhfNLXR09ACIz6-HDY2MiGGYoPJ4zyae4KhodfTXFrXZzfJ76db%20TbwFBSHwBIIhBhhSIxOIMBKJW71a4pUE-AD0mkmoMOx1O9SWtCuNxabRQ9wMxjBLzeHzp6jBxghGyQs2MsK8fkCGKRKOisXiSSBwla6lx%20KeRJJk0mrPecAYzCiURc5AJBM1EF%20FyQUBwUC4pGmyPgolm-VYujgPEKJXAuXiJkplh0%20DO8jQAAskGgANZIcRwZU2-n28yy%20nO13FUqejHesxUv0c9pwHAAdy4AIAjAAGVzK0gGk00QTm6CrNAoBjNODMLi0M5wXZgOC5OAoX6Jzmxu18mAAIRQ4kG3GTbrT5QzZ2zzRHeeDoYjUeVNZ%20B8PR%20PJ9PZ7gAD1a7QzRagA" rel="nofollow noreferrer">playground solved casting the rest variable


问:
keras fit does not return loss history for validation set
Why, when passing the validation_split parameter to the fit method, the history.history dictionary contains val_loss. And, when passing the validation_data parameter to the fit method, the history.history dictionary does not contain the key val_loss?

(1)

```<code>model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss='mse')
history = model.fit(
    x=[x1_train, x2_train],  # i have two inputs
    y=y_train,
    # ...
    validation_split=0.2)
history.history.keys()  # --> dict_keys(['loss', 'val_loss'])
</code>```

(2)

```<code>model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss='mse')
history = model.fit(
    x=[x1_train, x2_train],
    y=y_train,
    # ...
    validation_data=([x1_val, x2_val], y_val))
history.history.keys()  # --> dict_keys(['loss'])
</code>```

答: The problem was that the input for validation_data was structured incorrectly, you can't pass both a list with x1_val and x2_val and then y_val. Take a look at the documentation here: https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit and this video that explains how to create a validation dataset for keras: https://www.youtube.com/watch?v=dzoh8cfnvnI&ab_channel=deeplizard

Body:
Why, when passing the validation_split parameter to the fit method, the history.history dictionary contains val_loss. And, when passing the validation_data parameter to the fit method, the history.history dictionary does not contain the key val_loss?

(1)

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss='mse')
history = model.fit(
    x=[x1_train, x2_train],  # i have two inputs
    y=y_train,
    # ...
    validation_split=0.2)
history.history.keys()  # --> dict_keys(['loss', 'val_loss'])

(2)

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss='mse')
history = model.fit(
    x=[x1_train, x2_train],
    y=y_train,
    # ...
    validation_data=([x1_val, x2_val], y_val))
history.history.keys()  # --> dict_keys(['loss'])


问:
Using Python Regex how can I specify beginning and/or end word and only any digits in the middle?
I need to match 'words' (string of characters with no spaces) that might have the word near at the beginning and/or the end and have only digits in the middle.

Examples: near3 4near near2near

It should not match words like nearing3 4nearsighted near3ness nearsighted

I tried this: x = re.match(r"((\bnear)|(near\b))(\d)", txt)
It works for this word: near3 and this word: near4near but not for this word 2near

答:
You can match optional near followed by digits and near OR match near and  digits using an alternation using the pipe |

You can surround the alternation with a non capture group and add word boundaries \b at both sides of the pattern to prevent a partial word match.

If you want to match a single digit, you can use only \d instead.

```<code>\b(?:(?:near)?\d+near|near\d+)\b
</code>```

Regex demo

Body:
You can match optional near followed by digits and near OR match near and  digits using an alternation using the pipe |

You can surround the alternation with a non capture group and add word boundaries \b at both sides of the pattern to prevent a partial word match.

If you want to match a single digit, you can use only \d instead.

\b(?:(?:near)?\d+near|near\d+)\b

Regex demo


问:
How to override a base class' DB connection string?
I have a base class (written using C#.net) which uses datasets to pull data from DB and the connection string is in App.config file. So after writing the base class it has been compiled into dll.

And to use this base class for different project I have to override the DB connection string, so first is it possible to do and if possible, can anyone give me an example for it?

答:
I would suggest giving your class an overloaded constructor, like this:

```<code>private readonly string connectionString;

public Foo() : this(Settings.Default.DbConnectionString) {
}

public Foo(string connectionString) {
    this.connectionString = connectionString;
}
</code>```

Then the derived class can just pass the "overridden" connection string into the constructor.

I think this is cleaner than using polymorphism with a virtual property etc - especially as presumably the connection string isn't going to change over the course of the object's lifetime. You're not really changing the behaviour (which is what polymorphism's good for) - you're changing the initialization (which is what constructor parameters are good for).

Body:
I would suggest giving your class an overloaded constructor, like this:

private readonly string connectionString;

public Foo() : this(Settings.Default.DbConnectionString) {
}

public Foo(string connectionString) {
    this.connectionString = connectionString;
}

Then the derived class can just pass the "overridden" connection string into the constructor.

I think this is cleaner than using polymorphism with a virtual property etc - especially as presumably the connection string isn't going to change over the course of the object's lifetime. You're not really changing the behaviour (which is what polymorphism's good for) - you're changing the initialization (which is what constructor parameters are good for).


问:
How can I use regex in python to validate dates in the MM/DD/YYYY format?
I'm working on a project for my beginning python class and it's heavily focused on regex. Part of this project involves using regex to validate the date format MM/DD/YYYY.

My Regex is as follows:

```<code>(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|12\d|3[01])\/(?:1\d{3})
</code>```

I'm having an issue where if I enter a date like

```<code>13/31/1999
</code>```

my regex wont match the first 1, but instead will match

```<code>3/31/1999
</code>```

I'm not sure why this is happening because I'm expecting if the DD starts with a 1, then my regex should only match that 1 followed by either 0,1,2.

Here is a visual representation of my issue

答:
(For the record, this was solved in the comments) Add the caret (^) at the beginning of your regular expression to match the beginning of the string. That should match your requirement:

```<code>^(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|12\d|3[01])\/(?:1\d{3})
</code>```

You can see it working with your examples here.

Body:
I'm working on a project for my beginning python class and it's heavily focused on regex. Part of this project involves using regex to validate the date format MM/DD/YYYY.

My Regex is as follows:

(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|12\d|3[01])\/(?:1\d{3})

I'm having an issue where if I enter a date like

13/31/1999

my regex wont match the first 1, but instead will match

3/31/1999

I'm not sure why this is happening because I'm expecting if the DD starts with a 1, then my regex should only match that 1 followed by either 0,1,2.

Here is a visual representation of my issue

Body:
(For the record, this was solved in the comments) Add the caret (^) at the beginning of your regular expression to match the beginning of the string. That should match your requirement:

^(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|12\d|3[01])\/(?:1\d{3})

You can see it working with your examples here.


问:
How to run docker image in Kubernetes (v1.21) pod for CI/CD scenario?
We're investigating using an AKS cluster to run our Azure Pipeline Agents.

I've looked into tools like Kaniko for building docker images, which should work fine, however some of our pipelines run docker commands, e.g. we run checkov using the docker image, but I've struggled to find any solution that seems to work, given the deprecation of the docker shim in kubernetes.

The obvious solution would be add those tools that we currently run from docker into our agent image but this isn't a great solution as it will mean that any time a developer wants to run a tool like that we would need to modify the new image, which is less than ideal.

Any suggestions?

Thanks

答:
You could just use nerdctl or crictl for your commands and even create an alias for that (specially wiht nerdctl) = alias docker="nerdctl"

As docker images or better said container images using the OCI image format you will have no issues running them with containerd or cri-o.