问:
animatedPositioned is not animated on Flutter
I need to animate widget and I used AnimatedPositioned. but not animated. just change position without animate

Full Code

```<code>Column(
      children: <Widget>[
        Container(
          height: 50,
            width: width,
            color: Palette.white,
          child: Padding(
            padding: const EdgeInsets.only(left:20.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 200,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Palette.lightSilver,
                    borderRadius: BorderRadius.all(Radius.circular(20))
                  ),
                  child: Stack(
                    children: <Widget>[
                      AnimatedPositioned(
                        right:check? 0:null,
                          left:check?null: 0,
                          child: InkWell(
                            onTap: (){
                              setState(() =>
                                check = !check
                              );
                            },
                            child: Container(
                              width: 110,
                              height: 40,
                              decoration: BoxDecoration(
                                  color: Palette.darkSilver2,
                                  borderRadius: BorderRadius.all(Radius.circular(20))
                              ),
                            ),
                          ),
                        duration: const Duration(milliseconds: 50000),
                        curve: Curves.bounceOut,
                      )
                    ],
                  ),
                ),
              ],
            ),
          )
        ),
</code>```

答:
You can animate using only left or right property of animated container.</p>

```<code>Container(
                  width: 200,
                  height: 60,
                  decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.all(Radius.circular(20))),
                  child: Stack(
                    children: <Widget>[
                      AnimatedPositioned(
                        left: check
                            ? 90
                            : 0, // here 90 is (200(above container)-110(container which is animating))
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              check = !check;
                            });
                          },
                          child: Container(
                            width: 110,
                            height: 40,
                            decoration: BoxDecoration(
                                color: Colors.teal,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(20))),
                          ),
                        ),
                        duration: const Duration(seconds: 1),
                        curve: Curves.bounceOut,
                      ),
                    ],
                  ),
                ),
</code>```

Body:
I need to animate widget and I used AnimatedPositioned. but not animated. just change position without animate

Full Code

Column(
      children: <Widget>[
        Container(
          height: 50,
            width: width,
            color: Palette.white,
          child: Padding(
            padding: const EdgeInsets.only(left:20.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 200,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Palette.lightSilver,
                    borderRadius: BorderRadius.all(Radius.circular(20))
                  ),
                  child: Stack(
                    children: <Widget>[
                      AnimatedPositioned(
                        right:check? 0:null,
                          left:check?null: 0,
                          child: InkWell(
                            onTap: (){
                              setState(() =>
                                check = !check
                              );
                            },
                            child: Container(
                              width: 110,
                              height: 40,
                              decoration: BoxDecoration(
                                  color: Palette.darkSilver2,
                                  borderRadius: BorderRadius.all(Radius.circular(20))
                              ),
                            ),
                          ),
                        duration: const Duration(milliseconds: 50000),
                        curve: Curves.bounceOut,
                      )
                    ],
                  ),
                ),
              ],
            ),
          )
        ),

Body:
You can animate using only left or right property of animated container.

Container(
                  width: 200,
                  height: 60,
                  decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.all(Radius.circular(20))),
                  child: Stack(
                    children: <Widget>[
                      AnimatedPositioned(
                        left: check
                            ? 90
                            : 0, // here 90 is (200(above container)-110(container which is animating))
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              check = !check;
                            });
                          },
                          child: Container(
                            width: 110,
                            height: 40,
                            decoration: BoxDecoration(
                                color: Colors.teal,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(20))),
                          ),
                        ),
                        duration: const Duration(seconds: 1),
                        curve: Curves.bounceOut,
                      ),
                    ],
                  ),
                ),


来源: stackexchange

问:
FileNotFoundError: [WinError 2] The system cannot find the file specified when using export_graphviz
I trained my model using Random Forest and I want to Visualize the Decision Tree. Then, I want to convert the export_graphviz to a png file.

```<code>from subprocess import call

# Convert to png
call(['dot', '-Tpng', 'tree_from_optimized_forest.dot', '-o', 'tree_from_optimized_forest.png', '-Gdpi=200'])
Image('tree_from_optimized_forest.png')
</code>```

The output is

```<code>---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-95-f836aa32a65b> in <module>
      2
      3 # Convert to png
----> 4 call(['dot', '-Tpng', 'tree_from_optimized_forest.dot', '-o', 'tree_from_optimized_forest.png', '-Gdpi=200'])
      5 Image('tree_from_optimized_forest.png')

~\Anaconda3\lib\subprocess.py in call(timeout, *popenargs, **kwargs)
    321     retcode = call(["ls", "-l"])
    322     """
--> 323     with Popen(*popenargs, **kwargs) as p:
    324         try:
    325             return p.wait(timeout=timeout)

~\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

~\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
   1176                                          env,
   1177                                          os.fspath(cwd) if cwd is not None else None,
-> 1178                                          startupinfo)
   1179             finally:
   1180                 # Child is launched. Close the parent's copy of those pipe

FileNotFoundError: [WinError 2] The system cannot find the file specified

</code>```

How to solve the error?

答:
I solve it using pydot library</p>

```<code>import pydot

(graph,) = pydot.graph_from_dot_file('tree_real_data.dot')
graph.write_png('somefile.png')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I trained my model using Random Forest and I want to Visualize the Decision Tree. Then, I want to convert the export_graphviz to a png file.

from subprocess import call

# Convert to png
call(['dot', '-Tpng', 'tree_from_optimized_forest.dot', '-o', 'tree_from_optimized_forest.png', '-Gdpi=200'])
Image('tree_from_optimized_forest.png')

The output is

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-95-f836aa32a65b> in <module>
      2
      3 # Convert to png
----> 4 call(['dot', '-Tpng', 'tree_from_optimized_forest.dot', '-o', 'tree_from_optimized_forest.png', '-Gdpi=200'])
      5 Image('tree_from_optimized_forest.png')

~\Anaconda3\lib\subprocess.py in call(timeout, *popenargs, **kwargs)
    321     retcode = call(["ls", "-l"])
    322     """
--> 323     with Popen(*popenargs, **kwargs) as p:
    324         try:
    325             return p.wait(timeout=timeout)

~\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

~\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
   1176                                          env,
   1177                                          os.fspath(cwd) if cwd is not None else None,
-> 1178                                          startupinfo)
   1179             finally:
   1180                 # Child is launched. Close the parent's copy of those pipe

FileNotFoundError: [WinError 2] The system cannot find the file specified

How to solve the error?

Body:
I solve it using pydot library

import pydot

(graph,) = pydot.graph_from_dot_file('tree_real_data.dot')
graph.write_png('somefile.png')


问:
Why the loop becomes infinite?
How to get out of an infinite loop?

```<code>unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}
</code>```

Help, please.

Thank you!

答:
As i is of type unsigned char which is of size 1byte and can hold 0 to 255 values.
If you increment i after 255 (i.e 0xFF) expectation is i to become 256 but i hold value 0 due overflow. (i.e in 256 is equivalent to 0x100 and only lower byte value will be available in i)

In order to run loop from 0 to 260 you need to change the type of i which can hold value beyond 255.

short int or int is preferable,

```<code>unsigned char half_limit = 130;

for (int i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}
</code>```

Title: Why the loop becomes infinite?

Body:
How to get out of an infinite loop?

unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}

Help, please.

Thank you!

Body:
As i is of type unsigned char which is of size 1byte and can hold 0 to 255 values.
If you increment i after 255 (i.e 0xFF) expectation is i to become 256 but i hold value 0 due overflow. (i.e in 256 is equivalent to 0x100 and only lower byte value will be available in i)

In order to run loop from 0 to 260 you need to change the type of i which can hold value beyond 255.

short int or int is preferable,

unsigned char half_limit = 130;

for (int i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}


问:
Access element from external XML file in Android
I am developing an Android Application.I have create an another XML file for layout:-

Chatfile.XML

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/suitableblack"
    android:orientation="vertical">

    <Button
    android:id="@+id/signout"
    android:layout_width="422dp"
    android:layout_height="64dp"
    android:text="Button" />

<ListView
    android:id="@+id/Msgdisplay"
    android:layout_width="374dp"
    android:layout_height="593dp"
    android:layout_below="@id/signout"
    android:layout_marginLeft="20dp"
    android:forceDarkAllowed="false" />

<LinearLayout
    android:layout_width="390dp"
    android:layout_height="83dp"
    android:layout_below="@id/Msgdisplay"
    android:layout_marginLeft="20dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/Msginput"
        android:layout_width="482dp"
        android:layout_height="67dp"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <Button
        android:id="@+id/Sendbtn"
        android:layout_width="match_parent"
        android:layout_height="68dp"
        android:layout_weight="1"
        android:text="Button" />
</LinearLayout>
</code>```

