问:
Fetching data from firebase without calling own data
I have a tinder type set up and I am fetching all of the users so I can swipe on their cards. everything works smoothly except for the fact that this swipe view is also calling the data from the current user allowing them to swipe on themselves. This should not happen.

The code that I am using is

func fetchUser() {

```<code>     topCardView = nil
     var previousCardView: CardView?
    Database.database().reference().child("jobPost").observe(.childAdded, with: { (snapshot) in

            if let userDictionary = snapshot.value as? [String: AnyObject] {

                let poster = Poster(dictionary: userDictionary as [String : AnyObject])
                let cardView = self.setupCardFromUser(poster: poster)
                self.cardViewModels.append(poster.toCardViewModel())

                if let currentUser = Auth.auth().currentUser?.uid,
                    currentUser == poster.fromId {
                    cardView.removeFromSuperview()
                    } else if self.topCardView == nil {
                      self.topCardView = cardView
                    }

                previousCardView?.nextCardView = cardView
                previousCardView = cardView

        }

    }, withCancel: nil)

}
</code>```

This allows me to call all of the data from firebase however, it is also calling the currentUsers data as well.

I thought that maybe if were to use

```<code>  let currentUser = Auth.auth().currentUser?.uid

   if currentUser == cardView {
     cardView?.removeFromSuperview()

    }
</code>```

would do the job but on this, I am receiving error

Binary operator '==' cannot be applied to operands of type 'String?' and 'CardView'

does anyone know a quick fix?

答:
Does your cardView have information about user?
Maybe you can add userID field to the card view ?
if it's possible , you will be able to do something like this

```<code>if let currentUser = Auth.auth().currentUser?.uid,
  let cardView = cardView,
  currentUser == cardView.userID {
  // put your code to ignore card
}
</code>```

where userId - will be string type

Body:
I have a tinder type set up and I am fetching all of the users so I can swipe on their cards. everything works smoothly except for the fact that this swipe view is also calling the data from the current user allowing them to swipe on themselves. This should not happen.

The code that I am using is

func fetchUser() {

     topCardView = nil
     var previousCardView: CardView?
    Database.database().reference().child("jobPost").observe(.childAdded, with: { (snapshot) in

            if let userDictionary = snapshot.value as? [String: AnyObject] {

                let poster = Poster(dictionary: userDictionary as [String : AnyObject])
                let cardView = self.setupCardFromUser(poster: poster)
                self.cardViewModels.append(poster.toCardViewModel())

                if let currentUser = Auth.auth().currentUser?.uid,
                    currentUser == poster.fromId {
                    cardView.removeFromSuperview()
                    } else if self.topCardView == nil {
                      self.topCardView = cardView
                    }

                previousCardView?.nextCardView = cardView
                previousCardView = cardView

        }

    }, withCancel: nil)

}

This allows me to call all of the data from firebase however, it is also calling the currentUsers data as well.

I thought that maybe if were to use

  let currentUser = Auth.auth().currentUser?.uid

   if currentUser == cardView {
     cardView?.removeFromSuperview()

    }

would do the job but on this, I am receiving error

Binary operator '==' cannot be applied to operands of type 'String?' and 'CardView'

does anyone know a quick fix?

Body:
Does your cardView have information about user?
Maybe you can add userID field to the card view ?
if it's possible , you will be able to do something like this

if let currentUser = Auth.auth().currentUser?.uid,
  let cardView = cardView,
  currentUser == cardView.userID {
  // put your code to ignore card
}

where userId - will be string type


来源: stackexchange

问:
How to add ScrollView inside constraint layout in different screen quality?
Im creating a project in android studio and this is my xml:

```<code><?xml version="1.0" encoding="utf-8"?>

<!-- tools:ignore="LabelFor" quita el warining Missing accessibility label-->
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/DescripcionDia"
        android:layout_width="413dp"
        android:layout_height="50dp"
        app:layout_constraintBottom_toTopOf="@+id/scrollView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="This is a random  text "
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ContenedorTexto"
        android:layout_width="371dp"
        android:layout_height="119dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.949">

        <EditText

            android:id="@+id/TextoDescriptivo"
            android:layout_width="351dp"
            android:layout_height="96dp"
            android:autofillHints=""
            android:ems="10"
            android:inputType="textPersonName"
            android:text="@string/asdadsfasdf_nasdfasdfasd_asdfasdfasdfasdf_asd_nfasd_fas_dfa_s"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="LabelFor" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="361dp"
        android:layout_height="507dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="21dp"
        app:layout_constraintBottom_toTopOf="@+id/ContenedorTexto"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/DescripcionDia">

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

            <Button
                android:id="@+id/button70"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/button" />

            <Button
                android:id="@+id/button72"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="BUTTON2" />

             ... [several testing buttons]

            <Button
                android:id="@+id/button65"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/button" />

        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

So when i run my app in a virtual device like ... Pixel 3XL its all correct, the program respect the actual design i want.

But when i do in a device with less screen quality, like nexus 4 i have this :

As you can see, there are 3 problems here:

The first one is the layout with the text view is ignored.
The second one is the layout in the bottom,is not respected.
And finally the third one is the scroll view does not start directly with the first button, just the half.

What is the mistake im commiting ? and what can i do to make this not happen

答:
Set your ScrollView height

```<code>android:layout_height="0dp"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im creating a project in android studio and this is my xml:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/DescripcionDia"
        android:layout_width="413dp"
        android:layout_height="50dp"
        app:layout_constraintBottom_toTopOf="@+id/scrollView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="This is a random  text "
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ContenedorTexto"
        android:layout_width="371dp"
        android:layout_height="119dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.949">

        <EditText

            android:id="@+id/TextoDescriptivo"
            android:layout_width="351dp"
            android:layout_height="96dp"
            android:autofillHints=""
            android:ems="10"
            android:inputType="textPersonName"
            android:text="@string/asdadsfasdf_nasdfasdfasd_asdfasdfasdfasdf_asd_nfasd_fas_dfa_s"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="LabelFor" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="361dp"
        android:layout_height="507dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="21dp"
        app:layout_constraintBottom_toTopOf="@+id/ContenedorTexto"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/DescripcionDia">

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

            <Button
                android:id="@+id/button70"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/button" />

            <Button
                android:id="@+id/button72"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="BUTTON2" />

             ... [several testing buttons]

            <Button
                android:id="@+id/button65"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/button" />

        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

So when i run my app in a virtual device like ... Pixel 3XL its all correct, the program respect the actual design i want.

But when i do in a device with less screen quality, like nexus 4 i have this :

As you can see, there are 3 problems here:

The first one is the layout with the text view is ignored.
The second one is the layout in the bottom,is not respected.
And finally the third one is the scroll view does not start directly with the first button, just the half.

What is the mistake im commiting ? and what can i do to make this not happen

Body:
Set your ScrollView height

android:layout_height="0dp"


问:
access photos from Picasa in Android using Google APIs
I am trying to fetch photos from a Picasa album in Android.

I have used following link as a reference:

http://gdata-java-client.googlecode.com/svn/tags/2.2.1-alpha/sample/picasa/picasa-atom-android-sample/instructions.html

But in the above example I think the user can only access albums, whereas I want to access photos also, which might need PhotoEntry Class, so can anyone suggest to me what files I need for Android previously to get photos from Picasa?

答:
I've come across this source code for a widget that uses picasa api.  It uses the older gdata api libraries.  I have been unable to get the new libraries to work for downloading.

http://droidphotoframe.svn.sourceforge.net/viewvc/droidphotoframe/trunk/

ContentLicense: CC BY-SA 3.0


问:
NGINX proxy_pass http://localhost:9999/ Not Found
I run my webapp on NGINX with the following configuration:

```<code># Based on https://www.nginx.com/resources/wiki/start/topics/examples/full/#nginx-conf
# user              www www;  ## Default: nobody

worker_processes  auto;
error_log         "/opt/bitnami/nginx/logs/error.log";
pid               "/opt/bitnami/nginx/tmp/nginx.pid";

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;
  log_format    main '$remote_addr - $remote_user [$time_local] '
  '"$request" $status  $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';
  access_log    "/opt/bitnami/nginx/logs/access.log";
  add_header    X-Frame-Options SAMEORIGIN;

  client_body_temp_path  "/opt/bitnami/nginx/tmp/client_body" 1 2;
  proxy_temp_path        "/opt/bitnami/nginx/tmp/proxy" 1 2;
  fastcgi_temp_path      "/opt/bitnami/nginx/tmp/fastcgi" 1 2;
  scgi_temp_path         "/opt/bitnami/nginx/tmp/scgi" 1 2;
  uwsgi_temp_path        "/opt/bitnami/nginx/tmp/uwsgi" 1 2;

  sendfile           on;
  tcp_nopush         on;
  tcp_nodelay        off;
  gzip               on;
  gzip_http_version  1.0;
  gzip_comp_level    2;
  gzip_proxied       any;
  gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  keepalive_timeout  65;
  ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;
  client_max_body_size 80M;
  server_tokens off;
  include  "/opt/bitnami/nginx/conf/server_blocks/*.conf";

  # HTTP Server
  server {
    # port to listen on. Can also be set to an IP:PORT
    listen  8080;

    location /api/* {
      proxy_set_header X-Forwarded-Host $host:$server_port;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://localhost:9999;

    }

    location /status {
      stub_status on;
      access_log   off;
      allow 127.0.0.1;
      deny all;
    }
  }
}
</code>```

and the way that I do the call:

```<code>methods: {
  load_user(event) {

    console.log(this.$kc)

    const config = {
      headers: {Authorization: `Bearer ${this.$kc.token}`}
    };

    this.$axios.get('/api/hello/sali', config)
      .then((response) => {
        console.log(response)
      })
      .catch(() => {
        console.log("errro")
      })
  },
</code>```

Then it shows the following message:

However, it should return:

What am I doing wrong?

答:
Not is recomendly that you put your web server inside of nginx configuration, you have that create a file inside of folder sites-enabled. And with the main problem:

In you javascript code you httpRequest is pointing to PORT 8090 but the port that is in nginx-config is 8080

The real problem is in your javascript code try with port 9999 or 8080

Body:
I run my webapp on NGINX with the following configuration:

# Based on https://www.nginx.com/resources/wiki/start/topics/examples/full/#nginx-conf
# user              www www;  ## Default: nobody

worker_processes  auto;
error_log         "/opt/bitnami/nginx/logs/error.log";
pid               "/opt/bitnami/nginx/tmp/nginx.pid";

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;
  log_format    main '$remote_addr - $remote_user [$time_local] '
  '"$request" $status  $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';
  access_log    "/opt/bitnami/nginx/logs/access.log";
  add_header    X-Frame-Options SAMEORIGIN;

  client_body_temp_path  "/opt/bitnami/nginx/tmp/client_body" 1 2;
  proxy_temp_path        "/opt/bitnami/nginx/tmp/proxy" 1 2;
  fastcgi_temp_path      "/opt/bitnami/nginx/tmp/fastcgi" 1 2;
  scgi_temp_path         "/opt/bitnami/nginx/tmp/scgi" 1 2;
  uwsgi_temp_path        "/opt/bitnami/nginx/tmp/uwsgi" 1 2;

  sendfile           on;
  tcp_nopush         on;
  tcp_nodelay        off;
  gzip               on;
  gzip_http_version  1.0;
  gzip_comp_level    2;
  gzip_proxied       any;
  gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  keepalive_timeout  65;
  ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;
  client_max_body_size 80M;
  server_tokens off;
  include  "/opt/bitnami/nginx/conf/server_blocks/*.conf";

  # HTTP Server
  server {
    # port to listen on. Can also be set to an IP:PORT
    listen  8080;

    location /api/* {
      proxy_set_header X-Forwarded-Host $host:$server_port;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://localhost:9999;

    }

    location /status {
      stub_status on;
      access_log   off;
      allow 127.0.0.1;
      deny all;
    }
  }
}

and the way that I do the call:

methods: {
  load_user(event) {

    console.log(this.$kc)

    const config = {
      headers: {Authorization: `Bearer ${this.$kc.token}`}
    };

    this.$axios.get('/api/hello/sali', config)
      .then((response) => {
        console.log(response)
      })
      .catch(() => {
        console.log("errro")
      })
  },

Then it shows the following message:

However, it should return:

What am I doing wrong?


问:
Method to refresh Fragment content when data changed ( like recall onCreateView)
I have an Activity with a fragment container in layout.
3 different Fragment can be displayed in it.
These fragments contains a Listview which displays data with custom Adapter i made.

So each list elements is created during onCreateView, after i queried a database to have data.

But sometimes some data may changes in my database, so i would like to redraw/recreate it the Listview.

What would be the best way (i mean, the less ressources demanding) to refresh my fragment view ?

Is there a method to recall onCreateView manually ?

答:
set in Fragment that you want to refresh</p>

```<code>    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
    super.setUserVisibleHint(isVisibleToUser)
    if(isVisibleToUser){
        if (getFragmentManager() != null) {
            getFragmentManager()
                ?.beginTransaction()
                ?.detach(this)
                ?.attach(this)
                ?.commit();
        }
    }
}
</code>```

Body:
set in Fragment that you want to refresh

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
    super.setUserVisibleHint(isVisibleToUser)
    if(isVisibleToUser){
        if (getFragmentManager() != null) {
            getFragmentManager()
                ?.beginTransaction()
                ?.detach(this)
                ?.attach(this)
                ?.commit();
        }
    }
}


问:
How to get the part of a string after the last occurrence of certain character?
I would like to have the substring after the last occurrence of a certin character.
Now I found here how to get the first, second or so parts, but I need only the last part.
The input data is a list of file directories:

```<code>c:\dir\subdir\subdir\file.txt
c:\dir\subdir\subdir\file2.dat
c:\dir\subdir\file3.png
c:\dir\subdir\subdir\subdir\file4.txt
</code>```

Unfortunately this is the data I have to work it, otherwise I could list it using command prompt.
The problem is that the number of the directories are always changing.
My code based on the previous link is:

```<code>select (regexp_split_to_array(BTRIM(path),'\\'))[1] from myschema.mytable
</code>```

So far I've tried some things in the brackets that came in to my mind. For example [end], [-1] etc.
Non of them are working. Is there a way to get the last part without rearranging my strings backwards, and getting the first part, then turning it back?

答:
You can use regexp_matches():

```<code>select (regexp_matches(path, '[^\\]+$'))[1]
</code>```

Here is a db<>fiddle.

Body:
I would like to have the substring after the last occurrence of a certin character.
Now I found here how to get the first, second or so parts, but I need only the last part.
The input data is a list of file directories:

c:\dir\subdir\subdir\file.txt
c:\dir\subdir\subdir\file2.dat
c:\dir\subdir\file3.png
c:\dir\subdir\subdir\subdir\file4.txt

Unfortunately this is the data I have to work it, otherwise I could list it using command prompt.
The problem is that the number of the directories are always changing.
My code based on the previous link is:

select (regexp_split_to_array(BTRIM(path),'\\'))[1] from myschema.mytable

So far I've tried some things in the brackets that came in to my mind. For example [end], [-1] etc.
Non of them are working. Is there a way to get the last part without rearranging my strings backwards, and getting the first part, then turning it back?

Body:
You can use regexp_matches():

select (regexp_matches(path, '[^\\]+$'))[1]

Here is a db<>fiddle.


问:
Discord.js Breaking down Ban Command for Command Handler issues
I have a rather large index.js so iv been busy stripping it out into individual command files, i have successfully exported all my code into separate commands, all but ban. So far the ban code works as intended, but if a 18 digit user ID is entered, and they have left the server it should check and log it in a .json file but currently its not getting past if (isNaN(args[1])) it just plain wont accept anything, number and or letters all result in "You need to enter a vlaid @Member or UserID #" This is very frustrating as it took me hours to get working within my index.js

 run: async (bot, message, args) => {

        if (!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send("You do not have permission to perform this command!")

        const user1 = message.mentions.users.first();
        var member = message.mentions.members.first()

        if (member) {

            const member = message.mentions.members.first()

            let reason = args.slice(2).join(' '); // arguments should already be defined
            var user = message.mentions.users.first();

            member.ban({ reason: `${args.slice(2).join(' ')}` }).then(() => {
                let uEmbed = new RichEmbed()
                    .setTitle('**' + `Sucessfully Banned ${user1.tag}!` + '**')
                    .setThumbnail('https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
                    .setImage('https://media3.giphy.com/media/H99r2HtnYs492/giphy.gif?cid=ecf05e47db8ad81dd0dbb6b132bb551add0955f9b92ba021&rid=giphy.gif')
                    .setColor(0x320b52)
                    .setTimestamp()
                    .setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
                message.channel.send(uEmbed);

            }).catch(err => {
                message.channel.send('I was unable to kick the member');
                console.log(err);
            });
        } else {
            let user = message.mentions.users.first(),
                userID = user ? user.id : args[1]

            if (isNaN(args[1])) return message.channel.send("You need to enter a vlaid @Member or UserID #");

            if (args[1].length <= 17 || args[1].length >= 19) return message.channel.send("UserID # must be 18 Digits");

            if (userID) {
                let bannedIDs = require('./bannedIDs.json').ids || []

                if (!bannedIDs.includes(userID)) bannedIDs.push(userID)

                fs.writeFileSync('./bannedIDs.json', JSON.stringify({ ids: bannedIDs }))
                let reason = args.slice(2).join(' ');
                let uEmbed = new RichEmbed()
                    .setTitle('**' + `UserID #${args[1]}\n Will be Banned on Return!` + '**')
                    .setThumbnail('https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
                    .setImage('https://i.imgur.com/6Sh8csf.gif')
                    .setColor(0x320b52)
                    .setTimestamp()
                    .setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
                    message.channel.send(uEmbed);

            } else {
                message.channel.send('Error')
            }
        }
    }

}

```

答: Firstly, if (args[1].length <= 17 || args[1].length >= 19 can be reduced to if(args[1].length !== 18), I saw your other post and it suggests you got passed this bug, is this correct?


问:
Why would adding a Mesh Collider make Inverse Kinematic legs mess up their movement?
Without mesh collider: https://imgur.com/a/0FQBqLG

With mesh collider: https://imgur.com/a/ho1sT9q (See how legs now walk unpredictably)

Can someone please explain what is the cause of this? Is it colliding with itself somehow? I don't know where to begin trying to fix this.

In case anyone is interested, the gecko setup is from a very cool procedural animation tutorial here: https://www.weaverdev.io/blog/bonehead-procedural-animation

Thank you for any help.

edit: Solved .. ended up being an unpredictable issue from my end (indeed it involved layers). Added my own answer to this which I will accept when it lets me. Thank you so much though for the assistance.

答: The feet movement was being controlled by Raycasting to Ground layer, but the ground layer was incorrectly set up on my end. This was therefore solved by correcting that issue. D'oh. Now collisions and movement work perfectly. Thank you all.</p>


问:
H.264 RTSP Absolute TIMESTAMP
Is it possible to read an absolute timestamp from an H.264 stream sent trough RTSP from an Axis camera?

It will be necessary to know when the frame has been taken by the camera.

Thanks
Andrea

答:
Assuming the cameras firmware works properly and it's synchronized with NTP regularly, you can extract the absolute timestamp from RTCP Sender Report. But this functionality is not available in FFMpeg library API, you have to use header libavformat/rtsp.h in order to access internal data structures. And then you have to calculate the ntp timestamp for every frame:

```<code>RTSPState* rtsp_state = (RTSPState*) pFormatCtx->priv_data;
RTSPStream* rtsp_stream = rtsp_state->rtsp_streams[0];
RTPDemuxContext* rtp_demux_context = (RTPDemuxContext*) rtsp_stream->transport_priv;

int32_t d_ts = rtp_demux_context->timestamp - rtp_demux_context->last_rtcp_timestamp;
uint64_t last_ntp_time = rtp_demux_context->last_rtcp_ntp_time;
uint32_t seconds = ((last_ntp_time >> 32) & 0xffffffff)-2208988800;
uint32_t fraction  = (last_ntp_time & 0xffffffff);
double useconds = ((double) fraction / 0xffffffff);
double base_time = seconds+useconds;

double frame_ntp_time = base_time+d_ts/90000.0;
</code>```

Full example is here.

Title: H.264 RTSP Absolute TIMESTAMP

Body:
Assuming the cameras firmware works properly and it's synchronized with NTP regularly, you can extract the absolute timestamp from RTCP Sender Report. But this functionality is not available in FFMpeg library API, you have to use header libavformat/rtsp.h in order to access internal data structures. And then you have to calculate the ntp timestamp for every frame:

RTSPState* rtsp_state = (RTSPState*) pFormatCtx->priv_data;
RTSPStream* rtsp_stream = rtsp_state->rtsp_streams[0];
RTPDemuxContext* rtp_demux_context = (RTPDemuxContext*) rtsp_stream->transport_priv;

int32_t d_ts = rtp_demux_context->timestamp - rtp_demux_context->last_rtcp_timestamp;
uint64_t last_ntp_time = rtp_demux_context->last_rtcp_ntp_time;
uint32_t seconds = ((last_ntp_time >> 32) & 0xffffffff)-2208988800;
uint32_t fraction  = (last_ntp_time & 0xffffffff);
double useconds = ((double) fraction / 0xffffffff);
double base_time = seconds+useconds;

double frame_ntp_time = base_time+d_ts/90000.0;

Full example is here.


问:
Cannot install npm package in Angular project
I clone my project from GitLab and I need to install the NPM packages in my project.

When I run npm install it shows me this error:

and I go to the log file and see:

```<code>30601 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30601 verbose stack     at JSON.parse (<anonymous>)
30601 verbose stack     at parseJson (/usr/lib/node_modules/npm/node_modules/json-parse-better-errors/index.js:7:17)
30601 verbose stack     at /usr/lib/node_modules/npm/node_modules/node-fetch-npm/src/body.js:96:50
30601 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
30602 verbose cwd /home/mrcoder/Projects/Angular/Ava/PFA/pfa-front-cpl
30603 verbose Linux 5.4.0-33-generic
30604 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
30605 verbose node v12.17.0
30606 verbose npm  v6.14.4
30607 error Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30608 verbose exit [ 1, true ]
</code>```

This is my package.json:

```<code>{
  "name": "vex",
  "version": "9.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.7",
    "@angular/cdk": "~9.1.3",
    "@angular/common": "~9.0.7",
    "@angular/compiler": "~9.0.7",
    "@angular/core": "~9.0.7",
    "@angular/flex-layout": "9.0.0-beta.29",
    "@angular/forms": "~9.0.7",
    "@angular/material": "~9.1.3",
    "@angular/platform-browser": "~9.0.7",
    "@angular/platform-browser-dynamic": "~9.0.7",
    "@angular/router": "~9.0.7",
    "@iconify/icons-emojione": "~1.0.5",
    "@iconify/icons-fa-brands": "~1.0.10",
    "@iconify/icons-fa-solid": "~1.0.8",
    "@iconify/icons-ic": "~1.0.9",
    "@iconify/icons-logos": "~1.0.9",
    "@ngrx/store": "^9.1.2",
    "@ngx-loading-bar/core": "~5.0.0-alpha.1",
    "@ngx-loading-bar/router": "~5.0.0-alpha.1",
    "@ngx-translate/core": "^12.1.2",
    "@visurel/iconify-angular": "^0.0.7",
    "angular-calendar": "~0.28.5",
    "angular2-promise-buttons": "^4.0.6",
    "apexcharts": "~3.17.0",
    "color": "~3.1.2",
    "date-fns": "~2.11.0",
    "highlight.js": "~9.18.1",
    "jalali-moment": "^3.3.3",
    "luxon": "~1.22.0",
    "ng2-jalali-date-picker": "^2.3.0",
    "ngx-material-file-input": "^2.1.1",
    "ngx-quill": "~8.1.0",
    "ngx-showdown": "~5.1.0",
    "ngx-take-until-destroy": "~5.4.0",
    "ngx-toastr": "^12.0.1",
    "quill": "~1.3.7",
    "rxjs": "~6.5.4",
    "showdown": "^1.9.1",
    "simplebar": "~4.2.3",
    "tailwindcss": "~1.2.0",
    "tslib": "~1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "~9.0.0",
    "@angular-devkit/build-angular": "~0.900.7",
    "@angular/cli": "~9.0.7",
    "@angular/compiler-cli": "~9.0.7",
    "@angular/language-service": "~9.0.7",
    "@fullhuman/purgecss-loader": "^1.0.0",
    "@types/color": "~3.0.0",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/luxon": "~1.22.0",
    "@types/node": "~13.9.3",
    "@types/showdown": "~1.9.3",
    "@types/simplebar": "~5.1.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "postcss-loader": "~3.0.0",
    "postcss-scss": "~2.0.0",
    "protractor": "~5.4.0",
    "tailwindcss-dir": "~4.0.0",
    "ts-node": "^8.8.1",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}
</code>```

What's the problem? How can I solve it?

答:
Actually you are having some issue in your package-lock.json. Because package-lock.json inserts a integrity key with each dependency in that json. Sometimes that json gets disformed/corrupted so when npm goes to read it next time to figure out what version of dependency to install. It gives this kind of error. The steps given below can resolve this issue.

Delete package-lock.json.

Delete node_modules

Run npm cache clean --force

Run npm install.

Body:
I clone my project from GitLab and I need to install the NPM packages in my project.

When I run npm install it shows me this error:

and I go to the log file and see:

30601 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30601 verbose stack     at JSON.parse (<anonymous>)
30601 verbose stack     at parseJson (/usr/lib/node_modules/npm/node_modules/json-parse-better-errors/index.js:7:17)
30601 verbose stack     at /usr/lib/node_modules/npm/node_modules/node-fetch-npm/src/body.js:96:50
30601 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
30602 verbose cwd /home/mrcoder/Projects/Angular/Ava/PFA/pfa-front-cpl
30603 verbose Linux 5.4.0-33-generic
30604 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
30605 verbose node v12.17.0
30606 verbose npm  v6.14.4
30607 error Unexpected end of JSON input while parsing near '...19"},"dist":{"integri'
30608 verbose exit [ 1, true ]

This is my package.json:

{
  "name": "vex",
  "version": "9.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.7",
    "@angular/cdk": "~9.1.3",
    "@angular/common": "~9.0.7",
    "@angular/compiler": "~9.0.7",
    "@angular/core": "~9.0.7",
    "@angular/flex-layout": "9.0.0-beta.29",
    "@angular/forms": "~9.0.7",
    "@angular/material": "~9.1.3",
    "@angular/platform-browser": "~9.0.7",
    "@angular/platform-browser-dynamic": "~9.0.7",
    "@angular/router": "~9.0.7",
    "@iconify/icons-emojione": "~1.0.5",
    "@iconify/icons-fa-brands": "~1.0.10",
    "@iconify/icons-fa-solid": "~1.0.8",
    "@iconify/icons-ic": "~1.0.9",
    "@iconify/icons-logos": "~1.0.9",
    "@ngrx/store": "^9.1.2",
    "@ngx-loading-bar/core": "~5.0.0-alpha.1",
    "@ngx-loading-bar/router": "~5.0.0-alpha.1",
    "@ngx-translate/core": "^12.1.2",
    "@visurel/iconify-angular": "^0.0.7",
    "angular-calendar": "~0.28.5",
    "angular2-promise-buttons": "^4.0.6",
    "apexcharts": "~3.17.0",
    "color": "~3.1.2",
    "date-fns": "~2.11.0",
    "highlight.js": "~9.18.1",
    "jalali-moment": "^3.3.3",
    "luxon": "~1.22.0",
    "ng2-jalali-date-picker": "^2.3.0",
    "ngx-material-file-input": "^2.1.1",
    "ngx-quill": "~8.1.0",
    "ngx-showdown": "~5.1.0",
    "ngx-take-until-destroy": "~5.4.0",
    "ngx-toastr": "^12.0.1",
    "quill": "~1.3.7",
    "rxjs": "~6.5.4",
    "showdown": "^1.9.1",
    "simplebar": "~4.2.3",
    "tailwindcss": "~1.2.0",
    "tslib": "~1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "~9.0.0",
    "@angular-devkit/build-angular": "~0.900.7",
    "@angular/cli": "~9.0.7",
    "@angular/compiler-cli": "~9.0.7",
    "@angular/language-service": "~9.0.7",
    "@fullhuman/purgecss-loader": "^1.0.0",
    "@types/color": "~3.0.0",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/luxon": "~1.22.0",
    "@types/node": "~13.9.3",
    "@types/showdown": "~1.9.3",
    "@types/simplebar": "~5.1.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "postcss-loader": "~3.0.0",
    "postcss-scss": "~2.0.0",
    "protractor": "~5.4.0",
    "tailwindcss-dir": "~4.0.0",
    "ts-node": "^8.8.1",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}

What's the problem? How can I solve it?


问:
Vlookup() equivalent in Dplyr
My df looks like:

```<code>library(tidyverse)
df_1 <- tibble::tribble(
          ~sub_date, ~value_1, ~value_2,
          "2020-05",       58,      130,
          "2020-05",       58,       "check",
          "2020-03",       50,      120,
          "2020-03",       55,       "check",
          "2020-03",       55,       "check"
          )
</code>```

I want to change the values of the rows containing "check" with the reference values here:

```<code>df_ref <- tibble::tribble(
            ~sub_date, ~ref_value,
            "2020-05",        123,
            "2020-03",        234
            )
</code>```

Basically - using the df_ref table as a reference only for the rows containing check.

I want to use the equivalent of a lookup() in excel, used in a if() function.

Final result being:

```<code>df_final <- tibble::tribble(
              ~sub_date, ~value_1, ~value_2,
              "2020-05",       58,      130,
              "2020-05",       58,      123,
              "2020-03",       50,      120,
              "2020-03",       55,      234,
              "2020-03",       55,      234
              )
</code>```

Title: Vlookup() equivalent in Dplyr

Body:
My df looks like:

library(tidyverse)
df_1 <- tibble::tribble(
          ~sub_date, ~value_1, ~value_2,
          "2020-05",       58,      130,
          "2020-05",       58,       "check",
          "2020-03",       50,      120,
          "2020-03",       55,       "check",
          "2020-03",       55,       "check"
          )

I want to change the values of the rows containing "check" with the reference values here:

df_ref <- tibble::tribble(
            ~sub_date, ~ref_value,
            "2020-05",        123,
            "2020-03",        234
            )

Basically - using the df_ref table as a reference only for the rows containing check.

I want to use the equivalent of a lookup() in excel, used in a if() function.

Final result being:

df_final <- tibble::tribble(
              ~sub_date, ~value_1, ~value_2,
              "2020-05",       58,      130,
              "2020-05",       58,      123,
              "2020-03",       50,      120,
              "2020-03",       55,      234,
              "2020-03",       55,      234
              )

Body:
Using base R:

ref_lut <- with(df_ref, setNames(ref_value, sub_date))

df_1$value_2 <-
  ifelse(df_1$value_2 == "check", ref_lut[df_1$sub_date], df_1$value_2)

df_1

  sub_date value_1 value_2
  <chr>      <dbl> <chr>
1 2020-05       58 130
2 2020-05       58 123
3 2020-03       50 120
4 2020-03       55 234
5 2020-03       55 234


问:
AWS Lambda verify requests from Slack
I have the following Python code in AWS Lambda to verify if an event received is indeed from Slack:

```<code>   import hmac
   import json
   def verifySignature(header,body):
        h = hmac.new(key=os.getenv('sign_secret').encode(), \
            msg=f'v0:{header.get("X-Slack-Request-Timestamp")}:{body}'.encode(), \
            digestmod="sha256")
        result = hmac.compare_digest('v0='+h.hexdigest(),header.get('X-Slack-Signature'))
        print('v0='+h.hexdigest(),header.get('X-Slack-Signature'))
        return result

    def lambda_handler(event, context):
        body = json.loads(event.get('body'))
        if verifySignature(event.get('headers'),body):
            do_something()
</code>```

Slack's authentication protocol is outlined here. However, I keep getting mismatching signatures (result == False). Does anyone know why?

答:
There is a high chance the issue is coming from the encoding / decoding. There is pip package to verify the slack signature.

But the verification code is simple:

import hashlib
import hmac

def verify_slack_signature(slack_post_request, slack_signing_secret):
    slack_signing_secret = bytes(slack_signing_secret, 'utf-8')
    slack_signature = slack_post_request['headers']['X-Slack-Signature']
    slack_request_timestamp = slack_post_request['headers']['X-Slack-Request-Timestamp']
    request_body = slack_post_request["body"]

    basestring = f"v0:{slack_request_timestamp}:{request_body}".encode('utf-8')
    my_signature = 'v0=' + hmac.new(slack_signing_secret, basestring, hashlib.sha256).hexdigest()

    return hmac.compare_digest(my_signature, slack_signature)
```

Title: AWS Lambda verify requests from Slack

Body:
I have the following Python code in AWS Lambda to verify if an event received is indeed from Slack:

   import hmac
   import json
   def verifySignature(header,body):
        h = hmac.new(key=os.getenv('sign_secret').encode(), \
            msg=f'v0:{header.get("X-Slack-Request-Timestamp")}:{body}'.encode(), \
            digestmod="sha256")
        result = hmac.compare_digest('v0='+h.hexdigest(),header.get('X-Slack-Signature'))
        print('v0='+h.hexdigest(),header.get('X-Slack-Signature'))
        return result

    def lambda_handler(event, context):
        body = json.loads(event.get('body'))
        if verifySignature(event.get('headers'),body):
            do_something()

Slack's authentication protocol is outlined here. However, I keep getting mismatching signatures (result == False). Does anyone know why?


问:
Flutter - Passing data between stateful widget in a socket connection
I am new to flutter and I am woking on sockets which keeps streaming data which I need to update on a appbar. So I have to stateful widgets

```<code>class _HomePageState extends State<HomePage> {
TickerAppBar appBar = TickerAppBar();
//Some declarations

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    connectionSetup();
  }

connectionSetup() async {
    this.socket.connect(connectionString);
    this.socket.sendSubscription(subscriptionString);
    await processData();
}

Future<Null> processData() async{
    subscription = socket.streamController.stream.listen(
        (data) {
         appBar.setStreamData(data); //Passing data into appbar widget
         //rest of the code of current widget
         }
     );
}

@override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: appBar,
        //rest of the code
    )
}

}

class TickerAppBar extends StatefulWidget implements PreferredSizeWidget  {
String streamData;
_TickerAppBarState child = _TickerAppBarState();

setStreamData(data){
    this.streamData = data;
    child.processData(); //To invoke the function every time the data is passed
  }
}

class _TickerAppBarState extends State<TickerAppBar>{

Future<String> processData() async{
//Cannot set state here since its a constructor and the widget is not mounted.
}

}

</code>```

So how I can set the data every time the data is passed into tickerappbar? so that my custom appbar displays new data which comes in every second.

答: I would suggest you follow the BLoC pattern, in which you can define your streams at one place and subscribe to the said stream from any widget, once you have the data ready, you can write to the stream and it will be shared on all the subscribed widgets.</p>

Body:
I am new to flutter and I am woking on sockets which keeps streaming data which I need to update on a appbar. So I have to stateful widgets

class _HomePageState extends State<HomePage> {
TickerAppBar appBar = TickerAppBar();
//Some declarations

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    connectionSetup();
  }

connectionSetup() async {
    this.socket.connect(connectionString);
    this.socket.sendSubscription(subscriptionString);
    await processData();
}

Future<Null> processData() async{
    subscription = socket.streamController.stream.listen(
        (data) {
         appBar.setStreamData(data); //Passing data into appbar widget
         //rest of the code of current widget
         }
     );
}

@override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: appBar,
        //rest of the code
    )
}

}

class TickerAppBar extends StatefulWidget implements PreferredSizeWidget  {
String streamData;
_TickerAppBarState child = _TickerAppBarState();

setStreamData(data){
    this.streamData = data;
    child.processData(); //To invoke the function every time the data is passed
  }
}

class _TickerAppBarState extends State<TickerAppBar>{

Future<String> processData() async{
//Cannot set state here since its a constructor and the widget is not mounted.
}

}

So how I can set the data every time the data is passed into tickerappbar? so that my custom appbar displays new data which comes in every second.


问:
Using django-widget-tweaks with Jinja2 template engine
I'm using django v1.11.7 with Jinja2 v2.10 as the template engine.

In my website, I wish to render forms using bootstrap. I found out that django-widget-tweaks can be used for this integration.

This package won't work with Jinja templates, since it needs to load a custom tag set into the Jinja environment. Loading tag sets can be complex, since I may need to write an extension.

Is there an easy way to get django-widget-tweaks to work with Jinja? Or is there another way for integrating boostrap with Jinja?

答:
A little late but maybe this can help.

What I did is import the function I wanted to use and called them in my jinja templates:

app_root.jinja2.py

```<code>from jinja2 import Environment
from jinja2 import contextfunction

from widget_tweaks.templatetags.widget_tweaks import render_field

def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'render_field': render_field,
    })
    return env
</code>```

In template

```<code>{% set class = class + "my-html-class" %}
{{ render_field(field, class) }}
</code>```

EDIT: Anyone with a little bit of Jinja and template tag experience knows this won't work. For my current needs, I defined the two following function in my jinja config and will evaluate my needs at a later time.

```<code>def set_attr(bound_field, attr, value):
    bound_field.field.widget.attrs[attr] = value
    return bound_field

def add_class(bound_field, value):
    try:
        bound_field.field.widget.attrs['class'] += value
    except KeyError:
        bound_field.field.widget.attrs['class'] = value
    return bound_field
</code>```

EDIT 2
Other useful link: https://github.com/niwinz/django-jinja/issues/140

To make this solution work, I had to make these changes:
jinja2.py

```<code>from jinja2 import Environment
from widget_tweaks.templatetags.widget_tweaks import add_class
from widget_tweaks.templatetags.widget_tweaks import set_attr

def environment(**options):
    env = Environment(**options)
    env.filters['set_attr'] = set_attr
    env.filters['add_class'] = add_class
    return env
</code>```

template.html

```<code>{{ form.field |set_attr('attr:val') }}
{{ form.field |add_class('my_class') }}
</code>```

Body:
A little late but maybe this can help.

What I did is import the function I wanted to use and called them in my jinja templates:

app_root.jinja2.py

from jinja2 import Environment
from jinja2 import contextfunction

from widget_tweaks.templatetags.widget_tweaks import render_field

def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'render_field': render_field,
    })
    return env

In template

{% set class = class + "my-html-class" %}
{{ render_field(field, class) }}

EDIT: Anyone with a little bit of Jinja and template tag experience knows this won't work. For my current needs, I defined the two following function in my jinja config and will evaluate my needs at a later time.

def set_attr(bound_field, attr, value):
    bound_field.field.widget.attrs[attr] = value
    return bound_field

def add_class(bound_field, value):
    try:
        bound_field.field.widget.attrs['class'] += value
    except KeyError:
        bound_field.field.widget.attrs['class'] = value
    return bound_field

EDIT 2
Other useful link: https://github.com/niwinz/django-jinja/issues/140

To make this solution work, I had to make these changes:
jinja2.py

from jinja2 import Environment
from widget_tweaks.templatetags.widget_tweaks import add_class
from widget_tweaks.templatetags.widget_tweaks import set_attr

def environment(**options):
    env = Environment(**options)
    env.filters['set_attr'] = set_attr
    env.filters['add_class'] = add_class
    return env

template.html

{{ form.field |set_attr('attr:val') }}
{{ form.field |add_class('my_class') }}


问:
Angular: configure default QueryParamsHandling
I've built an angular 9 app, and added localization with @ngx-translate. I've configured my app so that it takes the lang query parameter and changes the locale accordingly.

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  constructor(private route: ActivatedRoute, private translateService: TranslateService) {
    this.translateService.setDefaultLang('en');
    this.route.queryParamMap.subscribe((params) => {
      let lang = params.get('lang');
      console.log('language', lang);
      if (lang !== null) {
        this.translateService.use(lang);
      }
    });
  }
}
</code>```

I then added 3 buttons on my sidebar to change the query parameter (and switch the language)

```<code><div class="p-1 text-center">
  <a [routerLink]='[]' [queryParams]="{}">
    <app-flag [country]="'en'" [appHoverClass]="'brightness-250'"></app-flag>
  </a>
  <a [routerLink]='[]' [queryParams]="{'lang':'nl'}">
    <app-flag [country]="'nl'" [appHoverClass]="'brightness-250'"></app-flag>
  </a>
  <a [routerLink]='[]' [queryParams]="{'lang':'fr'}">
    <app-flag [country]="'fr'" [appHoverClass]="'brightness-250'"></app-flag>
  </a>
</div>
</code>```

This is working fine. But when a normal routerLink is pressed, or at a router.navigate() call, the query parameters are lost again.

I don't want to decorate each and every routerLink in my application with the [queryParamsHandling]="'preserve'" directive since this is a tedious job and horrible practice. There is already a GitHub issue active for this topic, but the angular team is pretty much not working on it (for 4 years already): https://github.com/angular/angular/issues/12664

Is there a way (any way) to have the query parameters (or just the lang query parameter) preserved by default when navigating?

I've already created an ExtendedRouter on top of the default angular router

```<code>import { Router, QueryParamsHandling, NavigationExtras, UrlTree } from '@angular/router';

export class ExtendedRouter {
  constructor(private router: Router) {
  }

  private _defaultQueryParamsHandling: QueryParamsHandling = null;
  public get defaultQueryParamsHandling() {
    return this._defaultQueryParamsHandling;
  }
  public set defaultQueryParamsHandling(value: QueryParamsHandling) {
    this._defaultQueryParamsHandling = value;
  }

  public navigate(commands: any[], extras?: NavigationExtras) {
    return this.router.navigate(commands, {
      queryParamsHandling: extras.queryParamsHandling ?? this.defaultQueryParamsHandling ?? '',
      fragment: extras.fragment,
      preserveFragment: extras.preserveFragment,
      queryParams: extras.queryParams,
      relativeTo: extras.relativeTo,
      replaceUrl: extras.replaceUrl,
      skipLocationChange: extras.skipLocationChange
    });
  }

  public navigateByUrl(url: string | UrlTree, extras?: NavigationExtras) {
    return this.router.navigateByUrl(url, {
      queryParamsHandling: extras.queryParamsHandling ?? this.defaultQueryParamsHandling ?? '',
      fragment: extras.fragment,
      preserveFragment: extras.preserveFragment,
      queryParams: extras.queryParams,
      relativeTo: extras.relativeTo,
      replaceUrl: extras.replaceUrl,
      skipLocationChange: extras.skipLocationChange
    });
  }

  public createUrlTree(commands: any[], extras?: NavigationExtras) {
    return this.router.createUrlTree(commands, extras);
  }

  public serializeUrl(url: UrlTree) {
    return this.router.serializeUrl(url);
  }
}
</code>```

But this doesn't deal with the [routerLink] directive. I've tried creating one as well, but all fields I need are scoped to private.

```<code>import { Directive, Renderer2, ElementRef, Attribute, Input } from '@angular/core';
import { RouterLink, Router, ActivatedRoute } from '@angular/router';
import { ExtendedRouter } from '../../helpers/extended-router';

@Directive({
  selector: '[extendedRouterLink]'
})
export class ExtendedRouterLinkDirective extends RouterLink {

  private router2: Router;
  private route2: ActivatedRoute;
  private commands2: any[] = [];
  constructor(router: Router, route: ActivatedRoute, @Attribute('tabindex') tabIndex: string, renderer: Renderer2, el: ElementRef<any>, private extendedRouter: ExtendedRouter) {
    super(router, route, tabIndex, renderer, el);
    this.router2 = router;
    this.route2 = route;
  }

  @Input()
  set extendedRouterLink(commands: any[] | string | null | undefined) {
    if (commands != null) {
      this.commands2 = Array.isArray(commands) ? commands : [commands];
    } else {
      this.commands2 = [];
    }
    super.commands = commands;
  }

  get urlTree() {
    return this.router2.createUrlTree(this.commands, {
      relativeTo: this.route2,
      queryParams: this.queryParams,
      fragment: this.fragment,
      queryParamsHandling: this.queryParamsHandling,
      preserveFragment: this.attrBoolValue(this.preserveFragment),
    });
  }

  private attrBoolValue = (s: any) => {
    return s === '' || !!s;
  }

}
</code>```

Anyone an idea how to get around this without having to define a [queryParamsHandling] on each [routerLink]?

答:
There is a small problem with this approach:

@Directive({
  selector: 'a[routerLink]'
})
export class QueryParamsHandlingDirective extends RouterLinkWithHref {
  queryParamsHandling: QueryParamsHandling = 'merge';
}
```

<p>The problem is that it extends <code>RouterLinkWithHref</code>, meaning an <code></code> will have <strong>2 directives</strong>(one which extends the other) attached to it.</p>

<p>And this is what happens inside <code>RouterLinkWithHref</code>'s <code>click</code> handler:</p>

<pre class="lang-js prettyprint-override"><code>@HostListener('click')
onClick(): boolean {
  const extras = {
    skipLocationChange: attrBoolValue(this.skipLocationChange),
    replaceUrl: attrBoolValue(this.replaceUrl),
    state: this.state,
  };
  this.router.navigateByUrl(this.urlTree, extras);
  return true;
}
</code>```

What's more important is how this looks when it's shipped to the browser:

 RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey, shiftKey) {
  if (button !== 0 || ctrlKey || metaKey || shiftKey) {
      return true;
  }
  if (typeof this.target === 'string' && this.target != '_self') {
      return true;
  }
  var extras = {
      skipLocationChange: attrBoolValue(this.skipLocationChange),
      replaceUrl: attrBoolValue(this.replaceUrl),
      state: this.state
  };
  this.router.navigateByUrl(this.urlTree, extras);
  return false;
};
```

<p>This means that when you click on an <code><a></code> tag, the <code>QueryParamsHandlingDirective.onClick</code> will be invoked, and then <code>RouterLinkWithHref.onClick</code>. But since <code>RouterLinkWithHref.onClick</code> is called last, it won't have the <code>queryParamsHandling</code> set to <code>merge</code>.</p>

<hr>

<p>The solution is to slightly modify the custom directive so that it <strong>does not inherit</strong> anything, but simply sets a property:</p>

<pre class="lang-js prettyprint-override"><code>@Directive({
  selector: 'a[routerLink]'
})
export class QueryParamsHandlingDirective {
  constructor (routerLink: RouterLinkWithHref) {
    routerLink.queryParamsHandling = 'merge';
  }
}
</code>```

href="https://stackblitz.com/edit/angular-routing-preserve-queryparams-link-from-routing-c-eew3gj?file=src/app/directives/query-params-handling/query-params-handling.directive.ts" rel="nofollow noreferrer">StackBlitz.

Body:
I've built an angular 9 app, and added localization with @ngx-translate. I've configured my app so that it takes the lang query parameter and changes the locale accordingly.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  constructor(private route: ActivatedRoute, private translateService: TranslateService) {
    this.translateService.setDefaultLang('en');
    this.route.queryParamMap.subscribe((params) => {
      let lang = params.get('lang');
      console.log('language', lang);
      if (lang !== null) {
        this.translateService.use(lang);
      }
    });
  }
}

I then added 3 buttons on my sidebar to change the query parameter (and switch the language)

    <app-flag [country]="'en'" [appHoverClass]="'brightness-250'"></app-flag>

    <app-flag [country]="'nl'" [appHoverClass]="'brightness-250'"></app-flag>

    <app-flag [country]="'fr'" [appHoverClass]="'brightness-250'"></app-flag>

This is working fine. But when a normal routerLink is pressed, or at a router.navigate() call, the query parameters are lost again.

I don't want to decorate each and every routerLink in my application with the [queryParamsHandling]="'preserve'" directive since this is a tedious job and horrible practice. There is already a GitHub issue active for this topic, but the angular team is pretty much not working on it (for 4 years already): https://github.com/angular/angular/issues/12664

Is there a way (any way) to have the query parameters (or just the lang query parameter) preserved by default when navigating?

I've already created an ExtendedRouter on top of the default angular router

import { Router, QueryParamsHandling, NavigationExtras, UrlTree } from '@angular/router';

export class ExtendedRouter {
  constructor(private router: Router) {
  }

  private _defaultQueryParamsHandling: QueryParamsHandling = null;
  public get defaultQueryParamsHandling() {
    return this._defaultQueryParamsHandling;
  }
  public set defaultQueryParamsHandling(value: QueryParamsHandling) {
    this._defaultQueryParamsHandling = value;
  }

  public navigate(commands: any[], extras?: NavigationExtras) {
    return this.router.navigate(commands, {
      queryParamsHandling: extras.queryParamsHandling ?? this.defaultQueryParamsHandling ?? '',
      fragment: extras.fragment,
      preserveFragment: extras.preserveFragment,
      queryParams: extras.queryParams,
      relativeTo: extras.relativeTo,
      replaceUrl: extras.replaceUrl,
      skipLocationChange: extras.skipLocationChange
    });
  }

  public navigateByUrl(url: string | UrlTree, extras?: NavigationExtras) {
    return this.router.navigateByUrl(url, {
      queryParamsHandling: extras.queryParamsHandling ?? this.defaultQueryParamsHandling ?? '',
      fragment: extras.fragment,
      preserveFragment: extras.preserveFragment,
      queryParams: extras.queryParams,
      relativeTo: extras.relativeTo,
      replaceUrl: extras.replaceUrl,
      skipLocationChange: extras.skipLocationChange
    });
  }

  public createUrlTree(commands: any[], extras?: NavigationExtras) {
    return this.router.createUrlTree(commands, extras);
  }

  public serializeUrl(url: UrlTree) {
    return this.router.serializeUrl(url);
  }
}

But this doesn't deal with the [routerLink] directive. I've tried creating one as well, but all fields I need are scoped to private.

import { Directive, Renderer2, ElementRef, Attribute, Input } from '@angular/core';
import { RouterLink, Router, ActivatedRoute } from '@angular/router';
import { ExtendedRouter } from '../../helpers/extended-router';

@Directive({
  selector: '[extendedRouterLink]'
})
export class ExtendedRouterLinkDirective extends RouterLink {

  private router2: Router;
  private route2: ActivatedRoute;
  private commands2: any[] = [];
  constructor(router: Router, route: ActivatedRoute, @Attribute('tabindex') tabIndex: string, renderer: Renderer2, el: ElementRef<any>, private extendedRouter: ExtendedRouter) {
    super(router, route, tabIndex, renderer, el);
    this.router2 = router;
    this.route2 = route;
  }

  @Input()
  set extendedRouterLink(commands: any[] | string | null | undefined) {
    if (commands != null) {
      this.commands2 = Array.isArray(commands) ? commands : [commands];
    } else {
      this.commands2 = [];
    }
    super.commands = commands;
  }

  get urlTree() {
    return this.router2.createUrlTree(this.commands, {
      relativeTo: this.route2,
      queryParams: this.queryParams,
      fragment: this.fragment,
      queryParamsHandling: this.queryParamsHandling,
      preserveFragment: this.attrBoolValue(this.preserveFragment),
    });
  }

  private attrBoolValue = (s: any) => {
    return s === '' || !!s;
  }

}

Anyone an idea how to get around this without having to define a [queryParamsHandling] on each [routerLink]?

Body:
There is a small problem with this approach:

@Directive({
  selector: 'a[routerLink]'
})
export class QueryParamsHandlingDirective extends RouterLinkWithHref {
  queryParamsHandling: QueryParamsHandling = 'merge';
}

The problem is that it extends RouterLinkWithHref, meaning an <a routerLink=""> will have 2 directives(one which extends the other) attached to it.

And this is what happens inside RouterLinkWithHref's click handler:

@HostListener('click')
onClick(): boolean {
  const extras = {
    skipLocationChange: attrBoolValue(this.skipLocationChange),
    replaceUrl: attrBoolValue(this.replaceUrl),
    state: this.state,
  };
  this.router.navigateByUrl(this.urlTree, extras);
  return true;
}

What's more important is how this looks when it's shipped to the browser:

 RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey, shiftKey) {
  if (button !== 0 || ctrlKey || metaKey || shiftKey) {
      return true;
  }
  if (typeof this.target === 'string' && this.target != '_self') {
      return true;
  }
  var extras = {
      skipLocationChange: attrBoolValue(this.skipLocationChange),
      replaceUrl: attrBoolValue(this.replaceUrl),
      state: this.state
  };
  this.router.navigateByUrl(this.urlTree, extras);
  return false;
};

This means that when you click on an <a> tag, the QueryParamsHandlingDirective.onClick will be invoked, and then RouterLinkWithHref.onClick. But since RouterLinkWithHref.onClick is called last, it won't have the queryParamsHandling set to merge.

The solution is to slightly modify the custom directive so that it does not inherit anything, but simply sets a property:

@Directive({
  selector: 'a[routerLink]'
})
export class QueryParamsHandlingDirective {
  constructor (routerLink: RouterLinkWithHref) {
    routerLink.queryParamsHandling = 'merge';
  }
}

StackBlitz.


问:
AdapterContextMenuInfo.id
I have looked online about this. So my understanding is that AdapterContextMenuInfo.position is the index of the item in the listview.

Is AdapterContextMenuInfo.id the index of the item in the Cursor or the primary key id of the item in the database? I have used it as the primary key id of the item in the database. Are cursors indexed by primary key?

答:
Is AdapterContextMenuInfo.id the index of the item in the Cursor or the primary key id of the item in the database?

It is the value of the _id column that is inside your Cursor, when you are using a CursorAdapter.

Are cursors indexed by primary key?

Cursors are not indexed, period. However, to use CursorAdapter, you must have a column in the Cursor's result set that has the name _id.

Title: AdapterContextMenuInfo.id


问:
how to get selected file path in javascript
get selected file path from JavaScript. Hi! I want to get selected file path from JavaScript

```<code><input type="file" class="input-file" id="inputfile" onchange="ReadFile()">
</code>```

here I want to assign file path to model.

```<code>function GetFileProerties() {
    var fileproperties = {
        "FileName": upload.files[0].name,
        "FilePath": ** here i want to assign selected file path ** ,
        "FileType": upload.files[0].name.substr((upload.files[0].name.lastIndexOf('.') + 1)),
        "FileSize": upload.files[0].size,
        "Modified Date": upload.files[0].lastModifiedDate
    }
    return JSON.stringify(fileproperties);
}
</code>```

答: Like you, I used <input type="file"...> to allow user to select file they want me to pull data from, and now need to connect with that file to pull the data.  My next attempt is combining event listener and loop to grab the file, path after it is selected.

Body:
get selected file path from JavaScript. Hi! I want to get selected file path from JavaScript

<input type="file" class="input-file" id="inputfile" onchange="ReadFile()">

here I want to assign file path to model.

function GetFileProerties() {
    var fileproperties = {
        "FileName": upload.files[0].name,
        "FilePath": ** here i want to assign selected file path ** ,
        "FileType": upload.files[0].name.substr((upload.files[0].name.lastIndexOf('.') + 1)),
        "FileSize": upload.files[0].size,
        "Modified Date": upload.files[0].lastModifiedDate
    }
    return JSON.stringify(fileproperties);
}


问:
Need to add missing value from pandas column
I've two pandas dataframe having one common column in both but they are not having same values. Wish to get the missing values to another dataframe common column.</p>

```<code>df1

name    mobile  email
abcd    992293  abcd@abcd.com
efgh    687678  efgh@efgh.com
ijkl    7878678 ijkl@ijkl.com
mnop    678687  mnop@mnop.com
qrst    6876    qrst@qrst.com

</code>```

```<code>df2

name    age
abcd    22
efgh    12
</code>```

```<code>Expected output

name    age
abcd    22
efgh    12
ijkl
mnop
qrst
</code>```

答:
This is a simple case of joining two data frames on a common key:</p>

```<code>pd.merge(df1, df2, on='name',how='left')
</code>```

Body:
I've two pandas dataframe having one common column in both but they are not having same values. Wish to get the missing values to another dataframe common column.

df1

name    mobile  email
abcd    992293  abcd@abcd.com
efgh    687678  efgh@efgh.com
ijkl    7878678 ijkl@ijkl.com
mnop    678687  mnop@mnop.com
qrst    6876    qrst@qrst.com

df2

name    age
abcd    22
efgh    12

Expected output

name    age
abcd    22
efgh    12
ijkl
mnop
qrst

Body:
This is a simple case of joining two data frames on a common key:

pd.merge(df1, df2, on='name',how='left')


问:
How to align radio buttons in radio group in front of each other?
I want to align my radio buttons in front of each other. My radio buttons are in the radio group and my parent layout is a constraint layout.

How to do that? I tried by putting the radio group into a child relative layout but it's not working. I want to align my radio buttons in front of each other.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/mValidity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"[In image you can see get now radio button is below the shop now radio button. but i want get now radio button will be in right of hop now.][1]
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mLink"
        app:layout_constraintVertical_bias="0.000" />

    <RadioGroup
        android:id="@+id/lRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mValidity"
        app:layout_constraintVertical_bias="0.000">

        <RadioButton
            android:id="@+id/mShopNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:onClick="checkButton"
            android:text="SHOP NOW" />

        <RadioButton
            android:id="@+id/mGetNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="checkButton"
            android:text="GET NOW" />

    </RadioGroup>

    <TextView
        android:id="@+id/mDealType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Deal Type"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lRadioGroup"
        app:layout_constraintVertical_bias="0.000" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:onClick="addNote"
        android:text="Insert Document"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mDealType"
        app:layout_constraintVertical_bias="0.035" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
you can give orientation = horizontal to RadioGroup like this

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/mValidity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mLink"
        app:layout_constraintVertical_bias="0.000" />

    <RadioGroup
        android:id="@+id/lRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mValidity">

        <RadioButton
            android:id="@+id/mShopNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:gravity="center|right"
            android:onClick="checkButton"
            android:text="SHOP NOW"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <RadioButton
            android:id="@+id/mGetNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:gravity="center|right"
            android:onClick="checkButton"
            android:text="GET NOW"
            app:layout_constraintStart_toEndOf="@+id/mShopNow"
            app:layout_constraintTop_toTopOf="@+id/mShopNow" />

    </RadioGroup>

    <TextView
        android:id="@+id/mDealType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Deal Type"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lRadioGroup"
        app:layout_constraintVertical_bias="0.000" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:onClick="addNote"
        android:text="Insert Document"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mDealType"
        app:layout_constraintVertical_bias="0.035" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I want to align my radio buttons in front of each other. My radio buttons are in the radio group and my parent layout is a constraint layout.

How to do that? I tried by putting the radio group into a child relative layout but it's not working. I want to align my radio buttons in front of each other.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/mValidity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"[In image you can see get now radio button is below the shop now radio button. but i want get now radio button will be in right of hop now.][1]
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mLink"
        app:layout_constraintVertical_bias="0.000" />

    <RadioGroup
        android:id="@+id/lRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mValidity"
        app:layout_constraintVertical_bias="0.000">

        <RadioButton
            android:id="@+id/mShopNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:onClick="checkButton"
            android:text="SHOP NOW" />

        <RadioButton
            android:id="@+id/mGetNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="checkButton"
            android:text="GET NOW" />

    </RadioGroup>

    <TextView
        android:id="@+id/mDealType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Deal Type"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lRadioGroup"
        app:layout_constraintVertical_bias="0.000" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:onClick="addNote"
        android:text="Insert Document"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mDealType"
        app:layout_constraintVertical_bias="0.035" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
you can give orientation = horizontal to RadioGroup like this

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/mValidity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mLink"
        app:layout_constraintVertical_bias="0.000" />

    <RadioGroup
        android:id="@+id/lRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mValidity">

        <RadioButton
            android:id="@+id/mShopNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:gravity="center|right"
            android:onClick="checkButton"
            android:text="SHOP NOW"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <RadioButton
            android:id="@+id/mGetNow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:gravity="center|right"
            android:onClick="checkButton"
            android:text="GET NOW"
            app:layout_constraintStart_toEndOf="@+id/mShopNow"
            app:layout_constraintTop_toTopOf="@+id/mShopNow" />

    </RadioGroup>

    <TextView
        android:id="@+id/mDealType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Deal Type"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lRadioGroup"
        app:layout_constraintVertical_bias="0.000" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:onClick="addNote"
        android:text="Insert Document"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mDealType"
        app:layout_constraintVertical_bias="0.035" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Input file for Perl job
I have a simple batch job that looks up users in a group from Active Directory. If the user count exceeds a threshold, it sends an email. I included a stripped down version of the code below just to give you an idea of what i am attempting to accomplish.  The thing i need help with is figuring out how to populate the $Group and $t values (currently hard coded) with values from another file. Not sure if i should use a simple log file or xml but the other file with have a list of group names and the threshold of the number of users we should have for each group.

Security_Group_X 50

Security_Group_Y 40

I then want this job to read those values from the input file and do a big For Each statement. Not sure what the input file should be formatted like and the easiet way to read the file to make it process the code below for each group in the file.

```<code>    my $Group = "Security_Group_X";
    Win32::NetAdmin::GetDomainController('',$Domain,$Server);

    if(! Win32::NetAdmin::GroupGetMembers($Server,$Group,\@UserList)){
print "error connecting to group " . $Group;
    }
    else {
$i=0;
$t=50;

foreach $user (@UserList){
            $i++.
            print " $user\n";
        }
    print $i . " Current users in this group.\n";

    if ($i > $t){
    ### i have some code here that would email the count and users ###
    }
    else {
    print $Group . " is still under the limit. \n";
    }
    }
</code>```

Thanks in advance for any advice.

答:
I think you may be looking to set up a configuration file.

Have a look under the Config:: name-space on cpan.

Here's one possible solution thats based on Config::Auto. I've chosen to format the configuration file as YAML.

test program test.pl:

```<code>#!/usr/bin/perl
use common::sense;

use Config::Auto;
use YAML;

my $config = Config::Auto::parse();

print YAML::Dump {config => $config};

my %groups = %{ $config->{groups} || {} };

print "\n";

foreach my $group_name (sort keys %groups) {
    my $group_limit = $groups{$group_name};

    print "group name: $group_name has limit $group_limit\n";
}
</code>```

contents of configuration file test.config:

```<code>---
# Sample YAML config file
groups:
  Security_Group_X: 50
  Security_Group_Y: 40
</code>```

This produces:

```<code>---
config:
  groups:
    Security_Group_X: 50
    Security_Group_Y: 40

group name: Security_Group_X has limit 50
group name: Security_Group_Y has limit 40
</code>```

Update: test.config could just as easily contain XML:

```<code><config>
  <!-- Sample XML config file -->
  <groups>
    <Security_Group_X>50</Security_Group_X>
    <Security_Group_Y>40</Security_Group_Y>
  </groups>
</config>
</code>```

Title: Input file for Perl job

Body:
I have a simple batch job that looks up users in a group from Active Directory. If the user count exceeds a threshold, it sends an email. I included a stripped down version of the code below just to give you an idea of what i am attempting to accomplish.  The thing i need help with is figuring out how to populate the $Group and $t values (currently hard coded) with values from another file. Not sure if i should use a simple log file or xml but the other file with have a list of group names and the threshold of the number of users we should have for each group.

Security_Group_X 50

Security_Group_Y 40

I then want this job to read those values from the input file and do a big For Each statement. Not sure what the input file should be formatted like and the easiet way to read the file to make it process the code below for each group in the file.

    my $Group = "Security_Group_X";
    Win32::NetAdmin::GetDomainController('',$Domain,$Server);

    if(! Win32::NetAdmin::GroupGetMembers($Server,$Group,\@UserList)){
print "error connecting to group " . $Group;
    }
    else {
$i=0;
$t=50;

foreach $user (@UserList){
            $i++.
            print " $user\n";
        }
    print $i . " Current users in this group.\n";

    if ($i > $t){
    ### i have some code here that would email the count and users ###
    }
    else {
    print $Group . " is still under the limit. \n";
    }
    }

Thanks in advance for any advice.

Body:
I think you may be looking to set up a configuration file.

Have a look under the Config:: name-space on cpan.

Here's one possible solution thats based on Config::Auto. I've chosen to format the configuration file as YAML.

test program test.pl:

#!/usr/bin/perl
use common::sense;

use Config::Auto;
use YAML;

my $config = Config::Auto::parse();

print YAML::Dump {config => $config};

my %groups = %{ $config->{groups} || {} };

print "\n";

foreach my $group_name (sort keys %groups) {
    my $group_limit = $groups{$group_name};

    print "group name: $group_name has limit $group_limit\n";
}

contents of configuration file test.config:

---
# Sample YAML config file
groups:
  Security_Group_X: 50
  Security_Group_Y: 40

This produces:

---
config:
  groups:
    Security_Group_X: 50
    Security_Group_Y: 40

group name: Security_Group_X has limit 50
group name: Security_Group_Y has limit 40

Update: test.config could just as easily contain XML:

<config>
  <!-- Sample XML config file -->
  <groups>
    <Security_Group_X>50</Security_Group_X>
    <Security_Group_Y>40</Security_Group_Y>
  </groups>
</config>


问:
PS - How to save output to file with colors?
How can I save the terminal output to a PDF file with colors?

I use right now this command:

myCommand that output something with colors to terminal | Out-Printer -Name "Microsoft Print to PDF"

It does create the file, but colors are missing. Any ideas? Tips?

I'm using Windows 10, Powershell

答:
You didn't say how your output commands look like, but ...

You could create an html file with colours and print this file as PDF, e.g.:

```<code>$HTMLFilePrefix = "<head></head><body>"
$HTMLFileSuffix = "<body>"
$HTMLStartRed = "<p><span style='color:red'>"
$HTMLEndRed = "</span></p>"
$HTMLFilePrefix + $HTMLStartRed + "This text is colored red" + $HTMLEndRed + $HTMLFileSuffix | Out-File -FilePath "C:\Temp\test.htm"
</code>```

Maybe "ConvertTo-Html" can also help to create the html file ...

Body:
You didn't say how your output commands look like, but ...

You could create an html file with colours and print this file as PDF, e.g.:

$HTMLFilePrefix = "<head></head><body>"
$HTMLFileSuffix = "<body>"
$HTMLStartRed = "<p><span style='color:red'>"
$HTMLEndRed = "</span></p>"
$HTMLFilePrefix + $HTMLStartRed + "This text is colored red" + $HTMLEndRed + $HTMLFileSuffix | Out-File -FilePath "C:\Temp\test.htm"

Maybe "ConvertTo-Html" can also help to create the html file ...


问:
ggplot2 : Bind 2 heatmaps and add a dataframe box in the corner
I made two heatmaps with the code:

I create the first heatmap

```<code>heatmap1<-ggplot(mod_mat_constraint, aes(x=Categorie, y=label)) +
  geom_tile(aes(fill=Value)) + scale_fill_manual(values = c("#86d65e","#404040","#86d65e","#40c5e8","#e84a4a","#86d65e","#404040","#e2e2e2"), breaks=label_text)
</code>```

I create the second heatmap

```<code>heatmap2<-ggplot(mod_mat_gen_env, aes(x=Categorie, y=label)) +
  geom_tile(aes(fill=Value)) + scale_fill_manual(values = c("#86d65e","#404040","#86d65e","#40c5e8","#e84a4a","#86d65e","#404040","#e2e2e2"), breaks=label_text)
</code>```

and I add them with a tree with:

```<code>heatmap2 %>% insert_left(tree) %>% insert_right(heatmap1, width=.5)
</code>```

which gives me:

and I wondered if there were a way with ggplot2 to add an additional df box at the right corner such as:

from a dataframe called DF1

```<code>COL1 COL2  COL3
0.1  Peter USA
</code>```

答:
Hard to help precisely without a dataset, but to get a table overlaid on your plot, probably the best way would be to use annotation_custom() with a tableGrob() from the gridExtra package.

Here's an example heatmap pulled right from the R Graph Gallery which I used to add in your table as a grob.

```<code># Library
library(ggplot2)
library(gridExtra)

# Dummy data
x <- LETTERS[1:20]
y <- paste0("var", seq(1,20))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(400, 0, 5)

# Heatmap
p <- ggplot(data, aes(X, Y, fill= Z)) +
  geom_tile()

df <- data.frame(COL1=0.1,COL2='Peter',COL3='USA')

# adding the table
p + coord_cartesian(clip='off') +
  theme(plot.margin = margin(r=140)) +
  annotation_custom(
    grob=tableGrob(df, theme=ttheme_default(base_size = 7)),
    xmin=20, xmax=27, ymin=1, ymax=5
  )
</code>```

You can probably use a similar approach in your case.  Note the few things that I had to do here to get this to work:

add the grob as annotation_custom().  You will need to play around with the positioning... really just play with those numbers.  Also note you may want to play with the base size to ensure the table is the right aspect ratio compared to your plot.

Extend the plot margin so that you have the real estate on that side to include the table.

Turn clipping off so that you can see things outside the plot area properly.

Body:
I made two heatmaps with the code:

I create the first heatmap

heatmap1<-ggplot(mod_mat_constraint, aes(x=Categorie, y=label)) +
  geom_tile(aes(fill=Value)) + scale_fill_manual(values = c("#86d65e","#404040","#86d65e","#40c5e8","#e84a4a","#86d65e","#404040","#e2e2e2"), breaks=label_text)

I create the second heatmap

heatmap2<-ggplot(mod_mat_gen_env, aes(x=Categorie, y=label)) +
  geom_tile(aes(fill=Value)) + scale_fill_manual(values = c("#86d65e","#404040","#86d65e","#40c5e8","#e84a4a","#86d65e","#404040","#e2e2e2"), breaks=label_text)

and I add them with a tree with:

heatmap2 %>% insert_left(tree) %>% insert_right(heatmap1, width=.5)

which gives me:

and I wondered if there were a way with ggplot2 to add an additional df box at the right corner such as:

from a dataframe called DF1

COL1 COL2  COL3
0.1  Peter USA

Body:
Hard to help precisely without a dataset, but to get a table overlaid on your plot, probably the best way would be to use annotation_custom() with a tableGrob() from the gridExtra package.

Here's an example heatmap pulled right from the R Graph Gallery which I used to add in your table as a grob.

# Library
library(ggplot2)
library(gridExtra)

# Dummy data
x <- LETTERS[1:20]
y <- paste0("var", seq(1,20))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(400, 0, 5)

# Heatmap
p <- ggplot(data, aes(X, Y, fill= Z)) +
  geom_tile()

df <- data.frame(COL1=0.1,COL2='Peter',COL3='USA')

# adding the table
p + coord_cartesian(clip='off') +
  theme(plot.margin = margin(r=140)) +
  annotation_custom(
    grob=tableGrob(df, theme=ttheme_default(base_size = 7)),
    xmin=20, xmax=27, ymin=1, ymax=5
  )

You can probably use a similar approach in your case.  Note the few things that I had to do here to get this to work:

add the grob as annotation_custom().  You will need to play around with the positioning... really just play with those numbers.  Also note you may want to play with the base size to ensure the table is the right aspect ratio compared to your plot.

Extend the plot margin so that you have the real estate on that side to include the table.

Turn clipping off so that you can see things outside the plot area properly.


问:
How to find a specific string chunk using regularExpression in javascript?
I want to find a specific chunk of a string using regular expression. I have already a name in this string like aside-canvas. So, When I check for aside it returns true string.match(/aside/) But it should return false. Because it has aside-canvas not just aside.

How can I do that with regular expression dynamically.

let
    string = 'aside-canvas othersName';
//checking for only aside not aside-canvas, so it should return false
```

答:
If you are trying to match an exact string, you don't even need a regex for that:

let string = 'aside-canvas other others';

console.log(string.includes('aside-canvas'))```
</div>
</div>
</p>

<p>If you want to make sure that different class names in the list are treated separately:</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>let string = 'aside-canvas other others';

console.log(string.split(' ').includes('aside'))

let string2 = 'aside-canvas other others aside';

console.log(string2.split(' ').includes('aside'))</code>```

Or if you are really married to the regex idea:

(?:^| )aside(?:$| ) will check if it's either the start or has a space (to keep boundaries between classes consistent). Then the class name of interest aside. Then if it's the end of the string or a space to make sure that's the end of the class name.

let string = 'aside-canvas other others';
let regex = /(?:^| )aside(?:$| )/
console.log(regex.test(string))

let string2 = 'aside-canvas other others aside';

console.log(regex.test(string2))
let word = 'anotherClassName';

let dynamicRegex = new RegExp(`(?:^| )${word}(?:^| )`);
console.log(dynamicRegex);```
</div>
</div>
</p>

<p>If you want to make the regex dynamically, just create a new instance of RegExp:</p>

<p>Just note that whatever is in word will be treated as regex rather than text. So if you want to match * for instance, you need to escape it out.</p>

```let word = 'anotherClassName';
let dynamicRegex = new RegExp(`(?:^| )${word}(?:^| )`);
```

Body:
If you are trying to match an exact string, you don't even need a regex for that:

let string = 'aside-canvas other others';

console.log(string.includes('aside-canvas'))

If you want to make sure that different class names in the list are treated separately:

let string = 'aside-canvas other others';

console.log(string.split(' ').includes('aside'))

let string2 = 'aside-canvas other others aside';

console.log(string2.split(' ').includes('aside'))

Or if you are really married to the regex idea:

(?:^| )aside(?:$| ) will check if it's either the start or has a space (to keep boundaries between classes consistent). Then the class name of interest aside. Then if it's the end of the string or a space to make sure that's the end of the class name.

let string = 'aside-canvas other others';
let regex = /(?:^| )aside(?:$| )/
console.log(regex.test(string))

let string2 = 'aside-canvas other others aside';

console.log(regex.test(string2))
let word = 'anotherClassName';

let dynamicRegex = new RegExp(`(?:^| )${word}(?:^| )`);
console.log(dynamicRegex);

If you want to make the regex dynamically, just create a new instance of RegExp:

Just note that whatever is in word will be treated as regex rather than text. So if you want to match * for instance, you need to escape it out.

let word = 'anotherClassName';
let dynamicRegex = new RegExp(`(?:^| )${word}(?:^| )`);


问:
How to get ddl auto generated script in Spring boot JPA/Hibernate?
Is there a way to quickly get initial SQL script for the database that is being generated by hibernating through ddl-auto property?

I would like to get an initial SQL script for the flyway as a quick start.

答:
You can see the DDL script generated by Hibernate in a Spring boot application by setting the logging level of Hibernate to debug mode in the application.properties file of your project.</p>

```<code>logging.level.org.hibernate.SQL=DEBUG
</code>```

Body:
You can see the DDL script generated by Hibernate in a Spring boot application by setting the logging level of Hibernate to debug mode in the application.properties file of your project.

logging.level.org.hibernate.SQL=DEBUG