So I want to access the button with ID-Sendbtn in  my MainActivity.java file and the code for that part is here:-

```<code>    Button sendbtn=findViewById(R.id.Sendbtn);
    sendbtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          String msg=message.getText().toString();
          if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
            FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
        }

    }
  });
</code>```

But whenever I run this code it gives me following error:-

```<code> Process: com.example.anochatzone, PID: 18398
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anochatzone/com.example.anochatzone.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.anochatzone.MainActivity.onCreate(MainActivity.java:87)
    at android.app.Activity.performCreate(Activity.java:6679)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

My main question is how can I access the button from chatfile.xml in my MainActivity.java

Update
MainActivity.java

```<code>  package com.example.anochatzone;

    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.text.Layout;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.*;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.database.FirebaseDatabase;

    import java.util.Objects;

    public class MainActivity extends AppCompatActivity {
    private FirebaseAuth authenticate;
        private String email_str="";
     private String password_str="";
    private EditText email,password,message;
    private Button loginbtn,resetbtn,sendbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
            Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title bar
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
            setContentView(R.layout.activity_main);
           email=findViewById(R.id.EmailInput);
           password=findViewById(R.id.Passwordinput);
           message=findViewById(R.id.Msginput);

    loginbtn=findViewById(R.id.Loginbtn);
           resetbtn= findViewById(R.id.ResetBtn);
       sendbtn=findViewById(R.id.Sendbtn);

        authenticate=FirebaseAuth.getInstance();

       loginbtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
     Toast.makeText(getApplicationContext(),"Please wait while we are processing your request........",Toast.LENGTH_SHORT).show();
                email_str=email.getText().toString();
                password_str=password.getText().toString();
            if(email_str.length()==0||password_str.length()==0)
            {
                Toast.makeText(getBaseContext(),"Please check email and password",Toast.LENGTH_LONG).show();
            }
            else
            {
                authenticate.signInWithEmailAndPassword(email_str,password_str).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                       if(task.isSuccessful()){
    Log.d("User display name" , FirebaseAuth . getInstance() . getCurrentUser().getDisplayName());
                         Toast.makeText(getApplicationContext(),"Welcome "+email_str+" you have sucessfully logged in",Toast.LENGTH_LONG).show();
                         setContentView(R.layout.chatfile);

                       }
                       else
                       {
                           Toast.makeText(getApplicationContext(),"Failed to sign in .Please check internet connection or try again later",Toast.LENGTH_SHORT).show();
                       }

                    }
                });
            }
           }
       });

    sendbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String msg=message.getText().toString();
        if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
             FirebaseDatabase.getInstance().getReference().push().setValue(new        chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()))    ;
        }
    }
    });
    }
}
</code>```

答:
Put below code in your activity_main.xml

```<code><include
    layout="@layout/chatfile"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Now you can access the button in Your MainActivity.

Body:
I am developing an Android Application.I have create an another XML file for layout:-

Chatfile.XML

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/suitableblack"
    android:orientation="vertical">

    <Button
    android:id="@+id/signout"
    android:layout_width="422dp"
    android:layout_height="64dp"
    android:text="Button" />

<ListView
    android:id="@+id/Msgdisplay"
    android:layout_width="374dp"
    android:layout_height="593dp"
    android:layout_below="@id/signout"
    android:layout_marginLeft="20dp"
    android:forceDarkAllowed="false" />

<LinearLayout
    android:layout_width="390dp"
    android:layout_height="83dp"
    android:layout_below="@id/Msgdisplay"
    android:layout_marginLeft="20dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/Msginput"
        android:layout_width="482dp"
        android:layout_height="67dp"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <Button
        android:id="@+id/Sendbtn"
        android:layout_width="match_parent"
        android:layout_height="68dp"
        android:layout_weight="1"
        android:text="Button" />
</LinearLayout>

So I want to access the button with ID-Sendbtn in  my MainActivity.java file and the code for that part is here:-

    Button sendbtn=findViewById(R.id.Sendbtn);
    sendbtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          String msg=message.getText().toString();
          if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
            FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
        }

    }
  });

But whenever I run this code it gives me following error:-

 Process: com.example.anochatzone, PID: 18398
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anochatzone/com.example.anochatzone.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.anochatzone.MainActivity.onCreate(MainActivity.java:87)
    at android.app.Activity.performCreate(Activity.java:6679)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

My main question is how can I access the button from chatfile.xml in my MainActivity.java

Update
MainActivity.java

  package com.example.anochatzone;

    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.text.Layout;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.*;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.database.FirebaseDatabase;

    import java.util.Objects;

    public class MainActivity extends AppCompatActivity {
    private FirebaseAuth authenticate;
        private String email_str="";
     private String password_str="";
    private EditText email,password,message;
    private Button loginbtn,resetbtn,sendbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
            Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title bar
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
            setContentView(R.layout.activity_main);
           email=findViewById(R.id.EmailInput);
           password=findViewById(R.id.Passwordinput);
           message=findViewById(R.id.Msginput);

    loginbtn=findViewById(R.id.Loginbtn);
           resetbtn= findViewById(R.id.ResetBtn);
       sendbtn=findViewById(R.id.Sendbtn);

        authenticate=FirebaseAuth.getInstance();

       loginbtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
     Toast.makeText(getApplicationContext(),"Please wait while we are processing your request........",Toast.LENGTH_SHORT).show();
                email_str=email.getText().toString();
                password_str=password.getText().toString();
            if(email_str.length()==0||password_str.length()==0)
            {
                Toast.makeText(getBaseContext(),"Please check email and password",Toast.LENGTH_LONG).show();
            }
            else
            {
                authenticate.signInWithEmailAndPassword(email_str,password_str).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                       if(task.isSuccessful()){
    Log.d("User display name" , FirebaseAuth . getInstance() . getCurrentUser().getDisplayName());
                         Toast.makeText(getApplicationContext(),"Welcome "+email_str+" you have sucessfully logged in",Toast.LENGTH_LONG).show();
                         setContentView(R.layout.chatfile);

                       }
                       else
                       {
                           Toast.makeText(getApplicationContext(),"Failed to sign in .Please check internet connection or try again later",Toast.LENGTH_SHORT).show();
                       }

                    }
                });
            }
           }
       });

    sendbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String msg=message.getText().toString();
        if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
             FirebaseDatabase.getInstance().getReference().push().setValue(new        chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()))    ;
        }
    }
    });
    }
}

Body:
Put below code in your activity_main.xml

<include
    layout="@layout/chatfile"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Now you can access the button in Your MainActivity.


问:
NHibernate HQL distinct and order by
I've recently upgraded from NHibernate 1.2 to 3.1 in an old code base. I've fixed most problems but I'm stuck on this one. (I can't change from HQL to another access method without lots of changes to the codebase).

This wasn't an issue in 1.2, but after the upgrade I'm getting the following problem.

I have the following HQL:

```<code>select distinct c.OwnerUser from Film c order by c.OwnerUser.UserName
</code>```

which results in the error:

```<code>[SQL: select distinct user1_.Id as Id33_, user1_.ApplicationId as Applicat2_33_, user1_.UserName as UserName33_, user1_.LoweredUserName as LoweredU4_33_, user1_.MobileAlias as MobileAl5_33_, user1_.IsAnonymous as IsAnonym6_33_, user1_.LastActivityDate as LastActi7_33_, user1_.CreateDate as CreateDate33_, user1_.CountryCode as CountryC9_33_, user1_.PreferredEditionId as Preferr10_33_ from dbo.tbl_Content film0_ inner join dbo.vw_aspnet_Users_With_Id user1_ on film0_.OwnerUserId=user1_.Id, dbo.vw_aspnet_Users_With_Id user2_ where film0_.discriminator in ('film', 'webcamfilm', 'slideshow') and film0_.OwnerUserId=user2_.Id order by user2_.UserName] ---> System.Data.SqlClient.SqlException: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
</code>```

This code works fine, just with a duplicate entry I don't want.

```<code>select c.OwnerUser from Film c order by c.OwnerUser.UserName
</code>```

How do I write the HQL to get distinct results?

答:
The error in this sql is clause order by user2_.UserName, but user2_.UserName can't be found in the select list, which happens to be a constraint for select distinct query.

Try

select distinct c.OwnerUser,
  c.OwnerUser.UserName from Film c order
  by c.OwnerUser.UserName

then iterate through resulting list and get OwnerUser as (OwnerUser)list[i][0] or similar

ContentLicense: CC BY-SA 3.0

Title: NHibernate HQL distinct and order by

Body:
I've recently upgraded from NHibernate 1.2 to 3.1 in an old code base. I've fixed most problems but I'm stuck on this one. (I can't change from HQL to another access method without lots of changes to the codebase).

This wasn't an issue in 1.2, but after the upgrade I'm getting the following problem.

I have the following HQL:

select distinct c.OwnerUser from Film c order by c.OwnerUser.UserName

which results in the error:

[SQL: select distinct user1_.Id as Id33_, user1_.ApplicationId as Applicat2_33_, user1_.UserName as UserName33_, user1_.LoweredUserName as LoweredU4_33_, user1_.MobileAlias as MobileAl5_33_, user1_.IsAnonymous as IsAnonym6_33_, user1_.LastActivityDate as LastActi7_33_, user1_.CreateDate as CreateDate33_, user1_.CountryCode as CountryC9_33_, user1_.PreferredEditionId as Preferr10_33_ from dbo.tbl_Content film0_ inner join dbo.vw_aspnet_Users_With_Id user1_ on film0_.OwnerUserId=user1_.Id, dbo.vw_aspnet_Users_With_Id user2_ where film0_.discriminator in ('film', 'webcamfilm', 'slideshow') and film0_.OwnerUserId=user2_.Id order by user2_.UserName] ---> System.Data.SqlClient.SqlException: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

This code works fine, just with a duplicate entry I don't want.

select c.OwnerUser from Film c order by c.OwnerUser.UserName

How do I write the HQL to get distinct results?


问:
Is there a way to version ~/.bashrc in-place by git, without copying to a different repo?
I'd like to version ~/.bashrc and ~/.bash_profile using git, best if in-place (at the actual location), rather than creating a new repo and copy the file over and do the versioning there.

Is there a way to do that? I think the difficulty is, if I create a repo at ~, it includes every folder in my home directory and is not desirable.

Is there some way to tell git: version only these files or folder, and disregard everything else and don't consider them to be submodules? If it can be like that, it might be a solution, except it seem like a super big repo to be at the home directory but at the same time ignoring almost everything.

答:
The bare repo approach is another option:

No extra tooling, no symlinks, files are tracked on a version control system, you can use different branches for different computers, you can replicate you configuration easily on new installation.

The technique consists in storing a Git bare repository in a "side" folder (like $HOME/.cfg or $HOME/.myconfig) using a specially crafted alias so that commands are run against that repository and not the usual .git local folder, which would interfere with any other Git repositories around.

Coupled with the alias

```<code>alias config='/usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME'
config config --local status.showUntrackedFiles no
</code>```

You then add only the files you want:

```<code>config add .vimrc
</code>```

Body:
The bare repo approach is another option:

No extra tooling, no symlinks, files are tracked on a version control system, you can use different branches for different computers, you can replicate you configuration easily on new installation.

The technique consists in storing a Git bare repository in a "side" folder (like $HOME/.cfg or $HOME/.myconfig) using a specially crafted alias so that commands are run against that repository and not the usual .git local folder, which would interfere with any other Git repositories around.

Coupled with the alias

alias config='/usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME'
config config --local status.showUntrackedFiles no

You then add only the files you want:

config add .vimrc


问:
How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project
I'm working on a Java project that uses the JNI.  The JNI calls a custom library that I've written myself, let's say mylib.dll, and that depends on a 3rd party library, libsndfile-1.dll.

When I run my program it crashes with

```<code>java.lang.UnsatisfiedLinkError:  C:\...path...\mylib.dll: Can't find dependent libraries.
</code>```

I've searched this site (and others) and I've tried a number of fixes:

I ran dependency walker. DW gave a couple of warnings -- that two libraries required by libsndfile, MPR.DLL and SHLWAPI.DLL, had "unresolved imports" -- but the DW FAQ said that these warnings could be safely ignored.

I fixed the method names in mylib.dll, as suggested here.  The method names had somehow gotten mangled by the compiler, but I added linker flags and the dll method names now match those in my jni header file exactly.

I put all of these DLLs in the same directory -- the same directory as the .jar that calls them -- to ensure that they're on the right PATH.

No dice.

Does anyone have any idea what's going on?

I'm doing my development in Visual Studio 2010 on a MacBook pro (via Parallels). I'm doing my testing in Windows XP on a toshiba laptop.

答:
place the required dlls in folder and set the folder path in PATH environment variable.
make sure updated environment PATH variable is reflected.</p>

Body:
I'm working on a Java project that uses the JNI.  The JNI calls a custom library that I've written myself, let's say mylib.dll, and that depends on a 3rd party library, libsndfile-1.dll.

When I run my program it crashes with

java.lang.UnsatisfiedLinkError:  C:\...path...\mylib.dll: Can't find dependent libraries.

I've searched this site (and others) and I've tried a number of fixes:

I ran dependency walker. DW gave a couple of warnings -- that two libraries required by libsndfile, MPR.DLL and SHLWAPI.DLL, had "unresolved imports" -- but the DW FAQ said that these warnings could be safely ignored.

I fixed the method names in mylib.dll, as suggested here.  The method names had somehow gotten mangled by the compiler, but I added linker flags and the dll method names now match those in my jni header file exactly.

I put all of these DLLs in the same directory -- the same directory as the .jar that calls them -- to ensure that they're on the right PATH.

No dice.

Does anyone have any idea what's going on?

I'm doing my development in Visual Studio 2010 on a MacBook pro (via Parallels). I'm doing my testing in Windows XP on a toshiba laptop.


问:
With Python, how to update multiple Mysql records with a long list of tuples?
I have a Python list that contains hundreds of tuples, and I want to update hundreds of corresponding records in a Mysql table with the data in the tuples. This is what my list of tuples looks like (shortened here):

updated_dates = [(1, '1997-12-29'), (2, '1998-01-05'), (3, '1998-01-12'), (4, '1998-01-19'), (5, '1998-01-26'), (6, '1998-02-02'), (7, '1998-02-09'), (8, '1998-02-16')]

Here is my code in which I attempt to update the Mysql records where the first value in each tuple corresponds with the id of each row to update:

```<code>for id_, date_ in updated_dates:
      sql = "UPDATE table SET date = %s WHERE id = %s"
      db_cursor.executemany(sql, (date_, id_))
      db_connection.commit()
</code>```

The error I receive is:

```<code>for id_, date_ in updated_dates:
ValueError: too many values to unpack (expected 2)
</code>```

I am sorry to ask a bad question, but I have spent much time on this without resolution. How may I update all my Mysql records with the data from the tuples in my list?

Thank you so much for your feedback.

答:
If you're using Python 2, you can use iteritems()

```<code>for id_, date_ in updated_dates.iteritems():
</code>```

Or for Python 3, you can use items().

```<code>for id_, date_ in updated_dates.items():
</code>```

Body:
I have a Python list that contains hundreds of tuples, and I want to update hundreds of corresponding records in a Mysql table with the data in the tuples. This is what my list of tuples looks like (shortened here):

updated_dates = [(1, '1997-12-29'), (2, '1998-01-05'), (3, '1998-01-12'), (4, '1998-01-19'), (5, '1998-01-26'), (6, '1998-02-02'), (7, '1998-02-09'), (8, '1998-02-16')]

Here is my code in which I attempt to update the Mysql records where the first value in each tuple corresponds with the id of each row to update:

for id_, date_ in updated_dates:
      sql = "UPDATE table SET date = %s WHERE id = %s"
      db_cursor.executemany(sql, (date_, id_))
      db_connection.commit()

The error I receive is:

for id_, date_ in updated_dates:
ValueError: too many values to unpack (expected 2)

I am sorry to ask a bad question, but I have spent much time on this without resolution. How may I update all my Mysql records with the data from the tuples in my list?

Thank you so much for your feedback.

Body:
If you're using Python 2, you can use iteritems()

for id_, date_ in updated_dates.iteritems():

Or for Python 3, you can use items().

for id_, date_ in updated_dates.items():


答: You're having an infinite loop because of unsigned char range which is from 0 to 255. So basically, i never reaches 2 * half_limit. i starts from 0 then goes to 255 then goes to 0 again and so on and so forth.

Title: Why the loop becomes infinite?


问:
giving priority to values in an SQL stmt
is there any way i can do a query to specify that I want to give priority to some value?

for instance i have:

```<code>SELECT TOP (20)
  r.MD5, r.Title, r.Link, t.Category, t.tfidf, COUNT(r.MD5) AS matching_terms
FROM
  Resource AS r INNER JOIN tags AS t ON r.MD5 = t.MD5
WHERE
  (t.Category IN ('algorithm', 'k-means', 'statistics', 'clustering', 'science'))

GROUP BY r.MD5, r.Title, r.Link, t.Category, t.tfidf
ORDER BY matching_terms DESC, t.tfidf DESC
</code>```

i want that 'algorithm' is given higher priority when finding results. any ideas?

答:
I'm not sure how high a priority you want to make 'algorithm', but in any case, you can add this to the ORDER BY clause, in order to make it the most important category (all other categories are equally important):

```<code>ORDER BY ..., CASE t.Category = 'algorithm' THEN 0 ELSE 1 END, ...
</code>```

If however your concept of "priority" is somehow correlated with the importance of the matching_terms expression, you could also try something like this (you'd have to nest your above select)

```<code>SELECT TOP(20) FROM (
  [your original select without TOP(20) clause]
)
ORDER BY (matching_terms * CASE t.Category = 'algorithm'
                           THEN 1.5 ELSE 1 END) DESC, t.tfidf DESC
</code>```

But that's just an example to give you an idea.

UPDATE: Following you comment, you can generate a case statement like this:

```<code>ORDER BY CASE t.Category WHEN 'algorithm'  THEN 0
                         WHEN 'k-means'    THEN 1
                         WHEN 'statistics' THEN 2
                         WHEN 'clustering' THEN 3
                         WHEN 'science'    THEN 4 END
</code>```

Or alternatively (especially if your list of categories is large), then you should add a sort field to tags, containing the priority. Then you could simply order by sort

Body:
is there any way i can do a query to specify that I want to give priority to some value?

for instance i have:

SELECT TOP (20)
  r.MD5, r.Title, r.Link, t.Category, t.tfidf, COUNT(r.MD5) AS matching_terms
FROM
  Resource AS r INNER JOIN tags AS t ON r.MD5 = t.MD5
WHERE
  (t.Category IN ('algorithm', 'k-means', 'statistics', 'clustering', 'science'))

GROUP BY r.MD5, r.Title, r.Link, t.Category, t.tfidf
ORDER BY matching_terms DESC, t.tfidf DESC

i want that 'algorithm' is given higher priority when finding results. any ideas?

Body:
I'm not sure how high a priority you want to make 'algorithm', but in any case, you can add this to the ORDER BY clause, in order to make it the most important category (all other categories are equally important):

ORDER BY ..., CASE t.Category = 'algorithm' THEN 0 ELSE 1 END, ...

If however your concept of "priority" is somehow correlated with the importance of the matching_terms expression, you could also try something like this (you'd have to nest your above select)

SELECT TOP(20) FROM (
  [your original select without TOP(20) clause]
)
ORDER BY (matching_terms * CASE t.Category = 'algorithm'
                           THEN 1.5 ELSE 1 END) DESC, t.tfidf DESC

But that's just an example to give you an idea.

UPDATE: Following you comment, you can generate a case statement like this:

ORDER BY CASE t.Category WHEN 'algorithm'  THEN 0
                         WHEN 'k-means'    THEN 1
                         WHEN 'statistics' THEN 2
                         WHEN 'clustering' THEN 3
                         WHEN 'science'    THEN 4 END

Or alternatively (especially if your list of categories is large), then you should add a sort field to tags, containing the priority. Then you could simply order by sort


问:
Linux At Command running docker-compose

Goal: I am trying to schedule a 'docker-compose up' at a scheduled time

Operating System: Linux Ubuntu 18.04

I have tried using the 'at' command in linux but I am trying to set variables and couldn't get it to quite work.

Attempts below:

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above does not run the docker-compose

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above runs docker-compose command immediately but not in 2 minutes
```

<pre class="lang-sh prettyprint-override"><code># run.sh

# SET LOGFILE LOCATION
LOG_FILE="/var/log/at/test.log"

FLIGHT_FILE="flight.yaml" docker-compose up --abort-on-container-exit >> "${LOG_FILE}"
</code>```

If there is a better way than using the 'at' command I am also open to that.

Thank you in advance

答:
in your example (both attempts are the same) only the echo is executed by sudo, at is executed as your user.

options:

run the script on the root's at queue:

```<code>sudo sh -c "echo \"KEY='VALUE' DIRECTION='D' sh /home/user/run.sh \" | at now + 1 min"
</code>```

make at run sudo - works only if you have sudo setup not to ask a password:

```<code>echo "sudo sh -c \"KEY='VALUE' DIRECTION='D' /home/user/run.sh\"" | at now + 2 min
</code>```

configure docker so you don't need sudo

Title: Linux At Command running docker-compose

Body:
Goal: I am trying to schedule a 'docker-compose up' at a scheduled time

Operating System: Linux Ubuntu 18.04

I have tried using the 'at' command in linux but I am trying to set variables and couldn't get it to quite work.

Attempts below:

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above does not run the docker-compose

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above runs docker-compose command immediately but not in 2 minutes

# run.sh

# SET LOGFILE LOCATION
LOG_FILE="/var/log/at/test.log"

FLIGHT_FILE="flight.yaml" docker-compose up --abort-on-container-exit >> "${LOG_FILE}"

If there is a better way than using the 'at' command I am also open to that.

Thank you in advance

Body:
in your example (both attempts are the same) only the echo is executed by sudo, at is executed as your user.

options:

run the script on the root's at queue:

sudo sh -c "echo \"KEY='VALUE' DIRECTION='D' sh /home/user/run.sh \" | at now + 1 min"

make at run sudo - works only if you have sudo setup not to ask a password:

echo "sudo sh -c \"KEY='VALUE' DIRECTION='D' /home/user/run.sh\"" | at now + 2 min

configure docker so you don't need sudo


问:
Select data from multiple tables with same column names and structure using sql
I am get data from a third party database to generate certain reports. The issue is that it keeps on generating a new table every month to insert the same record in same columns in the following manner:

```<code>For December table : Data_12_2019
For January table  : Data_1_2020
For February table : Data_2_2020
For March table    : Data_3_2020 and so on
</code>```

and table data is as following:

```<code>UserId  DLogId  LogDate
1461    1799    2020-01-06 09:07:51.000
1462    1803    2020-01-07 09:29:39.000
1463    1806    2020-01-07 11:43:11.000
1464    1807    2020-01-09 09:16:47.000
1457    1819    2020-01-10 09:00:56.000
</code>```

table2

```<code>UserId  DLogId  LogDate
1466    1853    2020-02-03 09:11:54.000
1468    1831    2020-02-04 09:17:09.000
1470    1833    2020-02-5 09:01:06.000
</code>```

and need output in a single table in following manner:

```<code>UserId  DLogId  LogDate
1461    1799    2020-01-06 09:07:51.000
1462    1803    2020-01-07 09:29:39.000
1463    1806    2020-01-07 11:43:11.000
1464    1807    2020-01-09 09:16:47.000
1457    1819    2020-01-10 09:00:56.000
1466    1853    2020-02-03 09:11:54.000
1468    1831    2020-02-04 09:17:09.000
1470    1833    2020-02-5 09:01:06.000
</code>```

I want to get data placed in above tables and tables that will be generated in future also.
I am seeking a help about how to do it.

答:
You can achieve this using dynamic query. If your table structure is same, you can try like following.

```<code>DECLARE @query AS NVARCHAR(max) = Stuff((SELECT DISTINCT ' ' + 'SELECT * FROM ' + Quotename(name) + ' UNION'
                 FROM
                 (
                  SELECT
                    [name]
                FROM
                    sys.sysobjects
                WHERE
                    [xtype] = 'U'
                    and NAME LIKE 'Data_[0-9][0-9]_[0-9][0-9][0-9][0-9]'
                 )t
                 FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '');

SET @query= substring(@query,0,len(@query)-5)
exec(@query)
</code>```

Note: Better replace * with the column names you want.

To get all the tables you can use sysobject and filter out based on table names like

```<code>SELECT [name]
FROM sys.sysobjects
WHERE [xtype] = 'U'
    AND NAME LIKE 'Data_[0-9][0-9]_[0-9][0-9][0-9][0-9]'
</code>```

And build a dynamic query using UNION.

Body:
I am get data from a third party database to generate certain reports. The issue is that it keeps on generating a new table every month to insert the same record in same columns in the following manner:

For December table : Data_12_2019
For January table  : Data_1_2020
For February table : Data_2_2020
For March table    : Data_3_2020 and so on

and table data is as following:

UserId  DLogId  LogDate
1461    1799    2020-01-06 09:07:51.000
1462    1803    2020-01-07 09:29:39.000
1463    1806    2020-01-07 11:43:11.000
1464    1807    2020-01-09 09:16:47.000
1457    1819    2020-01-10 09:00:56.000

table2

UserId  DLogId  LogDate
1466    1853    2020-02-03 09:11:54.000
1468    1831    2020-02-04 09:17:09.000
1470    1833    2020-02-5 09:01:06.000

and need output in a single table in following manner:

UserId  DLogId  LogDate
1461    1799    2020-01-06 09:07:51.000
1462    1803    2020-01-07 09:29:39.000
1463    1806    2020-01-07 11:43:11.000
1464    1807    2020-01-09 09:16:47.000
1457    1819    2020-01-10 09:00:56.000
1466    1853    2020-02-03 09:11:54.000
1468    1831    2020-02-04 09:17:09.000
1470    1833    2020-02-5 09:01:06.000

I want to get data placed in above tables and tables that will be generated in future also.
I am seeking a help about how to do it.

Body:
You can achieve this using dynamic query. If your table structure is same, you can try like following.

DECLARE @query AS NVARCHAR(max) = Stuff((SELECT DISTINCT ' ' + 'SELECT * FROM ' + Quotename(name) + ' UNION'
                 FROM
                 (
                  SELECT
                    [name]
                FROM
                    sys.sysobjects
                WHERE
                    [xtype] = 'U'
                    and NAME LIKE 'Data_[0-9][0-9]_[0-9][0-9][0-9][0-9]'
                 )t
                 FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '');

SET @query= substring(@query,0,len(@query)-5)
exec(@query)

Note: Better replace * with the column names you want.

To get all the tables you can use sysobject and filter out based on table names like

SELECT [name]
FROM sys.sysobjects
WHERE [xtype] = 'U'
    AND NAME LIKE 'Data_[0-9][0-9]_[0-9][0-9][0-9][0-9]'

And build a dynamic query using UNION.


问:
How to access last element in a web page when everything has the same class?
I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

```<code>message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")
</code>```

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

答:
Use last():

```<code>message = self.driver.find_element_by_xpath("(//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')])[last()]")
</code>```

Body:
I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

Body:
Use last():

message = self.driver.find_element_by_xpath("(//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')])[last()]")


问:
Clean way of injecting/checking for presence of a HttpServletRequest with CDI from code that can be called outside a request?
I have a piece of code that can be called both within and outside a HTTP request, but wants to access information in the HttpServletRequest if it is available. My first attempt was the following:

```<code>@Inject
private Instance<HttpServletRequest> httpReq;

void doSomethingIfInRequest(){
  if (httpReq.isUnsatisfied()){
    return;
  }
  httpReq.get()
  // ...
}
</code>```

However, even outside a request, isUnsatisfied() returns false, leading get() to throw org.jboss.weld.exceptions.IllegalStateException: WELD-000710: Cannot inject HttpServletRequest outside of a Servlet request.

I can solve this by catching the exception or creating another class that holds the request but was wondering whether CDI/Weld offers something to deal with this.

答:
In addition to the solution by Siliarus, the following code can be used to check whether the current context is HttpServletRequestContext or not.</p>

```<code>@Inject
BeanManager bm;

public boolean isHttpRequestScopeIsActive() {
        if (isHttpRequestScopeActive == null) {

            try {
                Context context = bm.getContext(RequestScoped.class);
                isHttpRequestScopeActive = context instanceof HttpRequestContextImpl;
            } catch (ContextNotActiveException e) {
                isHttpRequestScopeActive = false;
            }

        }
        return isHttpRequestScopeActive;

    }
</code>```

Body:
I have a piece of code that can be called both within and outside a HTTP request, but wants to access information in the HttpServletRequest if it is available. My first attempt was the following:

@Inject
private Instance<HttpServletRequest> httpReq;

void doSomethingIfInRequest(){
  if (httpReq.isUnsatisfied()){
    return;
  }
  httpReq.get()
  // ...
}

However, even outside a request, isUnsatisfied() returns false, leading get() to throw org.jboss.weld.exceptions.IllegalStateException: WELD-000710: Cannot inject HttpServletRequest outside of a Servlet request.

I can solve this by catching the exception or creating another class that holds the request but was wondering whether CDI/Weld offers something to deal with this.

Body:
In addition to the solution by Siliarus, the following code can be used to check whether the current context is HttpServletRequestContext or not.

@Inject
BeanManager bm;

public boolean isHttpRequestScopeIsActive() {
        if (isHttpRequestScopeActive == null) {

            try {
                Context context = bm.getContext(RequestScoped.class);
                isHttpRequestScopeActive = context instanceof HttpRequestContextImpl;
            } catch (ContextNotActiveException e) {
                isHttpRequestScopeActive = false;
            }

        }
        return isHttpRequestScopeActive;

    }


问:
Access string_array from activity and send selected item to another activity in android
hello friends today my question is about string_array.On my activity i created two buttons.Now on (strings.xml) i created string array name with two items and i have inserted some text as shown below.On each button click i would like to access each item individually.for example on button1 click show me first item and on button 2 click give me the 2nd item on.Can you please give me the code for button click as i have little idea on how to access item.I have created a textview activity to display my item with every click.my code is working fine till now but i need help with extra code that i have to add.Please help me .</p>

```<code>// Button activity page
android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="50dp"
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:text="@string/OKILA"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_marginRight="50dp"
        android:text="1"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>
</code>```

```<code>//strings.xml
    <string-array name="chapters">
        <item>this is tes1</item>
        <item>this is test2</item>
    </string-array>
</code>```

```<code>//main
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class Lipok extends AppCompatActivity implements View.OnClickListener {
    Toolbar mActionBarToolbar;
    Button btnOne;
    Button btnTwo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipok);
        mActionBarToolbar=(Toolbar)findViewById(R.id.CHAPTERS);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setTitle("CHAPTERS");
    String[] chapters=getResources().getStringArray(R.array.chapters);

        btnOne = findViewById(R.id.btn1);
        btnTwo = findViewById(R.id.button1);

        btnOne.setOnClickListener(this);
        btnTwo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String text="";
        switch(v.getId()){
            case R.id.btn1 : {
                text = getResources().getStringArray(R.array.chapters)[0];
                break;
            }
            case R.id.button1 : {
                text = getResources().getStringArray(R.array.chapters)[1];
                break;
            }
        }

        Intent intent = new Intent(Lipok.this,lipokchapters.class);
        intent.putExtra("DATA", text);
        startActivity(intent);
    }
}

</code>```

```<code>//textview activity page
package com.Aolai.temeshilai;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class lipokchapters extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipokchapters);
        textView=findViewById(R.id.textv);
        String text= getIntent().getStringExtra("Data");
        textView.setText(text);

    }
}
</code>```

答:
This is basics of Android so before answering I suggest you to go
  through basic tutorials before posting on Stackoberflow.

Now,

Here is how you can access the items from your string_array.

```<code>String[] chapters= getResources().getStringArray(R.array.chapters);
</code>```

Now,here is pseudo code that might help you.

```<code>btn1.setOnClickListener(

your_text_view.setText(chapters[0])

)
//Here 0 means your first item, likewise you can access items by their index in
 array
</code>```

Body:
hello friends today my question is about string_array.On my activity i created two buttons.Now on (strings.xml) i created string array name with two items and i have inserted some text as shown below.On each button click i would like to access each item individually.for example on button1 click show me first item and on button 2 click give me the 2nd item on.Can you please give me the code for button click as i have little idea on how to access item.I have created a textview activity to display my item with every click.my code is working fine till now but i need help with extra code that i have to add.Please help me .

// Button activity page
android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="50dp"
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:text="@string/OKILA"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_marginRight="50dp"
        android:text="1"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>

//strings.xml
    <string-array name="chapters">
        <item>this is tes1</item>
        <item>this is test2</item>
    </string-array>

//main
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class Lipok extends AppCompatActivity implements View.OnClickListener {
    Toolbar mActionBarToolbar;
    Button btnOne;
    Button btnTwo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipok);
        mActionBarToolbar=(Toolbar)findViewById(R.id.CHAPTERS);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setTitle("CHAPTERS");
    String[] chapters=getResources().getStringArray(R.array.chapters);

        btnOne = findViewById(R.id.btn1);
        btnTwo = findViewById(R.id.button1);

        btnOne.setOnClickListener(this);
        btnTwo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String text="";
        switch(v.getId()){
            case R.id.btn1 : {
                text = getResources().getStringArray(R.array.chapters)[0];
                break;
            }
            case R.id.button1 : {
                text = getResources().getStringArray(R.array.chapters)[1];
                break;
            }
        }

        Intent intent = new Intent(Lipok.this,lipokchapters.class);
        intent.putExtra("DATA", text);
        startActivity(intent);
    }
}

//textview activity page
package com.Aolai.temeshilai;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class lipokchapters extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipokchapters);
        textView=findViewById(R.id.textv);
        String text= getIntent().getStringExtra("Data");
        textView.setText(text);

    }
}

Body:
This is basics of Android so before answering I suggest you to go
  through basic tutorials before posting on Stackoberflow.

Now,

Here is how you can access the items from your string_array.

String[] chapters= getResources().getStringArray(R.array.chapters);

Now,here is pseudo code that might help you.

btn1.setOnClickListener(

your_text_view.setText(chapters[0])

)
//Here 0 means your first item, likewise you can access items by their index in
 array


问:
Unable to Set Suite Variable for multiple variables in robot framework using "AND" condition
I'm trying Set Suite Variable for multiple variables in Robot Framework (RIDE tool, keyword driven) using "AND" condition, but not able to.

The below is my script:

```<code> Set Suite Variable    ${username} AND
 ${password} AND
 ${URL} AND
 ${Browser}
</code>```

Error im facing:

Invalid variable syntax '${username} AND'.

pip list:

```<code>robotframework                          3.1.2
[...]
selenium                                3.8.1
</code>```

Do let me know if any missing from my end. Thanks in advance!

答:
Since Set Suite Variable does not support setting multiple variables at once but you still want to do it in a single line I would try with Run Keywords instead:

```<code>Run Keywords    Set Suite Variable    ${VAR1}    value1    AND    Set Suite Variable    ${VAR2}    value2
</code>```

But probably the cleanest way would be to have a keyword where your variables are set

```<code>*** Keywords ***
Set Variables
    Set Suite Variable    ${VAR1}    value1
    Set Suite Variable    ${VAR2}    value2
</code>```

Body:
I'm trying Set Suite Variable for multiple variables in Robot Framework (RIDE tool, keyword driven) using "AND" condition, but not able to.

The below is my script:

 Set Suite Variable    ${username} AND
 ${password} AND
 ${URL} AND
 ${Browser}

Error im facing:

Invalid variable syntax '${username} AND'.

pip list:

robotframework                          3.1.2
[...]
selenium                                3.8.1

Do let me know if any missing from my end. Thanks in advance!

Body:
Since Set Suite Variable does not support setting multiple variables at once but you still want to do it in a single line I would try with Run Keywords instead:

Run Keywords    Set Suite Variable    ${VAR1}    value1    AND    Set Suite Variable    ${VAR2}    value2

But probably the cleanest way would be to have a keyword where your variables are set

*** Keywords ***
Set Variables
    Set Suite Variable    ${VAR1}    value1
    Set Suite Variable    ${VAR2}    value2


问:
IAM Role does not exist for EMR Notebooks
I'm trying to create a Notebook on an Amazon EMR cluster.

I didn't find the default role for notebooks EMR_Notebooks_DefaultRole to add as IAM. All the available roles that exists are:

After adding the strategy and adding the role I got error:

Error: Service role does not have permission to access the S3 LocationUri {}

Contents of my EMR_Notebooks_DefaultRole:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Resource": "*",
            "Action": [
                "ec2:AuthorizeSecurityGroupEgress",
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:CancelSpotInstanceRequests",
                "ec2:CreateNetworkInterface",
                "ec2:CreateSecurityGroup",
                "ec2:CreateTags",
                "ec2:DeleteNetworkInterface",
                "ec2:DeleteSecurityGroup",
                "ec2:DeleteTags",
                "ec2:DescribeAvailabilityZones",
                "ec2:DescribeAccountAttributes",
                "ec2:DescribeDhcpOptions",
                "ec2:DescribeImages",
                "ec2:DescribeInstanceStatus",
                "ec2:DescribeInstances",
                "ec2:DescribeKeyPairs",
                "ec2:DescribeNetworkAcls",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DescribePrefixLists",
                "ec2:DescribeRouteTables",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSpotInstanceRequests",
                "ec2:DescribeSpotPriceHistory",
                "ec2:DescribeSubnets",
                "ec2:DescribeTags",
                "ec2:DescribeVpcAttribute",
                "ec2:DescribeVpcEndpoints",
                "ec2:DescribeVpcEndpointServices",
                "ec2:DescribeVpcs",
                "ec2:DetachNetworkInterface",
                "ec2:ModifyImageAttribute",
                "ec2:ModifyInstanceAttribute",
                "ec2:RequestSpotInstances",
                "ec2:RevokeSecurityGroupEgress",
                "ec2:RunInstances",
                "ec2:TerminateInstances",
                "ec2:DeleteVolume",
                "ec2:DescribeVolumeStatus",
                "ec2:DescribeVolumes",
                "ec2:DetachVolume",
                "iam:GetRole",
                "iam:GetRolePolicy",
                "iam:ListInstanceProfiles",
                "iam:ListRolePolicies",
                "iam:PassRole",
                "s3:*",
                "s3:CreateBucket",
                "s3:Get*",
                "s3:List*",
                "sdb:BatchPutAttributes",
                "sdb:Select",
                "sqs:CreateQueue",
                "sqs:Delete*",
                "sqs:GetQueue*",
                "sqs:PurgeQueue",
                "sqs:ReceiveMessage",
                "cloudwatch:PutMetricAlarm",
                "cloudwatch:DescribeAlarms",
                "cloudwatch:DeleteAlarms",
                "application-autoscaling:RegisterScalableTarget",
                "application-autoscaling:DeregisterScalableTarget",
                "application-autoscaling:PutScalingPolicy",
                "application-autoscaling:DeleteScalingPolicy",
                "application-autoscaling:Describe*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot*",
            "Condition": {
                "StringLike": {
                    "iam:AWSServiceName": "spot.amazonaws.com"
                }
            }
        }
    ]
}
</code>```

BlocNotes Stopped

答:
you already have "s3:*" in your policy, have this apply to the S3 bucket

explicitly, include the bucket ARN and folder path

arn:aws:s3:::bucket

arn:aws:s3:::bucket/*

when creating the notebook in the EMR console, also specify a folder in the path

Body:
I'm trying to create a Notebook on an Amazon EMR cluster.

I didn't find the default role for notebooks EMR_Notebooks_DefaultRole to add as IAM. All the available roles that exists are:

After adding the strategy and adding the role I got error:

Error: Service role does not have permission to access the S3 LocationUri {}

Contents of my EMR_Notebooks_DefaultRole:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Resource": "*",
            "Action": [
                "ec2:AuthorizeSecurityGroupEgress",
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:CancelSpotInstanceRequests",
                "ec2:CreateNetworkInterface",
                "ec2:CreateSecurityGroup",
                "ec2:CreateTags",
                "ec2:DeleteNetworkInterface",
                "ec2:DeleteSecurityGroup",
                "ec2:DeleteTags",
                "ec2:DescribeAvailabilityZones",
                "ec2:DescribeAccountAttributes",
                "ec2:DescribeDhcpOptions",
                "ec2:DescribeImages",
                "ec2:DescribeInstanceStatus",
                "ec2:DescribeInstances",
                "ec2:DescribeKeyPairs",
                "ec2:DescribeNetworkAcls",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DescribePrefixLists",
                "ec2:DescribeRouteTables",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSpotInstanceRequests",
                "ec2:DescribeSpotPriceHistory",
                "ec2:DescribeSubnets",
                "ec2:DescribeTags",
                "ec2:DescribeVpcAttribute",
                "ec2:DescribeVpcEndpoints",
                "ec2:DescribeVpcEndpointServices",
                "ec2:DescribeVpcs",
                "ec2:DetachNetworkInterface",
                "ec2:ModifyImageAttribute",
                "ec2:ModifyInstanceAttribute",
                "ec2:RequestSpotInstances",
                "ec2:RevokeSecurityGroupEgress",
                "ec2:RunInstances",
                "ec2:TerminateInstances",
                "ec2:DeleteVolume",
                "ec2:DescribeVolumeStatus",
                "ec2:DescribeVolumes",
                "ec2:DetachVolume",
                "iam:GetRole",
                "iam:GetRolePolicy",
                "iam:ListInstanceProfiles",
                "iam:ListRolePolicies",
                "iam:PassRole",
                "s3:*",
                "s3:CreateBucket",
                "s3:Get*",
                "s3:List*",
                "sdb:BatchPutAttributes",
                "sdb:Select",
                "sqs:CreateQueue",
                "sqs:Delete*",
                "sqs:GetQueue*",
                "sqs:PurgeQueue",
                "sqs:ReceiveMessage",
                "cloudwatch:PutMetricAlarm",
                "cloudwatch:DescribeAlarms",
                "cloudwatch:DeleteAlarms",
                "application-autoscaling:RegisterScalableTarget",
                "application-autoscaling:DeregisterScalableTarget",
                "application-autoscaling:PutScalingPolicy",
                "application-autoscaling:DeleteScalingPolicy",
                "application-autoscaling:Describe*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot*",
            "Condition": {
                "StringLike": {
                    "iam:AWSServiceName": "spot.amazonaws.com"
                }
            }
        }
    ]
}

BlocNotes Stopped


问:
JavaScript firing too many events?
The handle mousemove events are amongst 3
s which are nested inside each other. Can't seem to find the issue which is causing too many events to get fired.

(function() {
  var boxes = [
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ];

  boxes[0].addEventListener(
    "mousemove", function(event) { console.log("Box 1"); }
  );
  boxes[1].addEventListener(
    "mousemove", function(event) { console.log("Box 2"); }
  );
  boxes[2].addEventListener(
    "mousemove", function(event) { console.log("Box 3"); }
  );
})();

```

答:
You need to use event.stopPropagation() function. As you have said that div are nested,
So,

When an event happens on an element, it first runs the handlers on
  it, then on its parent, then all the way up on other ancestors which is called Event Bubbling.

You can read about it here.

Look at the following example,

let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");

box1.addEventListener("click",()=> alert("Box1"));
box2.addEventListener("click",()=> alert("Box2"));
box3.addEventListener("click",()=> alert("Box3"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box1,.box2,.box3 {
  border: 1px solid;
  padding: 10px;
}</code>```

  Box 1

    Box 2

Box 3

```
</div>
</div>
</p>

<p>If you click on Box3, Box2 and Box1 alert also shown.
The Reason behind is that, Event Bubbling</p>

<p>You can Stop It by Using <code>event.stopPropagation()</code> function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function() {
  var boxes = [
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ];

  boxes[0].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 1");
    }
  );
  boxes[1].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 2");
    }
  );
  boxes[2].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 3");
    }
  );
})();</code>```

#box1,#box2,#box3 {
  border: 1px solid;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box1">
  Box 1
  <div id="box2">
    Box 2
    <div id="box3">Box 3</div>
  </div>
</div></code>```

OR,

You can add the event on the parent element only once, like this

(function() {
  var parentBox = document.getElementById("box1");

  parentBox.addEventListener("click",
    function(event) {
      let targetDiv = event.target;
      switch(targetDiv.id) {
       case "box1" : console.log("Box 1");break;
       case "box2" : console.log("Box 2");break;
       case "box3" : console.log("Box 3");break;
      }
    },true);

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box1,#box2,#box3 {
  border: 1px solid;
  padding: 10px;
}</code>```

  Box 1

    Box 2

Box 3

```

Title: JavaScript firing too many events?

Body:
You need to use event.stopPropagation() function. As you have said that div are nested,
So,

When an event happens on an element, it first runs the handlers on
  it, then on its parent, then all the way up on other ancestors which is called Event Bubbling.

You can read about it here.

Look at the following example,

let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");

box1.addEventListener("click",()=> alert("Box1"));
box2.addEventListener("click",()=> alert("Box2"));
box3.addEventListener("click",()=> alert("Box3"));

.box1,.box2,.box3 {
  border: 1px solid;
  padding: 10px;
}

<div class="box1">
  Box 1
  <div class="box2">
    Box 2
    <div class="box3">Box 3</div>
  </div>
</div>

If you click on Box3, Box2 and Box1 alert also shown.
The Reason behind is that, Event Bubbling

You can Stop It by Using event.stopPropagation() function

(function() {
  var boxes = [
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ];

  boxes[0].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 1");
    }
  );
  boxes[1].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 2");
    }
  );
  boxes[2].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 3");
    }
  );
})();

#box1,#box2,#box3 {
  border: 1px solid;
  padding: 10px;
}

<div id="box1">
  Box 1
  <div id="box2">
    Box 2
    <div id="box3">Box 3</div>
  </div>
</div>

OR,

You can add the event on the parent element only once, like this

(function() {
  var parentBox = document.getElementById("box1");

  parentBox.addEventListener("click",
    function(event) {
      let targetDiv = event.target;
      switch(targetDiv.id) {
       case "box1" : console.log("Box 1");break;
       case "box2" : console.log("Box 2");break;
       case "box3" : console.log("Box 3");break;
      }
    },true);

})();

#box1,#box2,#box3 {
  border: 1px solid;
  padding: 10px;
}

<div id="box1">
  Box 1
  <div id="box2">
    Box 2
    <div id="box3">Box 3</div>
  </div>
</div>


问:
Handling an element without click attribute
I want to click this element called "Select File", it is a button but i am unable to click it using selenium command. The the element I am about to click is as follows:

```<code><label for="file" class="pb default" style="display: inline-block;margin: 5px 10px;">Select File</label>
</code>```

the script I am using to click for that element is:

```<code>_test_=browser.find_elements_by_class_name("pb default")
_test_.click()
</code>```

It gives an exception like this:

```<code>Traceback (most recent call last):
  File "z:\test_selenium_impossible_click.py", line 58, in
<module>
    _test_.click()
AttributeError: 'list' object has no attribute 'click'
</code>```

I am using latest firefox version with latest webdriver for firefox

UPDATE :
i have edited the code to become like this :

```<code>_test_=browser.find_element_by_class_name("pb default")
_test_.click()
</code>```

but now it gives output like this :

```<code>  Traceback (most recent call last):
  File "z:\automator-python\test_selenium_impossible_click.py", line 57, in <module>
    _test_=browser.find_element_by_class_name("pb default")
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .pb default
</code>```

i have tried the other ways like what has been suggested to me but it still gives output like what i mentioned above...do you know how to solve this??

答:
The problem is not missing attributes, it in the element locating.

find_elements_* return a list, not a single element, so you can't click it.

by_class_name recive a single class as parameter, you sent two.

To locate the element by multiple classes use css_selector

```<code>find_element_by_css_selector('.pb.default')
</code>```

Body:
I want to click this element called "Select File", it is a button but i am unable to click it using selenium command. The the element I am about to click is as follows:

Select File

the script I am using to click for that element is:

_test_=browser.find_elements_by_class_name("pb default")
_test_.click()

It gives an exception like this:

Traceback (most recent call last):
  File "z:\test_selenium_impossible_click.py", line 58, in
<module>
    _test_.click()
AttributeError: 'list' object has no attribute 'click'

I am using latest firefox version with latest webdriver for firefox

UPDATE :
i have edited the code to become like this :

_test_=browser.find_element_by_class_name("pb default")
_test_.click()

but now it gives output like this :

  Traceback (most recent call last):
  File "z:\automator-python\test_selenium_impossible_click.py", line 57, in <module>
    _test_=browser.find_element_by_class_name("pb default")
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .pb default

i have tried the other ways like what has been suggested to me but it still gives output like what i mentioned above...do you know how to solve this??

Body:
The problem is not missing attributes, it in the element locating.

find_elements_* return a list, not a single element, so you can't click it.

by_class_name recive a single class as parameter, you sent two.

To locate the element by multiple classes use css_selector

find_element_by_css_selector('.pb.default')


答:
Try this :

xml file

```<code>android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="50dp"
        android:id="@+id/OKILA"
        android:layout_width="wrap_content"
        android:text="@string/OKILA"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_marginRight="50dp"
        android:text="1"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>
</code>```

strings.xml

```<code>    <string-array name="chapters">
        <item>this is tes1</item>
        <item>this is test2</item>
    </string-array>
</code>```

Main Class

```<code>public class Lipok extends AppCompatActivity implements View.OnClickListener {
    Toolbar mActionBarToolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipok);
        mActionBarToolbar=(Toolbar)findViewById(R.id.CHAPTERS);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setTitle("CHAPTERS");

    }

    @Override
    public void onClick(View v) {
         String text="";
         switch(v.getId()){
              case R.id.OKILA : {
                   text = getResources().getStringArray(R.array.testArray)[0];
                   break;
              }
              case R.id.button1 : {
                   text = getResources().getStringArray(R.array.testArray)[1];
                   break;
              }
         }
         Toast.makeText(this, text, Toast.LENGTH_LONG).show();

             Intent intent = new Intent(this, YOUR_ACTIVITY_NAME.class);
             intent.putExtra("DATA", text);
             startActivity(intent);

         // Or else you can do whatever you want to do here with that text
    }
}
</code>```

Then in your other activity

```<code>String data = getIntent().getStringExtra("DATA");
YOUR_TEXTVIEW_NAME.setText(data);
</code>```

Title: Access string_array from activity and send selected item to another activity in android

Body:
Try this :

xml file

android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="50dp"
        android:id="@+id/OKILA"
        android:layout_width="wrap_content"
        android:text="@string/OKILA"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_marginRight="50dp"
        android:text="1"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>

strings.xml

    <string-array name="chapters">
        <item>this is tes1</item>
        <item>this is test2</item>
    </string-array>

Main Class

public class Lipok extends AppCompatActivity implements View.OnClickListener {
    Toolbar mActionBarToolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lipok);
        mActionBarToolbar=(Toolbar)findViewById(R.id.CHAPTERS);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setTitle("CHAPTERS");

    }

    @Override
    public void onClick(View v) {
         String text="";
         switch(v.getId()){
              case R.id.OKILA : {
                   text = getResources().getStringArray(R.array.testArray)[0];
                   break;
              }
              case R.id.button1 : {
                   text = getResources().getStringArray(R.array.testArray)[1];
                   break;
              }
         }
         Toast.makeText(this, text, Toast.LENGTH_LONG).show();

             Intent intent = new Intent(this, YOUR_ACTIVITY_NAME.class);
             intent.putExtra("DATA", text);
             startActivity(intent);

         // Or else you can do whatever you want to do here with that text
    }
}

Then in your other activity

String data = getIntent().getStringExtra("DATA");
YOUR_TEXTVIEW_NAME.setText(data);


答:
```<code>PREPARE stmt1 FROM ' SELECT GROUP_CONCAT('SELECT * FROM ',TABLE_NAME,' UNION ')
FROM information_schema.tables
WHERE table_schema =? AND table_name LIKE 'Data_%'';

SET @a = 'MyDb';

EXECUTE stmt1 USING @a;
</code>```

Title: Select data from multiple tables with same column names and structure using sql


问:
How to parse moment into specific timezone from moment.unix()
I have an initial value for a timestamp (created in User-1's timezone) I'm retrieving from firebase's firestore. the format this is in, is seconds in UTC from the Unix Epoch.

My goal is to take the initial timestamp value, and convert it to the timezone of the current user. if I use

moment.unix(initial_In_Seconds).format("H:mma") I get the correct initial time. Using .unix() is the only way I've been able to get the correct initial time. Now I need to convert it to a specific timezone. lets say "America/Denver" (the initial timezone is GMT -05:00)

I haven't been successful using moment.tz() in any of my amalgamations thus far.

I've tried:

```<code>moment.tz(moment.unix(initial_In_Seconds).format("H:mma"), "America/Denver")

let unix = moment.unix(initial_In_Seconds).format("H:mma");
let parsed = moment.tz(unix, "America/Denver");
</code>```

How can this be parsed? Moment.js confuses me

答:
If your timezone offset is specified using IANA representative locations, such as 'America/Denver', then you can likely use toLocaleString provided the locations aren't too obscure (i.e. aren't unsupported by ECMAScript implementations likely to run your code), e.g.

function timeValueWithTimezone(unixOffset, loc) {
  let d = new Date(unixOffset * 1000);
  return d.toLocaleString(void 0, {
    hour12: true,
    hour: 'numeric',
    minute: '2-digit',
    timeZone: loc
  });
}

let timeValue = 1582090120;
let loc = 'America/Denver';

console.log('At your local time: ' +
  new Date(timeValue * 1000).toLocaleString(void 0, {
    hour12: true,
    hour: 'numeric',
    minute: '2-digit'
}));
console.log('Denver local time is: ' + timeValueWithTimezone(timeValue, loc));```

Body:
I have an initial value for a timestamp (created in User-1's timezone) I'm retrieving from firebase's firestore. the format this is in, is seconds in UTC from the Unix Epoch.

My goal is to take the initial timestamp value, and convert it to the timezone of the current user. if I use

moment.unix(initial_In_Seconds).format("H:mma") I get the correct initial time. Using .unix() is the only way I've been able to get the correct initial time. Now I need to convert it to a specific timezone. lets say "America/Denver" (the initial timezone is GMT -05:00)

I haven't been successful using moment.tz() in any of my amalgamations thus far.

I've tried:

moment.tz(moment.unix(initial_In_Seconds).format("H:mma"), "America/Denver")

let unix = moment.unix(initial_In_Seconds).format("H:mma");
let parsed = moment.tz(unix, "America/Denver");

How can this be parsed? Moment.js confuses me


问:
Php get keys from associative array
How could I get only the entire first row from an array. (I use Laravel)

For example when I say:

```<code>$request-all();
</code>```

I receive:

```<code>array:2 [
  "email" => "james@hotmail.com"
  "password" => "adms|Wh"
]
</code>```

I want to receive:

```<code>email
password
</code>```

答:
You can use the PHP array_keys() function to get all the keys out of an associative array.

```<code>$array = array("email"=>"james@hotmail.com", "password"=>"adms|Wh");
</code>```

Get keys from $array array

```<code> print_r(array_keys($array));
</code>```

You can also use the PHP foreach loop to find or display all the keys, like this:

Loop through $array array

```<code>foreach($array as $key => $value){
    echo $key . " : " . $value . "<br>";
}
</code>```

Title: Php get keys from associative array

Body:
How could I get only the entire first row from an array. (I use Laravel)

For example when I say:

$request-all();

I receive:

array:2 [
  "email" => "james@hotmail.com"
  "password" => "adms|Wh"
]

I want to receive:

email
password

Body:
You can use the PHP array_keys() function to get all the keys out of an associative array.

$array = array("email"=>"james@hotmail.com", "password"=>"adms|Wh");

Get keys from $array array

 print_r(array_keys($array));

You can also use the PHP foreach loop to find or display all the keys, like this:

Loop through $array array

foreach($array as $key => $value){
    echo $key . " : " . $value . "<br>";
}


问:
React ref undefined
so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

```<code>export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
</code>```

However, this always prints null or undefined instead of "Hi" which is what I want.

答:
Its because you are logging it in constructor. Run the code in componentDidMount lifecyle.</p>

```<code>export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();

  }

componentDidMount(){
      console.log(this.intro.textContent);
    }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
</code>```

Title: React ref undefined

Body:
so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (

Hi

    )
  }
}

However, this always prints null or undefined instead of "Hi" which is what I want.

Body:
Its because you are logging it in constructor. Run the code in componentDidMount lifecyle.

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();

  }

componentDidMount(){
      console.log(this.intro.textContent);
    }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}


问:
recyclerView.isLayoutFrozen deprecated. What is the alternative in Kotlin?
How to stop the scrolling function of RecyclerView "temporarily" according to user input in a way that if the user wants the scroll functionality back, they can reactivate it. The most practical solution I could find is isLayoutFrozen in Kotlin.

However the function looks deprecated. So what is the better solution which can be applied to API 14 and onward?

答:
According to source,
the isLayoutFrozen method is replaced with isLayoutSuppressed.
You can use it as someRecyclerView.isLayoutSuppressed.
Check out API description.

If you are trying to assign the layout suppress property, use the suppressLayout(boolean) method.