问:
How to refer to other things in R loop
Say that I have this data:

```<code>library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))
</code>```

I then have several things that would be useful to figures out, mainly about how the values in a loop refer to other values and how to automate this process.

It would be best to put this in a loop. How to do so with data frame names? In other words, how to refer to the name of a data.frame in a loop?

```<code>data03 <- filter(data, num<=1)
data04 <- filter(data, num<=2)
data05 <- filter(data, num<=3)
data06 <- filter(data, num<=4)
data07 <- filter(data, num<=5)
data08 <- filter(data, num<=6)
</code>```

Then, how to make this loop work and simplified?

```<code>for (i in c(03, 04, 05, 06, 07, 08)) {
    #I want to print the number corresponding to i
    if(i=="03") print(1)
    if(i=="04") print(2)
    if(i=="05") print(3)
    if(i=="06") print(4)
    if(i=="07") print(5)
    if(i=="08") print(6)
    #I want to get the value corresponding to i for the plot title
    if(i=="03") title="1998-99"
    if(i=="04") title="1999-00"
    if(i=="05") title="2000-01"
    if(i=="06") title="2001-02"
    if(i=="07") title="2002-03"
    if(i=="08") title="2003-04"
    #I want to open the data frame, data+i
    df <- paste(data,i)
    #I want to plot, using the title saved above
    plot(df$num, main=title)
}
</code>```

答:
So if I understand your issue you are asking how can you refer to data.frame elements without referencing their names.

In that case assuming you have data.frame test.df we can use [[]] to access them like this

```<code>test.df <- data.frame(first=rnorm(10),second=rnorm(10))
test.df$first
[1]  0.8447835 -0.7210152 -1.6379253 -1.5695393 -1.2467788 -1.9273583  0.5633265 -0.4186060  1.3478030 -0.4379999
test.df[[1]]
[1]  0.8447835 -0.7210152 -1.6379253 -1.5695393 -1.2467788 -1.9273583  0.5633265 -0.4186060  1.3478030 -0.4379999
test.df$first == test.df[[1]]
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
</code>```

You can then do things like use this index for looping over.

Talking more specifically to your data if all you want is to print the number with the title in val you can just do this.

```<code>for(i in 1:length(data$num){
   plot(data$num[[i]],main=paste(data$val[[i]])
</code>```

Title: How to refer to other things in R loop

Body:
Say that I have this data:

library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))

I then have several things that would be useful to figures out, mainly about how the values in a loop refer to other values and how to automate this process.

It would be best to put this in a loop. How to do so with data frame names? In other words, how to refer to the name of a data.frame in a loop?

data03 <- filter(data, num<=1)
data04 <- filter(data, num<=2)
data05 <- filter(data, num<=3)
data06 <- filter(data, num<=4)
data07 <- filter(data, num<=5)
data08 <- filter(data, num<=6)

Then, how to make this loop work and simplified?

for (i in c(03, 04, 05, 06, 07, 08)) {
    #I want to print the number corresponding to i
    if(i=="03") print(1)
    if(i=="04") print(2)
    if(i=="05") print(3)
    if(i=="06") print(4)
    if(i=="07") print(5)
    if(i=="08") print(6)
    #I want to get the value corresponding to i for the plot title
    if(i=="03") title="1998-99"
    if(i=="04") title="1999-00"
    if(i=="05") title="2000-01"
    if(i=="06") title="2001-02"
    if(i=="07") title="2002-03"
    if(i=="08") title="2003-04"
    #I want to open the data frame, data+i
    df <- paste(data,i)
    #I want to plot, using the title saved above
    plot(df$num, main=title)
}

Body:
So if I understand your issue you are asking how can you refer to data.frame elements without referencing their names.

In that case assuming you have data.frame test.df we can use [[]] to access them like this

test.df <- data.frame(first=rnorm(10),second=rnorm(10))
test.df$first
[1]  0.8447835 -0.7210152 -1.6379253 -1.5695393 -1.2467788 -1.9273583  0.5633265 -0.4186060  1.3478030 -0.4379999
test.df[[1]]
[1]  0.8447835 -0.7210152 -1.6379253 -1.5695393 -1.2467788 -1.9273583  0.5633265 -0.4186060  1.3478030 -0.4379999
test.df$first == test.df[[1]]
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

You can then do things like use this index for looping over.

Talking more specifically to your data if all you want is to print the number with the title in val you can just do this.

for(i in 1:length(data$num){
   plot(data$num[[i]],main=paste(data$val[[i]])


来源: stackexchange

问:
redirect to CSS/JS files with partially known / partially unknown file names
Trying to use htaccess to redirect Googlebot from an incoming URL file request of this form:

v_3099_0726dd5b5e8dd67a214c0c243436d131_all.css

to a file of this form, where the four digits at 5028 are not known but are always four digits.

v_5028_0726dd5b5e8dd67a214c0c243436d131_all.css

I don't think this is possible with regex, because a catchcall regex for those four characters cannot be used in the target path.  In other words, Rewrite cannot be told, "go look in directory ____ for a file name that matches everything literally except those four characters, and match them with a regex catchall."

In RewriteCond, pattern matching with regex is only available in the right-hand side, in CondPattern, not in the left-hand side (test string) where one could have the false hope of using regex to match a file name on the server with -f flag and then using that regex grouping in a backreference in RewriteRule to accomplish the goal.  That strategy won't work.

In RewriteRule, pattern matching with regex is only available on the left-hand side, in Pattern of the incoming URL, so can't be used on the right-hand side to say, "go look in the directory ____ for a file that is the same except for these four unknown digits, and redirect to that file."  That strategy won't work, either.

Any ideas how to accomplish the goal stated at the top?  Thank you.

答:
I was unable to determine why server configuration or site code was forcing '410 Gone' response directive in htaccess to be overridden with a 404 response, so had to do something like this to tell googlebot to stop hunting for CSS/JS files that get purged periodically (and renamed when regenerated).

in .htaccess:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule v_(.*)_(.*)$ /410response.php [L]
</code>```

in 410response.php placed in root:

<?php header($_SERVER['SERVER_PROTOCOL'].' 410 Gone');

UPDATE I

The 404 response when attempting to use htaccess for the 410 directive was being forced by the server, because of server apparently having a custom 410 document, that apparently routed to 404.  Adding a directive to prevent that then properly allowed use of htaccess to return 410 for pattern matches in RewriteRule.  (I thought that I had already checked yesterday to see if this would work, since @MrWhite said in his answer above to control for server possibly having a custom 410; today when making this check, it did work and indicate that server 410-to-404 redirection was overridding my 410 directive.)

```<code>ErrorDocument 410 default
RewriteRule test\.txt$ - [NC,R=410]
</code>```

MrWhite!  I located this solution in one of your posts on Stack Exchange.

ContentLicense: CC BY-SA 4.0

Body:
I was unable to determine why server configuration or site code was forcing '410 Gone' response directive in htaccess to be overridden with a 404 response, so had to do something like this to tell googlebot to stop hunting for CSS/JS files that get purged periodically (and renamed when regenerated).

in .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule v_(.*)_(.*)$ /410response.php [L]

in 410response.php placed in root:

<?php header($_SERVER['SERVER_PROTOCOL'].' 410 Gone');

UPDATE I

The 404 response when attempting to use htaccess for the 410 directive was being forced by the server, because of server apparently having a custom 410 document, that apparently routed to 404.  Adding a directive to prevent that then properly allowed use of htaccess to return 410 for pattern matches in RewriteRule.  (I thought that I had already checked yesterday to see if this would work, since @MrWhite said in his answer above to control for server possibly having a custom 410; today when making this check, it did work and indicate that server 410-to-404 redirection was overridding my 410 directive.)

ErrorDocument 410 default
RewriteRule test\.txt$ - [NC,R=410]

MrWhite!  I located this solution in one of your posts on Stack Exchange.


问:
AJAX - Using POST instead of GET
Up until now I have been using:

```<code>xmlhttp.open("GET","server_script.php?q="+str,true);
</code>```

Thanks

Edit:
I am providing a solution for anyone that may come across this page to demonstrate how to use POST instead of GET. If you are new to AJAX I would recommend this tutorial http://www.w3schools.com/PHP/php_ajax_php.asp using the GET method first.

Solution-

javascript:

```<code>xmlhttp.open("POST","script.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('var_name='+str);
</code>```

php:

```<code>$var_name = GET['var_name'];

echo $var_name;
</code>```

For reasons regarding the use of POST and GET - see comments blow.

答:
The query you show is probably perfectly fine as a GET request. No need to change it.

There are reasons to use one over the other: Requests that change state on server side (i.e. change data) should generally use POST; "read" requests should be GET.

This comes with an implicit security advantage because you can't do any damage by smuggling an URL into a user's page (like, showing an image whose URL points to an admin page named deleteall.php).

If your request just retrieves data, you're perfectly fine staying with GET.

See this question for an extensive discussion on when to use which. GET vs POST in AJAX?

ContentLicense: CC BY-SA 3.0

Title: AJAX - Using POST instead of GET

Body:
Up until now I have been using:

xmlhttp.open("GET","server_script.php?q="+str,true);

Thanks

Edit:
I am providing a solution for anyone that may come across this page to demonstrate how to use POST instead of GET. If you are new to AJAX I would recommend this tutorial http://www.w3schools.com/PHP/php_ajax_php.asp using the GET method first.

Solution-

javascript:

xmlhttp.open("POST","script.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('var_name='+str);

php:

$var_name = GET['var_name'];

echo $var_name;

For reasons regarding the use of POST and GET - see comments blow.


问:
Create MySQL database in Docker container at build time
I need to create a Docker image with a large database. The database can be populated using a script populate_net_db.sh from specified folders. I need to create a Docker image that has this done at build time so that developers working with database can create a container and not wait long time before the database gets populated.

What I have done (this worked but is not what I need):

I can create database at run time and populate it using mysql Docker image and putting the required files into docker-entrypoint-initdb.d folder. This will require significant time to set things up when you run the image, but works as needed and I can access the DB with docker exec -it "image_name" mysql -u root -p exactly as required.

I can create the same database at build time using RUN command and see that the tables are set up correctly at build, however, when I run such an image a new mysql DB is set up and the DB from build is gone.

Is there a way to have the build-time database show up in docker exec -it "image_name" mysql -u root -p?

答: I managed to solve this problem by saving the contents of /var/lib/mysql/ in a temporary folder during build as: mv /var/lib/mysql /mnt/tmp/. Then I created an entrypoint script to put in /docker-entrypoint-initdb.d folder. This script deletes the /var/lib/mysql/ contents at run time and moves the saved state from /mnt/tmp/. This causes MySQL to restart. However, the database becomes available very fast at container run. This method takes ~5  minutes for a 27GB database versus >1hr with loading the database from a dump file.


问:
Java multiple message dialogs at the same time with focusLost event
The problem is that when i click on the surname field when the name field is empty both messages appear because the focus is lost even from surname when the message dialog appears. Is there anything i can do to make the program show the name message and the focus to stay on the name field?

I tried the .requestFocus() but it didn't work.

    private void NameFieldFocusLost(java.awt.event.FocusEvent evt) {
            if (NameField.getText().equals('smth')) {
                JOptionPane.showMessageDialog(null, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
                }
    }
    private void SurnameFieldFocusLost(java.awt.event.FocusEvent evt) {
            if (SurnameField.getText().equals("smth")) {
                JOptionPane.showMessageDialog(null, "Please put a surname!","Error!", JOptionPane.INFORMATION_MESSAGE);
            }
    }
```

答:
First off, in the NameFieldFocusLost event: if (NameField.getText().equals('smth')) { doesn't fly. The equals() method requires a String: if (NameField.getText().equals("smth")) { or better yet...since you want to ensure a name is actually provided:

if (NameField.getText().trim().equals("")) {

There must be something we're not being shown. I don't understand why both MessageBoxes would be displaying when focus is taken away from the nameFieldFocusLost event. This shouldn't happen unless you have code somewhere moving focus around especially before your form is actually visible. The requestFocus() method should work as well and should be called directly after you display the MessageBox, for example:

```<code>private void nameFieldFocusLost(java.awt.event.FocusEvent evt) {
    if (nameField.getText().trim().equals("")) {
        JOptionPane.showMessageDialog(this, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
        nameField.setText("");      // Clear the JTextField in case a white-space was placed there.
        nameField.requestFocus();   // Force focus back onto the JTextField.
    }
}
</code>```

If you are moving focus to a JTextField before the parent container is visible (Form / JDialog) then you could possibly experience your particular problem.

EDIT:

Ahhh...I see the problem, thank you for the comment. Here are a few ways you can get around this dilemma:

Add a condition within the focusLost event for the next
JTextField to be in focus which will force an exit of that event
should the validation of the previously focused JTextField fail.

In your case you have a First Name text field and a Last Name text
field. In the focusLost event for the Last Name field you would have
the very first line of code being:

```<code>if (nameField.getText().trim().equals("")) { return; }
</code>```

This way the remaining event code doesn't get run in the Surname
Lost Focus event unless validation for Name field is successful. The
entire Surname event code may look like this:

```<code>private void surnameFocusLost(java.awt.event.FocusEvent evt) {
    if (nameField.getText().trim().equals("")) { return; }
    if (surnameField.getText().trim().equals("")) {
        JOptionPane.showMessageDialog(this, "Please put a last name!","Error!", JOptionPane.INFORMATION_MESSAGE);
        surnameField.setText("");      // Clear the JTextField in case a white-space was placed there.
        surnameField.requestFocus();   // Force focus back onto the JTextField.
    }
}
</code>```

An other way would be to utilize the InputVerifier
Class.
There is good example of its use in this SO
post.

Don't use the JTextField's Focus Events at all. If there is a button
that will be selected to further processing with the inputted data
then check the validation for all your JTextFields there (in the button's actionPerformed event) and force a
focus upon the field that fails (nameField.requestFocus();) for proper input.

Body:
First off, in the NameFieldFocusLost event: if (NameField.getText().equals('smth')) { doesn't fly. The equals() method requires a String: if (NameField.getText().equals("smth")) { or better yet...since you want to ensure a name is actually provided:

if (NameField.getText().trim().equals("")) {

There must be something we're not being shown. I don't understand why both MessageBoxes would be displaying when focus is taken away from the nameFieldFocusLost event. This shouldn't happen unless you have code somewhere moving focus around especially before your form is actually visible. The requestFocus() method should work as well and should be called directly after you display the MessageBox, for example:

private void nameFieldFocusLost(java.awt.event.FocusEvent evt) {
    if (nameField.getText().trim().equals("")) {
        JOptionPane.showMessageDialog(this, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
        nameField.setText("");      // Clear the JTextField in case a white-space was placed there.
        nameField.requestFocus();   // Force focus back onto the JTextField.
    }
}

If you are moving focus to a JTextField before the parent container is visible (Form / JDialog) then you could possibly experience your particular problem.

EDIT:

Ahhh...I see the problem, thank you for the comment. Here are a few ways you can get around this dilemma:

Add a condition within the focusLost event for the next
JTextField to be in focus which will force an exit of that event
should the validation of the previously focused JTextField fail.

In your case you have a First Name text field and a Last Name text
field. In the focusLost event for the Last Name field you would have
the very first line of code being:

if (nameField.getText().trim().equals("")) { return; }

This way the remaining event code doesn't get run in the Surname
Lost Focus event unless validation for Name field is successful. The
entire Surname event code may look like this:

private void surnameFocusLost(java.awt.event.FocusEvent evt) {
    if (nameField.getText().trim().equals("")) { return; }
    if (surnameField.getText().trim().equals("")) {
        JOptionPane.showMessageDialog(this, "Please put a last name!","Error!", JOptionPane.INFORMATION_MESSAGE);
        surnameField.setText("");      // Clear the JTextField in case a white-space was placed there.
        surnameField.requestFocus();   // Force focus back onto the JTextField.
    }
}

An other way would be to utilize the InputVerifier
Class.
There is good example of its use in this SO
post.

Don't use the JTextField's Focus Events at all. If there is a button
that will be selected to further processing with the inputted data
then check the validation for all your JTextFields there (in the button's actionPerformed event) and force a
focus upon the field that fails (nameField.requestFocus();) for proper input.


问:
why my code show Warning message in ide "Access of shared member through an instance; qualifying expression will not be evaluated"

I create class

'MyLib.aspx
Namespace MyLib
  Public Class Base

    Public Shared _XPage As Page
    Public Shared _Func  As FuncClass

    Public Shared Property XPage() As Page
      Get
          Return _XPage
      End Get
      Protected Set(Val as Page)
          _Page = Val
      End Set
    End Property

    Public Sub New(ByVal Page As Page)
      XPage = Page
    End Sub
  End Class

  Public Class FuncClass : Inherits Base

    Public Sub New()
        MyBase.New(_XPage)
    End Sub

    Public Function Test() As String
        Return "Test"
    End Function
  End Class
End Namespace

```

<blockquote>
  <p>I try it...</p>
</blockquote>

<pre class="lang-vb prettyprint-override"><code>
'ASPX_Page.aspx
Import MyLib

Partial Class ASPX_Page

  Private ReadOnly LibX As Base = New Base(Me)

  Protected Sub Button1_Clcik(sender As Object, e As EventArgs)
  Handles Button1.Clcik

    'Access of shared member through an instance;
    'qualifying expression will not be evaluated
     LibX._Func.Test()

  End Sub
End Class

</code>```

IDE show Warning message
  "Access of shared member through an instance; qualifying expression will not > be evaluated", but still working fine

why it show warning message , How can I fix it?

答:
You get the warning because _Func is Shared and Shared members are supposed to be accessed via the type that they're a member of, not an instance of that type.  This:

LibX._Func.Test()
```

<p>is trying to access <code>_Func</code> via an instance of the <code>Base</code> class rather than the class itself.  That should be like this:</p>

<pre class="lang-vb prettyprint-override"><code>Base._Func.Test()
</code>```

If you want your _Func field to be instance-specific then don't declare it Shared and if you don't want it to be instance-specific then don't access it via a specific instance.

Note that this is a warning rather than an error.  If you do access a Shared member via an instance then the system will automatically ignore the instance and use the type, but it will tell you that it is doing so.  That's why you're being told that the qualifying expression, i.e. LibX, will not be evaluated.  It does that because someone might use a method that returns an instance rather than just a variable and that method would not be called, so anything else that that method also does would not happen.

Body:
I create class

'MyLib.aspx
Namespace MyLib
  Public Class Base

    Public Shared _XPage As Page
    Public Shared _Func  As FuncClass

    Public Shared Property XPage() As Page
      Get
          Return _XPage
      End Get
      Protected Set(Val as Page)
          _Page = Val
      End Set
    End Property

    Public Sub New(ByVal Page As Page)
      XPage = Page
    End Sub
  End Class

  Public Class FuncClass : Inherits Base

    Public Sub New()
        MyBase.New(_XPage)
    End Sub

    Public Function Test() As String
        Return "Test"
    End Function
  End Class
End Namespace

I try it...

'ASPX_Page.aspx
Import MyLib

Partial Class ASPX_Page

  Private ReadOnly LibX As Base = New Base(Me)

  Protected Sub Button1_Clcik(sender As Object, e As EventArgs)
  Handles Button1.Clcik

    'Access of shared member through an instance;
    'qualifying expression will not be evaluated
     LibX._Func.Test()

  End Sub
End Class

IDE show Warning message
  "Access of shared member through an instance; qualifying expression will not > be evaluated", but still working fine

why it show warning message , How can I fix it?

Body:
You get the warning because _Func is Shared and Shared members are supposed to be accessed via the type that they're a member of, not an instance of that type.  This:

LibX._Func.Test()

is trying to access _Func via an instance of the Base class rather than the class itself.  That should be like this:

Base._Func.Test()

If you want your _Func field to be instance-specific then don't declare it Shared and if you don't want it to be instance-specific then don't access it via a specific instance.

Note that this is a warning rather than an error.  If you do access a Shared member via an instance then the system will automatically ignore the instance and use the type, but it will tell you that it is doing so.  That's why you're being told that the qualifying expression, i.e. LibX, will not be evaluated.  It does that because someone might use a method that returns an instance rather than just a variable and that method would not be called, so anything else that that method also does would not happen.


问:
TypeError [ERR_INVALID_OPT_VALUE]: is invalid for option "hostname"
I am getting this error:

```<code>unhandledRejection: TypeError [ERR_INVALID_OPT_VALUE]: The value "blue-test.cle1x.us-west-1.rds.amazonaws.com" is invalid for option "hostname"
    at Object.lookupService (dns.js:173:11)
    at /app/main.js:32:7
    at new Promise (<anonymous>)
    at getDNSInfo (/app/main.js:31:36)
    at /app/main.js:113:12
    at Array.map (<anonymous>)
    at Server.<anonymous> (/app/main.js:112:68)
    at Server.emit (events.js:200:13)
    at parserOnIncoming (_http_server.js:709:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:17)
</code>```

I used this call:

```<code>  const dns = require('dns');
  dns.lookupService(host, port, (err, hostname, service) => {
    console.log('dns resolved:', {hostname, service, err});
    resolve({err, hostname, service});
  });
</code>```

and hostname is passed as host, so anyone know what's up with that?

答:
The first parameter of dns.lookupService() is address, not host. According to Node.js document:

dns.lookupService(address, port, callback)

Resolves the given address and port into a hostname and service using the operating system's underlying getnameinfo implementation.

If you want to resolve blue-test.cle1x.us-west-1.rds.amazonaws.com to its IP address, dns.lookup() is the right choice.

Body:
I am getting this error:

unhandledRejection: TypeError [ERR_INVALID_OPT_VALUE]: The value "blue-test.cle1x.us-west-1.rds.amazonaws.com" is invalid for option "hostname"
    at Object.lookupService (dns.js:173:11)
    at /app/main.js:32:7
    at new Promise (<anonymous>)
    at getDNSInfo (/app/main.js:31:36)
    at /app/main.js:113:12
    at Array.map (<anonymous>)
    at Server.<anonymous> (/app/main.js:112:68)
    at Server.emit (events.js:200:13)
    at parserOnIncoming (_http_server.js:709:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:17)

I used this call:

  const dns = require('dns');
  dns.lookupService(host, port, (err, hostname, service) => {
    console.log('dns resolved:', {hostname, service, err});
    resolve({err, hostname, service});
  });

and hostname is passed as host, so anyone know what's up with that?


问:
Append object values javascript
How can I append the customerApplicationAddress values no, street, barangay, municipality, province and put it inside the customerApplication.address

```<code>data(){
    return {
        customerApplicationAddress: {
          no: '',
          street: '',
          barangay: '',
          municipality: '',
          province: '',
        },
        customerApplication:{
          name: null,
          address: null
        }
    }
}
</code>```

Any idea how can I achieve this? I tried looping and concatenate it but somehow I'm getting an undefined error.

答:
Consider using computed properties for customApplication. Your code would look like:

```<code>Vue.extend({
  data() {
    return {
      customerApplicationAddress: {
        no: '',
        street: '',
        barangay: '',
        municipality: '',
        province: '',
      },
      customerApplication:{
        name: null,
        address: null
      }
    };
  },

  computed: {
    customerApplication() {

      const addr = this.customerApplicationAddress;

      return {
        // Or consider using string interpolation
        address: addr.no + ' ' + addr.street + ' ' + addr.barangay + ' ' + addr.municipality + ' ' + addr.province
      };
    }
  }
});
</code>```

By doing this, your customerApplication object would be automatically updated every time underlying customerApplicationAddress.* value changes.

Title: Append object values javascript

Body:
How can I append the customerApplicationAddress values no, street, barangay, municipality, province and put it inside the customerApplication.address

data(){
    return {
        customerApplicationAddress: {
          no: '',
          street: '',
          barangay: '',
          municipality: '',
          province: '',
        },
        customerApplication:{
          name: null,
          address: null
        }
    }
}

Any idea how can I achieve this? I tried looping and concatenate it but somehow I'm getting an undefined error.

Body:
Consider using computed properties for customApplication. Your code would look like:

Vue.extend({
  data() {
    return {
      customerApplicationAddress: {
        no: '',
        street: '',
        barangay: '',
        municipality: '',
        province: '',
      },
      customerApplication:{
        name: null,
        address: null
      }
    };
  },

  computed: {
    customerApplication() {

      const addr = this.customerApplicationAddress;

      return {
        // Or consider using string interpolation
        address: addr.no + ' ' + addr.street + ' ' + addr.barangay + ' ' + addr.municipality + ' ' + addr.province
      };
    }
  }
});

By doing this, your customerApplication object would be automatically updated every time underlying customerApplicationAddress.* value changes.


问:
Facebook Chat difficulty user's JID
I've a problem connecting to Facebook's XMPP to use chat api. In fact the only problem is that I don't know the JID, sometime user doesn't have provided his username and it won't work simply by settings his/her userID as an JID.

I've tried my own JID from facebook that I use in iChat and it worked perfectly.

So, according to the docs I should rather log user to the chat by using access token instead of username/password.

I'm successfuly logged in, the accesss token is in the form:
18112...|f6daa87...-1392...|qE7...-sD6...

Now I use the XMPPFramework with XMPPStreamFacebook by Eric Chamberlain.
This is my method starting the chat

```<code>-(void)launchService {
    if (xmppStream) {
        [xmppStream release];
        xmppStream = nil;
    }
    xmppStream = [[XMPPStreamFacebook alloc] init];
    xmpReconnect = [[XMPPReconnect alloc] initWithStream:xmppStream];

    if (xmppRosterStorage) {
        [xmppRosterStorage release];
        xmppRosterStorage = nil;
    }

    xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];

    if (xmppRoster) {
        [xmppRoster release];
        xmppRoster = nil;
    }
    xmppRoster = [[XMPPRoster alloc] initWithStream:xmppStream rosterStorage:xmppRosterStorage];

    [xmppStream addDelegate:self];
    [xmppRoster addDelegate:self];
    [xmppRoster setAutoRoster:YES];

    [xmppStream setHostName:@"chat.facebook.com"];
    [xmppStream setHostPort:5222];

    [xmppStream setMyJID:[XMPPJID jidWithString:@"test@chat.facebook.com"]];

    // You may need to alter these settings depending on the server you're connecting to
    allowSelfSignedCertificates = NO;
    allowSSLHostNameMismatch = NO;

    // Uncomment me when the proper information has been entered above.
    NSError *error = nil;
    if (![xmppStream connect:&error])
        NSLog(@"Error connecting: %@", error);
}
</code>```

and

```<code>   - (void)xmppStreamDidConnect:(XMPPStream *)sender {
        NSError *error = nil;
    //  [xmppStream authenticateWithAccessToken:[self appDelegate].token error:&error];

        NSLog(@"---------- xmppStreamDidConnect: ----------");

        isOpen = YES;

        if (![[self xmppStream] authenticateWithAccessToken:[self appDelegate].token error:&error])
        {
            NSLog(@"Error authenticating: %@", error);
        }
    }
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@"---------- xmppStream:didNotAuthenticate: ---------- %@ desc %@",error,[error description]);
}
...
</code>```

In the console I get:

```<code>2011-01-15 19:41:06.547 Facebookwebsiteziosfbconnect[81160:207] SEND: <?xml version='1.0'?>
2011-01-15 19:41:06.548 Facebookwebsiteziosfbconnect[81160:207] SEND: <stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' to='chat.facebook.com'>
2011-01-15 19:41:06.920 Facebookwebsiteziosfbconnect[81160:207] RECV: <?xml version="1.0"?><stream:stream id="4788E768" from="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xml:lang="en">
2011-01-15 19:41:06.922 Facebookwebsiteziosfbconnect[81160:207] RECV: <stream:features><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>X-FACEBOOK-PLATFORM</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features>
2011-01-15 19:41:06.922 Facebookwebsiteziosfbconnect[81160:207] ---------- xmppStreamDidConnect: ----------
2011-01-15 19:41:07.829 Facebookwebsiteziosfbconnect[81160:207] ---------- xmppStream:didNotAuthenticate: ---------- (null) desc (null)
</code>```

I just want to confirm that if I provided the real login (that I use in iChat) instead of test@chat.facebook.com, and my password authentication in didConnect everything the authentication works.

Does anyone see the problem?
Thx in advance.

答:
I believe the only way you can use a 3rd party client with FB chat is if the user has created a  FB user id.

In addition, just to be sure, after your XMPP authentication you should receive the full JID from the server.  something like this

```<code><iq id="0" type="result">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
    <jid>example@domain.com/resource</jid>
  </bind>
</iq>
</code>```

that is the JID you use.

ContentLicense: CC BY-SA 2.5

Title: Facebook Chat difficulty user's JID

Body:
I've a problem connecting to Facebook's XMPP to use chat api. In fact the only problem is that I don't know the JID, sometime user doesn't have provided his username and it won't work simply by settings his/her userID as an JID.

I've tried my own JID from facebook that I use in iChat and it worked perfectly.

So, according to the docs I should rather log user to the chat by using access token instead of username/password.

I'm successfuly logged in, the accesss token is in the form:
18112...|f6daa87...-1392...|qE7...-sD6...

Now I use the XMPPFramework with XMPPStreamFacebook by Eric Chamberlain.
This is my method starting the chat

-(void)launchService {
    if (xmppStream) {
        [xmppStream release];
        xmppStream = nil;
    }
    xmppStream = [[XMPPStreamFacebook alloc] init];
    xmpReconnect = [[XMPPReconnect alloc] initWithStream:xmppStream];

    if (xmppRosterStorage) {
        [xmppRosterStorage release];
        xmppRosterStorage = nil;
    }

    xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];

    if (xmppRoster) {
        [xmppRoster release];
        xmppRoster = nil;
    }
    xmppRoster = [[XMPPRoster alloc] initWithStream:xmppStream rosterStorage:xmppRosterStorage];

    [xmppStream addDelegate:self];
    [xmppRoster addDelegate:self];
    [xmppRoster setAutoRoster:YES];

    [xmppStream setHostName:@"chat.facebook.com"];
    [xmppStream setHostPort:5222];

    [xmppStream setMyJID:[XMPPJID jidWithString:@"test@chat.facebook.com"]];

    // You may need to alter these settings depending on the server you're connecting to
    allowSelfSignedCertificates = NO;
    allowSSLHostNameMismatch = NO;

    // Uncomment me when the proper information has been entered above.
    NSError *error = nil;
    if (![xmppStream connect:&error])
        NSLog(@"Error connecting: %@", error);
}

and

   - (void)xmppStreamDidConnect:(XMPPStream *)sender {
        NSError *error = nil;
    //  [xmppStream authenticateWithAccessToken:[self appDelegate].token error:&error];

        NSLog(@"---------- xmppStreamDidConnect: ----------");

        isOpen = YES;

        if (![[self xmppStream] authenticateWithAccessToken:[self appDelegate].token error:&error])
        {
            NSLog(@"Error authenticating: %@", error);
        }
    }
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@"---------- xmppStream:didNotAuthenticate: ---------- %@ desc %@",error,[error description]);
}
...

In the console I get:

2011-01-15 19:41:06.547 Facebookwebsiteziosfbconnect[81160:207] SEND: <?xml version='1.0'?>
2011-01-15 19:41:06.548 Facebookwebsiteziosfbconnect[81160:207] SEND: <stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' to='chat.facebook.com'>
2011-01-15 19:41:06.920 Facebookwebsiteziosfbconnect[81160:207] RECV: <?xml version="1.0"?><stream:stream id="4788E768" from="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xml:lang="en">
2011-01-15 19:41:06.922 Facebookwebsiteziosfbconnect[81160:207] RECV: <stream:features><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>X-FACEBOOK-PLATFORM</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features>
2011-01-15 19:41:06.922 Facebookwebsiteziosfbconnect[81160:207] ---------- xmppStreamDidConnect: ----------
2011-01-15 19:41:07.829 Facebookwebsiteziosfbconnect[81160:207] ---------- xmppStream:didNotAuthenticate: ---------- (null) desc (null)

I just want to confirm that if I provided the real login (that I use in iChat) instead of test@chat.facebook.com, and my password authentication in didConnect everything the authentication works.

Does anyone see the problem?
Thx in advance.

Body:
I believe the only way you can use a 3rd party client with FB chat is if the user has created a  FB user id.

In addition, just to be sure, after your XMPP authentication you should receive the full JID from the server.  something like this

<iq id="0" type="result">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
    <jid>example@domain.com/resource</jid>
  </bind>
</iq>

that is the JID you use.


问:
OCR with tesseract, pre-processing image
I need to extract digits from images like the one shown below, I'm using tesseract now, but it isn't working. Can anyone help me in pre-processing the images before feeding it to tesseract?

答:
I don't think tesseract is the right tool for it, Tesseract can only handle very clear letters.

If your numbers are all like those in the picture you can use opencv ORB detector https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_feature2d/py_orb/py_orb.html

Or if it don't work, you can use some deeplearning aproch, as a SSD Keras or YOLO.

https://github.com/pierluigiferrari/ssd_keras

Another option is to dismember the numbers (it is easy if is all the same size) and create a very simple convolutional neural network with keras.

https://keras.io/


问:
Describing the first few evaluation steps of a given foldr function
The following function is given:

```<code>mystery a b c xs =
  foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b
</code>```

I know what the function does roughly but I have a hard time really understanding the intermediate steps. I picked following example:

```<code>mystery 1 2 3 [1, 2, 3]
</code>```

Especially the use of rec is giving me a hard time. I assume that one of the final steps looks like this:

```<code>(\a b -> 3 + (b + 3 + 3 + 3) - 3) [] 1 2
</code>```

So the output is 11. Could someone describe the first few steps of the execution? What happens after:

```<code>foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1, 2, 3] 1 2
</code>```

答:
When the folding function given to foldr takes more than two parameters, it's often really a foldl in disguise. Let's see if that's true here.

```<code>mystery a b c xs = foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b
</code>```

Uncurry the two "extra" arguments to the folding function:

```<code>mystery a b c xs = foldr (\x rec (a,b) -> rec (x,b + c)) (\(a,b) -> a + b - c) xs (a,b)
</code>```

Extract function f out of the folding function, and finalStep from the nil case:

```<code>mystery a b c xs = foldr (\x rec z -> rec (f z x)) finalStep xs (a,b)
  where
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c
</code>```

Replace foldr with explicit recursion:

```<code>mystery a b c xs = go xs (a,b)
  where
    go [] = finalStep
    go (x:xs) = \z -> go xs (f z x)
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c
</code>```

Move the call to finalStep outside of go:

```<code>mystery a b c xs = finalStep $ go xs (a,b)
  where
    go [] = id
    go (x:xs) = \z -> go xs (f z x)
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c
</code>```

Eta-expand go and reverse the order of the arguments:

```<code>mystery a b c xs = finalStep $ go (a,b) xs
  where
    go z [] = z
    go z (x:xs) = go (f z x) xs
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c
</code>```

Now, go is exactly the definition of foldl f, so replace it with that:

```<code>mystery a b c xs = finalStep $ foldl f (a,b) xs
  where
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c
</code>```

Now we have a very simple fold operation that can be trivially worked through. The key takeaway from the above is the fact that foldr (\x rec -> rec . f x) finalStep xs z and finalStep $ foldl (flip f) z xs are the same, for any f, z, and xs.

Body:
The following function is given:

mystery a b c xs =
  foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b

I know what the function does roughly but I have a hard time really understanding the intermediate steps. I picked following example:

mystery 1 2 3 [1, 2, 3]

Especially the use of rec is giving me a hard time. I assume that one of the final steps looks like this:

(\a b -> 3 + (b + 3 + 3 + 3) - 3) [] 1 2

So the output is 11. Could someone describe the first few steps of the execution? What happens after:

foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1, 2, 3] 1 2

Body:
When the folding function given to foldr takes more than two parameters, it's often really a foldl in disguise. Let's see if that's true here.

mystery a b c xs = foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b

Uncurry the two "extra" arguments to the folding function:

mystery a b c xs = foldr (\x rec (a,b) -> rec (x,b + c)) (\(a,b) -> a + b - c) xs (a,b)

Extract function f out of the folding function, and finalStep from the nil case:

mystery a b c xs = foldr (\x rec z -> rec (f z x)) finalStep xs (a,b)
  where
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c

Replace foldr with explicit recursion:

mystery a b c xs = go xs (a,b)
  where
    go [] = finalStep
    go (x:xs) = \z -> go xs (f z x)
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c

Move the call to finalStep outside of go:

mystery a b c xs = finalStep $ go xs (a,b)
  where
    go [] = id
    go (x:xs) = \z -> go xs (f z x)
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c

Eta-expand go and reverse the order of the arguments:

mystery a b c xs = finalStep $ go (a,b) xs
  where
    go z [] = z
    go z (x:xs) = go (f z x) xs
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c

Now, go is exactly the definition of foldl f, so replace it with that:

mystery a b c xs = finalStep $ foldl f (a,b) xs
  where
    f (a,b) x = (x,b + c)
    finalStep (a,b) = a + b - c

Now we have a very simple fold operation that can be trivially worked through. The key takeaway from the above is the fact that foldr (\x rec -> rec . f x) finalStep xs z and finalStep $ foldl (flip f) z xs are the same, for any f, z, and xs.


答:
It looks like you are trying to turn an object into an array of key value pairs & then into a string.

You can do this by using Object.keys and then Array.prototype.map.

const data = {
    customerApplicationAddress: {
      no: '1',
      street: 'Big Street',
      barangay: 'some barangay',
      municipality: 'some municipality',
      province: 'some province',
    },
    customerApplication:{
      name: null,
      address: null
    }
}
data.customerApplication.address = Object.keys(data.customerApplicationAddress).map(k =>  data.customerApplicationAddress[k]).join(", ")

console.log(data)```

Title: Append object values javascript


问:
Split String by Two Characters Ignore Whitespace Before, In Between or After any of the Characters
I have an input string for example

```<code>var input = "'Test string','abc'";
</code>```

I want to split it by exactly two characters that is ', ignoring white spaces before, in between or after the delimiters. For example based on the input I'm expecting the following output.

```<code>index0='Test string'
index1='abc'
</code>```

I want to retain that output even if my input looks like any of these.

```<code>var input = "'Test string','abc'";
var input = "'Test string ','abc'";
var input = "'Test string' ,'abc'";
var input = "'Test string', 'abc'";
var input = "'Test string   '   ,   'abc'";
</code>```

As long as there are two characters ', (single quote and comma) regardless that they have spaces before, in between or after, I want to split a string based on those two char delimiters. Splitting should only by two chars. If an input has only ' or , retain the input as is. Only split the input by ', not by any of the two chars. Please help. Here's my code.

```<code>   static void Main(string[] args)
    {
        var input = "'Test string','abc'";
        var results = Regex.Split(input, @"[ ',]+");
        foreach (var item in results)
            Console.WriteLine(item);
        Console.ReadLine();

    }
</code>```

答:
Try this:</p>

```<code>string input = "'   Test string  ','abc'";
        string[] listInput = input.Split(',');
        foreach (string li in listInput){
          String output = li.TrimStart('\'').TrimEnd('\'').Trim();
            output = "'"+output+"'";
          Console.WriteLine(output);
        }
</code>```

Body:
I have an input string for example

var input = "'Test string','abc'";

I want to split it by exactly two characters that is ', ignoring white spaces before, in between or after the delimiters. For example based on the input I'm expecting the following output.

index0='Test string'
index1='abc'

I want to retain that output even if my input looks like any of these.

var input = "'Test string','abc'";
var input = "'Test string ','abc'";
var input = "'Test string' ,'abc'";
var input = "'Test string', 'abc'";
var input = "'Test string   '   ,   'abc'";

As long as there are two characters ', (single quote and comma) regardless that they have spaces before, in between or after, I want to split a string based on those two char delimiters. Splitting should only by two chars. If an input has only ' or , retain the input as is. Only split the input by ', not by any of the two chars. Please help. Here's my code.

   static void Main(string[] args)
    {
        var input = "'Test string','abc'";
        var results = Regex.Split(input, @"[ ',]+");
        foreach (var item in results)
            Console.WriteLine(item);
        Console.ReadLine();

    }

Body:
Try this:

string input = "'   Test string  ','abc'";
        string[] listInput = input.Split(',');
        foreach (string li in listInput){
          String output = li.TrimStart('\'').TrimEnd('\'').Trim();
            output = "'"+output+"'";
          Console.WriteLine(output);
        }


问:
Angular 7 Type 'void' is not assignable to type 'ObservableInput<{}>'
I can not figure it out why i got this error

```<code>  getByURL(url: string): any {
    return this.apiService.get(url).pipe(map(data => data));
  }

  getByNextPage(): Observable<any> {
    const url = 'url';
    this.getByURL(url).pipe(
      expand(data => {
        console.log(data);
      })
    );
  }
</code>```

I got this error at line that has expand(data => ... . I want to use expand() so i can recursive the call for the next api.

```<code>Type 'void' is not assignable to type 'ObservableInput<{}>'
</code>```

Any hint would be really appreciate. Thanks

答:
```<code>expand(data => {
  console.log(data);
})
</code>```

Your function does not return anything, hence the void. You need to return an observable.

Body:
I can not figure it out why i got this error

  getByURL(url: string): any {
    return this.apiService.get(url).pipe(map(data => data));
  }

  getByNextPage(): Observable<any> {
    const url = 'url';
    this.getByURL(url).pipe(
      expand(data => {
        console.log(data);
      })
    );
  }

I got this error at line that has expand(data => ... . I want to use expand() so i can recursive the call for the next api.

Type 'void' is not assignable to type 'ObservableInput<{}>'

Any hint would be really appreciate. Thanks

Body:
expand(data => {
  console.log(data);
})

Your function does not return anything, hence the void. You need to return an observable.


问:
How can I keep some columns as is and dynamically pivot the last column in SQL Server 2012
I have a table with 5 columns with values 0 or 1 and the last column QuoteStatus is of type VARCHAR.

I want to keep ControlNo and the other 4 columns as is, but the last column I need to pivot and also assign value either 0 or 1.

It can be more than 2 values: Lost or No Action.

So the data looks like this now:

```<code>DECLARE @Table1 TABLE
                (
                    ControlNo INT,
                    Bound INT,
                    Declined INT,
                    Rated INT,
                    Quoted INT,
                    QuoteStatus VARCHAR(50)
                )

INSERT INTO @Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
VALUES
(1111,1,0,1,1,'Lost'),
(2222,0,1,0,1,'No Action'),
(3333,1,1,0,0,NULL),
(4444,1,0,0,1,'Lost'),
(5555,0,1,1,1,'No Action')
</code>```

But I want it to look like this:

答:
I think what you are looking for is the PIVOT operator and for this problem I think you can get the result you want with something like this:</p>

```<code>SELECT *
FROM @Table1 a
PIVOT ( COUNT(QuoteStatus) FOR QuoteStatus IN ( [Lost], [No Action] ) b
</code>```

Body:
I have a table with 5 columns with values 0 or 1 and the last column QuoteStatus is of type VARCHAR.

I want to keep ControlNo and the other 4 columns as is, but the last column I need to pivot and also assign value either 0 or 1.

It can be more than 2 values: Lost or No Action.

So the data looks like this now:

DECLARE @Table1 TABLE
                (
                    ControlNo INT,
                    Bound INT,
                    Declined INT,
                    Rated INT,
                    Quoted INT,
                    QuoteStatus VARCHAR(50)
                )

INSERT INTO @Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
VALUES
(1111,1,0,1,1,'Lost'),
(2222,0,1,0,1,'No Action'),
(3333,1,1,0,0,NULL),
(4444,1,0,0,1,'Lost'),
(5555,0,1,1,1,'No Action')

But I want it to look like this:

Body:
I think what you are looking for is the PIVOT operator and for this problem I think you can get the result you want with something like this:

SELECT *
FROM @Table1 a
PIVOT ( COUNT(QuoteStatus) FOR QuoteStatus IN ( [Lost], [No Action] ) b


问:
Default web app in tomcat
Its been few days i've been searching for a solution.
My question is..I have to deploy a project in tomcat and make it as a default webapp. What I did is copied my war file and placed it in the tomcat/webapps folder. Started tomcat and changed the port to default. Now I can access my application at http://localhost/myapp .What i want is to see my application at http://localhost. How can I do this?  </p>

答:
you could rename your webapp to ROOT (the default app for tomcat), or you can use a web server that can handle domain names and redirects (like apache httpserver), and configure your site there.

The first approach is not very elegant, but quick and efficient though.

Title: Default web app in tomcat


问:
sed: Argument list too long when running sed -n
I am running this command from Why is my git repository so big? on a very big git repository as https://github.com/python/cpython

git rev-list --all --objects | sed -n $(git rev-list --objects --all | cut -f1 -d' ' | git cat-file --batch-check | grep blob | sort -n -k 3 | tail -n800 | while read hash type size; do size_in_kibibytes=$(echo $size | awk '{ foo = $1 / 1024 ; print foo "KiB" }'); echo -n "-e s/$hash/$size_in_kibibytes/p "; done) | sort -n -k1;

It works fine if I replace tail -n800 by tail -n40:

```<code>1160.94KiB Lib/ensurepip/_bundled/pip-8.0.2-py2.py3-none-any.whl
1169.59KiB Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl
1170.86KiB Lib/ensurepip/_bundled/pip-8.1.2-py2.py3-none-any.whl
1225.24KiB Lib/ensurepip/_bundled/pip-9.0.0-py2.py3-none-any.whl
...
</code>```

I found this question Bash : sed -n arguments saying I could use awk instead of sed.

Do you know how do fix this sed: Argument list too long when tail is -n800 instead of -n40?

答:
As an alternative, check if git sizer would work on your repository: that would help isolating what takes place in your repository.

If not, you have other commands in "How to find/identify large commits in git history?", which do loop around each objects and avoid the sed -nxx part

The alternative would be to redirect your result/command to a file, then sed on that file, as in here.

Body:
I am running this command from Why is my git repository so big? on a very big git repository as https://github.com/python/cpython

git rev-list --all --objects | sed -n $(git rev-list --objects --all | cut -f1 -d' ' | git cat-file --batch-check | grep blob | sort -n -k 3 | tail -n800 | while read hash type size; do size_in_kibibytes=$(echo $size | awk '{ foo = $1 / 1024 ; print foo "KiB" }'); echo -n "-e s/$hash/$size_in_kibibytes/p "; done) | sort -n -k1;

It works fine if I replace tail -n800 by tail -n40:

1160.94KiB Lib/ensurepip/_bundled/pip-8.0.2-py2.py3-none-any.whl
1169.59KiB Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl
1170.86KiB Lib/ensurepip/_bundled/pip-8.1.2-py2.py3-none-any.whl
1225.24KiB Lib/ensurepip/_bundled/pip-9.0.0-py2.py3-none-any.whl
...

I found this question Bash : sed -n arguments saying I could use awk instead of sed.

Do you know how do fix this sed: Argument list too long when tail is -n800 instead of -n40?


问:
How we can make thousands of set in ampl?
I am wondering if there is a way to define sets in ampl for the following problem?!

I wanna make a model with parameter X which is n dimensional. It is about information of each person in a household. such as age, job, ...
now I have 1000 family and for each family I want to define a parameter which has information X for each person.For example if I have one family I can define:

```<code>set G,  default{1..p};
set F,  default{1..t}; #number of family
set K, within G cross F;
param X{K};
</code>```

in the above example, X show the information of each person in the household.

How about if I have 1000 household? it does not make sense if I want to define 1000 sets with my hand!

答:
You can index a set over another set; see Section 6.5 of the AMPL book.

As a side note, I would recommend that you create separate parameters for each piece of information (age, job, ...) rather than including them all in a single parameter X.

Body:
I am wondering if there is a way to define sets in ampl for the following problem?!

I wanna make a model with parameter X which is n dimensional. It is about information of each person in a household. such as age, job, ...
now I have 1000 family and for each family I want to define a parameter which has information X for each person.For example if I have one family I can define:

set G,  default{1..p};
set F,  default{1..t}; #number of family
set K, within G cross F;
param X{K};

in the above example, X show the information of each person in the household.

How about if I have 1000 household? it does not make sense if I want to define 1000 sets with my hand!


答:
Split by comma and trim single quote and spaces afterwards</p>

```<code>var input = "'Test string   '   ,   'abc', 'John's test'";

var output = input.Split(',').Select(p => p.Trim().Trim('\'').Trim());

// Test string, abc, John's test.
</code>```

Title: Split String by Two Characters Ignore Whitespace Before, In Between or After any of the Characters

Body:
Split by comma and trim single quote and spaces afterwards

var input = "'Test string   '   ,   'abc', 'John's test'";

var output = input.Split(',').Select(p => p.Trim().Trim('\'').Trim());

// Test string, abc, John's test.


问:
React-Native : Orientation becomes locked on mount of signature component
I am using react-native-signature-capture for sign purpose.

```<code><RNSignatureCapture
    onSaveEvent={(result) => this.onSignatureSave(result)}
    saveImageFileInExtStorage={false}
    showNativeButtons={false}
    viewMode={this.state.landscapeMode ? "landscape" : "portrait"}
/>
</code>```

ViewMode determines the orientation of the screen. But the problem is after first render of the RNSignatureCapture total app gets locked to the same orientation as given in ViewMode. The only possible way to get rid  of it is deleting the app.

Is there any way for auto orientation according to device movement once the RNSignatureCapture is unmounted?

Thank You.

答: if ViewMode props is not provided then app won't get locked to particular orientation.

Body:
I am using react-native-signature-capture for sign purpose.

<RNSignatureCapture
    onSaveEvent={(result) => this.onSignatureSave(result)}
    saveImageFileInExtStorage={false}
    showNativeButtons={false}
    viewMode={this.state.landscapeMode ? "landscape" : "portrait"}
/>

ViewMode determines the orientation of the screen. But the problem is after first render of the RNSignatureCapture total app gets locked to the same orientation as given in ViewMode. The only possible way to get rid  of it is deleting the app.

Is there any way for auto orientation according to device movement once the RNSignatureCapture is unmounted?

Thank You.


问:
MPAndroidChart set a fixed markerview
I have created a chart using MPAndroidChart and I am looking to see if it is possible to set a fixed position for the markerview. My chart is being used inside a fragment. I want the markerview to always stay at the top of chart in the center of the X-Axis. I am using the Override Draw method but I can not get it to sit in the position I want it unless I specify it with ints. I tried to follow another guide where I override the getXoffset() but it I can not use this method in my class. Is this possible to do?

```<code>@Override
public void draw(Canvas canvas, float posX, float posY) {
posX = 400;
posY = -30;

canvas.translate(posX,posY);
draw(canvas);
canvas.translate(-posX,-posY);
}
}
</code>```

Full Fragment Code

```<code>public View onCreateView(LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph1_fragment, container, false);

mChart = (LineChart) view.findViewById(R.id.chart1);
mChart.setNoDataText("Getting Data From Server");
mChart.setNoDataTextColor(Color.BLACK);
makeChart();

return view;
}

private void makeChart() {

StringRequest req = new StringRequest(Request.Method.GET, URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.d(TAG, response.toString());

                try {
                    jsonResponse = "";
                    JSONObject jObject = new JSONObject(response);
                    JSONArray jsonArray = jObject.getJSONArray("Data");
                    for (int i = 0; i <= jsonArray.length(); i++) {

                        JSONObject o = jsonArray.getJSONObject(i);

                        time = o.getString("time");
                        open = o.getString("close");

                        float val = Float.parseFloat(open);

                        yVals1.add(new Entry(i, val));

                        long unixSeconds = Long.parseLong(time);
                        Date date = new Date(unixSeconds * 1000L);
                         SimpleDateFormat sdf = new
 SimpleDateFormat("HH:MM");

 sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
                        String formattedDate = sdf.format(date);

                        xValues.add(formattedDate);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d(TAG, "Error: " + error.getMessage());
    }
});

Graph_AppController.getInstance().addToRequestQueue(req);

handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {

        mChart.setBackgroundColor(Color.WHITE);
        mChart.setGridBackgroundColor(Color.WHITE);
        mChart.setDrawGridBackground(true);
        mChart.setDrawBorders(true);

        Legend l = mChart.getLegend();
        l.setEnabled(false);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setTextColor(Color.BLACK);

        xAxis.setValueFormatter(new DefaultAxisValueFormatter(0) {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xValues.get((int) value % xValues.size());
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTextColor(Color.BLACK);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawZeroLine(false);
        leftAxis.setDrawGridLines(false);
        leftAxis.setGridColor(Color.WHITE);
        leftAxis.setAxisLineColor(Color.BLACK);

        mChart.getAxisRight().setEnabled(false);
        LineDataSet set1;

        set1 = new LineDataSet(yVals1, "DataSet 1");

        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set1.setColor(Color.parseColor("#008000"));
        set1.setDrawCircles(true);
        set1.setLineWidth(3f);
        set1.setCircleRadius(1f);
        set1.setCircleColor(Color.parseColor("#008000"));
        set1.setFillAlpha(50);
        set1.setDrawFilled(true);
        set1.setFillColor(Color.parseColor("#008000"));
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setDrawCircleHole(false);

        dataSets.add(set1);

        LineData datab = new LineData(dataSets);
        datab.setDrawValues(false);

        mChart.setData(datab);
        mChart.setDrawMarkers(true);
        IMarker marker = new
  YourMarkerView(getContext(),R.layout.custom_marker);
        mChart.setMarker(marker);

    }
}, 3000);
}
public class YourMarkerView extends MarkerView {

private TextView tvContent;

public YourMarkerView(Context context, int layoutResource) {
    super(context, layoutResource);

    // find your layout components
    tvContent = (TextView) findViewById(R.id.tvContent);
}

// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)
@Override
public void refreshContent(Entry e, Highlight highlight) {

    tvContent.setText("$" + e.getY());

    // this will perform necessary layouting
    super.refreshContent(e, highlight);
}

private MPPointF mOffset;

@Override
public MPPointF getOffset() {

    if(mOffset == null) {
        // center the marker horizontally and vertically
        mOffset = new MPPointF(-(getWidth() / 2), -getHeight());
    }

    return mOffset;
}

@Override
public void draw(Canvas canvas, float posX, float posY) {
    posX = 400;
    posY = -30;

    canvas.translate(posX,posY);
    draw(canvas);
    canvas.translate(-posX,-posY);

}
}
</code>```

答:
Maybe you could use this :

```<code>posX=Resources.getSystem().getDisplayMetrics().widthPixels*ratio1
posY=Resources.getSystem().getDisplayMetrics().heightPixels*ratio2
</code>```

Resources.getSystem().getDisplayMetrics() will give you the sizes of your screen and then you can choose any ratio you want in order to set the position.

Title: MPAndroidChart set a fixed markerview

Body:
I have created a chart using MPAndroidChart and I am looking to see if it is possible to set a fixed position for the markerview. My chart is being used inside a fragment. I want the markerview to always stay at the top of chart in the center of the X-Axis. I am using the Override Draw method but I can not get it to sit in the position I want it unless I specify it with ints. I tried to follow another guide where I override the getXoffset() but it I can not use this method in my class. Is this possible to do?

@Override
public void draw(Canvas canvas, float posX, float posY) {
posX = 400;
posY = -30;

canvas.translate(posX,posY);
draw(canvas);
canvas.translate(-posX,-posY);
}
}

Full Fragment Code

public View onCreateView(LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph1_fragment, container, false);

mChart = (LineChart) view.findViewById(R.id.chart1);
mChart.setNoDataText("Getting Data From Server");
mChart.setNoDataTextColor(Color.BLACK);
makeChart();

return view;
}

private void makeChart() {

StringRequest req = new StringRequest(Request.Method.GET, URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.d(TAG, response.toString());

                try {
                    jsonResponse = "";
                    JSONObject jObject = new JSONObject(response);
                    JSONArray jsonArray = jObject.getJSONArray("Data");
                    for (int i = 0; i <= jsonArray.length(); i++) {

                        JSONObject o = jsonArray.getJSONObject(i);

                        time = o.getString("time");
                        open = o.getString("close");

                        float val = Float.parseFloat(open);

                        yVals1.add(new Entry(i, val));

                        long unixSeconds = Long.parseLong(time);
                        Date date = new Date(unixSeconds * 1000L);
                         SimpleDateFormat sdf = new
 SimpleDateFormat("HH:MM");

 sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
                        String formattedDate = sdf.format(date);

                        xValues.add(formattedDate);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d(TAG, "Error: " + error.getMessage());
    }
});

Graph_AppController.getInstance().addToRequestQueue(req);

handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {

        mChart.setBackgroundColor(Color.WHITE);
        mChart.setGridBackgroundColor(Color.WHITE);
        mChart.setDrawGridBackground(true);
        mChart.setDrawBorders(true);

        Legend l = mChart.getLegend();
        l.setEnabled(false);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setTextColor(Color.BLACK);

        xAxis.setValueFormatter(new DefaultAxisValueFormatter(0) {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xValues.get((int) value % xValues.size());
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTextColor(Color.BLACK);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawZeroLine(false);
        leftAxis.setDrawGridLines(false);
        leftAxis.setGridColor(Color.WHITE);
        leftAxis.setAxisLineColor(Color.BLACK);

        mChart.getAxisRight().setEnabled(false);
        LineDataSet set1;

        set1 = new LineDataSet(yVals1, "DataSet 1");

        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set1.setColor(Color.parseColor("#008000"));
        set1.setDrawCircles(true);
        set1.setLineWidth(3f);
        set1.setCircleRadius(1f);
        set1.setCircleColor(Color.parseColor("#008000"));
        set1.setFillAlpha(50);
        set1.setDrawFilled(true);
        set1.setFillColor(Color.parseColor("#008000"));
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setDrawCircleHole(false);

        dataSets.add(set1);

        LineData datab = new LineData(dataSets);
        datab.setDrawValues(false);

        mChart.setData(datab);
        mChart.setDrawMarkers(true);
        IMarker marker = new
  YourMarkerView(getContext(),R.layout.custom_marker);
        mChart.setMarker(marker);

    }
}, 3000);
}
public class YourMarkerView extends MarkerView {

private TextView tvContent;

public YourMarkerView(Context context, int layoutResource) {
    super(context, layoutResource);

    // find your layout components
    tvContent = (TextView) findViewById(R.id.tvContent);
}

// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)
@Override
public void refreshContent(Entry e, Highlight highlight) {

    tvContent.setText("$" + e.getY());

    // this will perform necessary layouting
    super.refreshContent(e, highlight);
}

private MPPointF mOffset;

@Override
public MPPointF getOffset() {

    if(mOffset == null) {
        // center the marker horizontally and vertically
        mOffset = new MPPointF(-(getWidth() / 2), -getHeight());
    }

    return mOffset;
}

@Override
public void draw(Canvas canvas, float posX, float posY) {
    posX = 400;
    posY = -30;

    canvas.translate(posX,posY);
    draw(canvas);
    canvas.translate(-posX,-posY);

}
}

Body:
Maybe you could use this :

posX=Resources.getSystem().getDisplayMetrics().widthPixels*ratio1
posY=Resources.getSystem().getDisplayMetrics().heightPixels*ratio2

Resources.getSystem().getDisplayMetrics() will give you the sizes of your screen and then you can choose any ratio you want in order to set the position.


问:
How do I get this javascript to run every second?
How do I get this javascript to run every second?

source code:

```<code><script type="text/javascript">
$(function() {
    //More Button
    $('.more').live("click",function()  {
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: "lastmsg="+ ID,
                cache: false,
                success: function(html){
                    $("ol#updates").prepend(html);
                    $("#more"+ID).remove();
                }
            });
        } else {
            $(".morebox").html('no posts to display');
        }

        return false;

    });
});

</script>
</code>```

答:
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.</p>

```<code>var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);
</code>```

Body:
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.

var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);


问:
Counting number of sequences of particular value for multiple columns in a data frame
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

```<code>x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))
</code>```

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

```<code>     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3
</code>```

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

答:
in base R you could do:

```<code> f = as.character(unique(unlist(x)))
 t(sapply(x,function(y)table(factor(rle(as.character(y))$values,f))))
      a b c d
Red   2 1 1 1
Blue  1 1 0 0
Green 3 2 0 0
</code>```

It seems your whole dataset is in factors so the code as.character() is used

Body:
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

Body:
in base R you could do:

 f = as.character(unique(unlist(x)))
 t(sapply(x,function(y)table(factor(rle(as.character(y))$values,f))))
      a b c d
Red   2 1 1 1
Blue  1 1 0 0
Green 3 2 0 0

It seems your whole dataset is in factors so the code as.character() is used


问:
Having trouble deciphering my teachers pseudo code
Im working on a Binary Search Tree assignment for class and for this function I need to follow my professor's pseudo code. Unfortunately, I'm not sure about one specific detail, and she refuses to clarify.

Link to the pseudo code is here:
https://imgur.com/a/rhjhEIa

```<code>SUBROUTINE insert(current, parent, node)
    IF current is null
        IF parent is null
            root = node
        ELSE
            ID node.value < parent.value
                parent.left = node
            ELSE
                parent.right = node
            END IF
            RETURN true
        END IF
    ELSE IF node.value = current.=value
        RETURN false
    ELSE IF ode.value < current.value
        insert(current.left, current, node)
    ELSE
        insert(current.right, current, node)
    END IF
END SUBROUTINE
</code>```

In place of node, I've tried seemingly most of the allowed variables, including current, parent, (and even value, which didn't work. Shocker.)

```<code>bool recursiveInsert(Node* current, Node* parent, double value)
{

    if (current == NULL)
    {
        if (parent == NULL)
        {
        }
        else
        {
            if (current->value < parent->value)
            {
                parent->left = current;
            }
            else
            {
                parent->right = current;
            }
            return true;
        }
    }
    else if(parent->value == current->value)
    {
        return false;
    }
    else if (parent->value < current->value)
    {
        insert(current->left, current->value, current);
    }
    else
    {
        insert(current->right, current->value, current);
    }
}
</code>```

I expect the output to add the value to the binary search tree and return true, but the program currently just throws a error whenever I get to the parts that require "node".

答:
node in the context of the pseudocode is a previously allocated node containing the data being inserted into the tree. The initial caller allocates it (which is both pointless and never done in RW code).In reality, it is highly unlikely to actually do this pattern unless you're considering a library that potentially moves nodes out of one tree into another, and you want to avoid the expense of setting-up/tearing-down the nodes themselves.

Regarding the algorithm, it's fairly straightforward, though not very pretty:

If both current and parent are null, it means this must be the first node in the tree tracked by some global pointer root. Therefore, root is assigned the incoming node directly.

Otherwise, If current is null but parent is not if means parent is some potential leaf in the tree (meaning it has either a left, a right, or both contained pointers that are null), and you've landed on the null pointer. The insertion requires comparing against the parent value to know whether you hang the node on the left or the right. Note that this is inefficient, as you already did this comparison (it's how you got here in the first place).

Otherwise if current is not-null we simply check whether the values are equal, or less (greater is assumed if neither of those are true), and drive into the subtree of left or right if warranted. In that case, current.left or current.right become the recursed current, and current becomes the parent of said-same recursive call.

That's it. That's how that algorithm works. And frankly, it's marginal.

To implement this algorithm with your argument list (that takes a value rather than a node for the final argument), you need only ensure node allocation only happens when it is time to actually hang it, and only then (there are two such cases.

```<code>bool recursiveInsert(Node* current, Node* parent, double value)
{
    bool result = false;

    if (current == NULL)
    {
        if (parent == NULL)
        {
            root = malloc(sizeof *root);
            root->value = value;
            root->left = root->right = NULL;
        }
        else
        {
            Node *p = malloc(sizeof *p);
            p->value = value;
            p->left = p->right = NULL;

            if (value < parent->value)
            {
                parent->left = p;
            }
            else
            {
                parent->right = p;
            }
            result = true;
        }
    }
    else if (value < parent->value)
        result = recursiveInsert(current->left, current, value);

    else if (parent->value < value)
        result = recursiveInsert(current->right, current, value);

    return result;
}
</code>```

When inserting a value into the tree, the call will look something like this:

```<code>recursiveInsert(root, NULL, value);
</code>```

It's not pretty, but it works. That it relies on global root presence is probably the worst part of this algorithm. The multi-compare is probably second on the list of yuck.

A Different Approach

Ideally the root of the tree is passed in as an argument. Further, we can make the algorithm recursive as it is now, but no longer rely on some global root. Finally, we can reduce the argument count to two: the address of a pointer (initially the address of the root pointer), and the value being inserted. sing a pointer-to-pointer as the tree access method makes this algorithm elegant, whether using recursion or not. Both are provided below:

Recursive Insertion

```<code>bool treeInsert(Node **pp, double value)
{
    bool result = false;
    if (!*pp)
    {
        *pp = malloc(sizeof **pp);
        (*pp)->value = value;
        (*pp)->left = (*pp)->right = NULL;
        result = true;
    }
    else if (value < (*pp)->value)
    {
        result = recursiveInsert(&(*pp)->left, value);
    }
    else if ((*pp)->value < value)
    {
        result = recursiveInsert(&(*pp)->right, value);
    }
    return result;
}
</code>```

Iterative Insertion

```<code>bool treeInsert(Node **pp, double value)
{
    bool result = false;

    while (*pp)
    {
        if (value < (*pp)->value)
            pp = &(*pp)->left;

        else if ((*pp)->value < value)
            pp = &(*pp)->right;

        else break;
    }

    if (!*pp)
    {
        *pp = malloc(sizeof **pp);
        (*pp)->value = value;
        (*pp)->left = (*pp)->right = NULL;
        result = true;
    }

    return result;
}
</code>```

in either case, you invoke by passing the address of the root pointer (thus a pointer to pointer), where an empty try is signified by a NULL root:

```<code>treeInsert(&root, value);
</code>```

Either function will accomplish the task at hand. I leave the error-hardening asa task for you (check your mallocs).

Body:
Im working on a Binary Search Tree assignment for class and for this function I need to follow my professor's pseudo code. Unfortunately, I'm not sure about one specific detail, and she refuses to clarify.

Link to the pseudo code is here:
https://imgur.com/a/rhjhEIa

SUBROUTINE insert(current, parent, node)
    IF current is null
        IF parent is null
            root = node
        ELSE
            ID node.value < parent.value
                parent.left = node
            ELSE
                parent.right = node
            END IF
            RETURN true
        END IF
    ELSE IF node.value = current.=value
        RETURN false
    ELSE IF ode.value < current.value
        insert(current.left, current, node)
    ELSE
        insert(current.right, current, node)
    END IF
END SUBROUTINE

In place of node, I've tried seemingly most of the allowed variables, including current, parent, (and even value, which didn't work. Shocker.)

bool recursiveInsert(Node* current, Node* parent, double value)
{

    if (current == NULL)
    {
        if (parent == NULL)
        {
        }
        else
        {
            if (current->value < parent->value)
            {
                parent->left = current;
            }
            else
            {
                parent->right = current;
            }
            return true;
        }
    }
    else if(parent->value == current->value)
    {
        return false;
    }
    else if (parent->value < current->value)
    {
        insert(current->left, current->value, current);
    }
    else
    {
        insert(current->right, current->value, current);
    }
}

I expect the output to add the value to the binary search tree and return true, but the program currently just throws a error whenever I get to the parts that require "node".

Body:
node in the context of the pseudocode is a previously allocated node containing the data being inserted into the tree. The initial caller allocates it (which is both pointless and never done in RW code).In reality, it is highly unlikely to actually do this pattern unless you're considering a library that potentially moves nodes out of one tree into another, and you want to avoid the expense of setting-up/tearing-down the nodes themselves.

Regarding the algorithm, it's fairly straightforward, though not very pretty:

If both current and parent are null, it means this must be the first node in the tree tracked by some global pointer root. Therefore, root is assigned the incoming node directly.

Otherwise, If current is null but parent is not if means parent is some potential leaf in the tree (meaning it has either a left, a right, or both contained pointers that are null), and you've landed on the null pointer. The insertion requires comparing against the parent value to know whether you hang the node on the left or the right. Note that this is inefficient, as you already did this comparison (it's how you got here in the first place).

Otherwise if current is not-null we simply check whether the values are equal, or less (greater is assumed if neither of those are true), and drive into the subtree of left or right if warranted. In that case, current.left or current.right become the recursed current, and current becomes the parent of said-same recursive call.

That's it. That's how that algorithm works. And frankly, it's marginal.

To implement this algorithm with your argument list (that takes a value rather than a node for the final argument), you need only ensure node allocation only happens when it is time to actually hang it, and only then (there are two such cases.

bool recursiveInsert(Node* current, Node* parent, double value)
{
    bool result = false;

    if (current == NULL)
    {
        if (parent == NULL)
        {
            root = malloc(sizeof *root);
            root->value = value;
            root->left = root->right = NULL;
        }
        else
        {
            Node *p = malloc(sizeof *p);
            p->value = value;
            p->left = p->right = NULL;

            if (value < parent->value)
            {
                parent->left = p;
            }
            else
            {
                parent->right = p;
            }
            result = true;
        }
    }
    else if (value < parent->value)
        result = recursiveInsert(current->left, current, value);

    else if (parent->value < value)
        result = recursiveInsert(current->right, current, value);

    return result;
}

When inserting a value into the tree, the call will look something like this:

recursiveInsert(root, NULL, value);

It's not pretty, but it works. That it relies on global root presence is probably the worst part of this algorithm. The multi-compare is probably second on the list of yuck.

A Different Approach

Ideally the root of the tree is passed in as an argument. Further, we can make the algorithm recursive as it is now, but no longer rely on some global root. Finally, we can reduce the argument count to two: the address of a pointer (initially the address of the root pointer), and the value being inserted. sing a pointer-to-pointer as the tree access method makes this algorithm elegant, whether using recursion or not. Both are provided below:

Recursive Insertion

bool treeInsert(Node **pp, double value)
{
    bool result = false;
    if (!*pp)
    {
        *pp = malloc(sizeof **pp);
        (*pp)->value = value;
        (*pp)->left = (*pp)->right = NULL;
        result = true;
    }
    else if (value < (*pp)->value)
    {
        result = recursiveInsert(&(*pp)->left, value);
    }
    else if ((*pp)->value < value)
    {
        result = recursiveInsert(&(*pp)->right, value);
    }
    return result;
}

Iterative Insertion

bool treeInsert(Node **pp, double value)
{
    bool result = false;

    while (*pp)
    {
        if (value < (*pp)->value)
            pp = &(*pp)->left;

        else if ((*pp)->value < value)
            pp = &(*pp)->right;

        else break;
    }

    if (!*pp)
    {
        *pp = malloc(sizeof **pp);
        (*pp)->value = value;
        (*pp)->left = (*pp)->right = NULL;
        result = true;
    }

    return result;
}

in either case, you invoke by passing the address of the root pointer (thus a pointer to pointer), where an empty try is signified by a NULL root:

treeInsert(&root, value);

Either function will accomplish the task at hand. I leave the error-hardening asa task for you (check your mallocs).


问:
Resizing div based on siblings of a specific class
I've found there's a simple way to count siblings of the
 tag and return a CSS style fit for the how many
 siblings there are:

ul{
 list-style-type: none;
    display: block;
}

#container{
 width: 100%;
 float: left;
 height: 100%;
 margin-left: 0;
 margin-top: 0;
}

li:first-child:nth-last-child(1) {
 height: 100%;
 background-color: red;
 width: 100%;
}

li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
 height: 100%;
 background-color: blue;
 float: left;
 width: 49%;
  margin-left: 1%;
}

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
 height: 100%;
 float: left;
 background-color: red;
 width: 33.333%;
}

li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
 height: 100%;
 background-color: blue;
 float: left;
 width: 24%;
  margin-left: 1%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
</div></code>```

I'm looking to hide
 tags with the class="hidden"

I've tried:

ul {
list-style: none;
}

li.hidden:first-child:nth-last-child(2),
li.hidden:first-child:nth-last-child(2) ~ li {
 display: none;
}

li.hidden:first-child:nth-last-child(3),
li.hidden:first-child:nth-last-child(3) ~ li {
 background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li class="hidden">1</li>
<li>2</li>
<li class="hidden">3</li>
<li>4</li>
</ul></code>```

Is there a way to selectively detect and change the CSS style of a
 tag with the class of "hidden" based on the number of
 tags with the class "hidden" without affecting the
 tags without the class of "hidden"?

答:
I have beautified/refactored your code (I think, is clearer this way) - I did not understand why do you want to use "first-child" in combination with "nth-last-child". How that supposed to work, I don't really understand.

Here's a quick reponse about this very same topic - Why you cannot achieve what you want from CSS only.
How to get nth-child selector to skip hidden divs

So, my response is not complete / is not working as you expect it. You'll have to use JQuery to achieve this, in my opinion.

ul{
 list-style-type: none;
    display: block;
}

#container{
 width: 100%;
 float: left;
 height: 100%;
 margin-left: 0;
 margin-top: 0;
}

li {
  color: yellow;
  float: left;
  height: 100%;
  line-height: 50px;
  margin-left: 1%;
  text-align: center;
  width: 20%;
}

li.hidden{
  display: none;
}

li:nth-child(1) {
 background-color: green;
}

li:not(.hidden):nth-child(2){
 background-color: silver;
}

li:not(.hidden):nth-child(3){
 background-color: red;
}

li:not(.hidden):nth-child(4){
 background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <ul>
      <li>1</li>
      <li class="hidden">2</li>
      <li>3</li>
      <li class="hidden">4</li>
  </ul>
</div></code>```

I have added a version with nth-of-type also - nothing new here. You should consider using jQuery.

ul{
  background: #eee;
  cursor: pointer;
  display: table;
 list-style-type: none;
  padding: 10px;
  width: 80%;
}

#container{
 width: 100%;
 float: left;
 height: 100%;
 margin-left: 0;
 margin-top: 0;
}

li {
  border: 1px solid #333;
  border-radius: 4px;
  color: #333;
  float: left;
  font-weight: bold;
  height: 100%;
  line-height: 50px;
  margin-left: 1%;
  text-align: center;
  width: 20%;
}

li.hidden{
  display: none;
}

ul:hover li.hidden {display: block;}

li:nth-of-type(1):not(.hidden) {
 background-color: green;
}

li:nth-of-type(2):not(.hidden){
 background-color: silver;
}

li:nth-of-type(3):not(.hidden){
 background-color: red;
}

li:nth-of-type(4):not(.hidden){
 background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <ul>
      <li>1</li>
      <li class="hidden">2</li>
      <li>3</li>
      <li class="hidden">4</li>
  </ul>
</div></code>```

Body:
I've found there's a simple way to count siblings of the
 tag and return a CSS style fit for the how many
 siblings there are:

ul{
 list-style-type: none;
    display: block;
}

#container{
 width: 100%;
 float: left;
 height: 100%;
 margin-left: 0;
 margin-top: 0;
}

li:first-child:nth-last-child(1) {
 height: 100%;
 background-color: red;
 width: 100%;
}

li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
 height: 100%;
 background-color: blue;
 float: left;
 width: 49%;
  margin-left: 1%;
}

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
 height: 100%;
 float: left;
 background-color: red;
 width: 33.333%;
}

li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
 height: 100%;
 background-color: blue;
 float: left;
 width: 24%;
  margin-left: 1%;
}

1

2

3

4

I'm looking to hide
 tags with the class="hidden"

I've tried:

ul {
list-style: none;
}

li.hidden:first-child:nth-last-child(2),
li.hidden:first-child:nth-last-child(2) ~ li {
 display: none;
}

li.hidden:first-child:nth-last-child(3),
li.hidden:first-child:nth-last-child(3) ~ li {
 background-color: blue;
}

1

2

3

4

Is there a way to selectively detect and change the CSS style of a
 tag with the class of "hidden" based on the number of
 tags with the class "hidden" without affecting the
 tags without the class of "hidden"?

Body:
I have beautified/refactored your code (I think, is clearer this way) - I did not understand why do you want to use "first-child" in combination with "nth-last-child". How that supposed to work, I don't really understand.

Here's a quick reponse about this very same topic - Why you cannot achieve what you want from CSS only.
How to get nth-child selector to skip hidden divs

So, my response is not complete / is not working as you expect it. You'll have to use JQuery to achieve this, in my opinion.

ul{
 list-style-type: none;
    display: block;
}

#container{
 width: 100%;
 float: left;
 height: 100%;
 margin-left: 0;
 margin-top: 0;
}

li {
  color: yellow;
  float: left;
  height: 100%;
  line-height: 50px;
  margin-left: 1%;
  text-align: center;
  width: 20%;
}

li.hidden{
  display: none;
}

li:nth-child(1) {
 background-color: green;
}

li:not(.hidden):nth-child(2){
 background-color: silver;
}

li:not(.hidden):nth-child(3){
 background-color: red;
}

li:not(.hidden):nth-child(4){
 background-color: blue;
}

<div id="container">
  <ul>
      <li>1</li>
      <li class="hidden">2</li>
      <li>3</li>
      <li class="hidden">4</li>
  </ul>
</div>

I have added a version with nth-of-type also - nothing new here. You should consider using jQuery.

ul{
  background: #eee;
  cursor: pointer;
  display: table;
 list-style-type: none;
  padding: 10px;
  width: 80%;
}

#container{
 width: 100%;
 float: left;
 height: 100%;
 margin-left: 0;
 margin-top: 0;
}

li {
  border: 1px solid #333;
  border-radius: 4px;
  color: #333;
  float: left;
  font-weight: bold;
  height: 100%;
  line-height: 50px;
  margin-left: 1%;
  text-align: center;
  width: 20%;
}

li.hidden{
  display: none;
}

ul:hover li.hidden {display: block;}

li:nth-of-type(1):not(.hidden) {
 background-color: green;
}

li:nth-of-type(2):not(.hidden){
 background-color: silver;
}

li:nth-of-type(3):not(.hidden){
 background-color: red;
}

li:nth-of-type(4):not(.hidden){
 background-color: blue;
}

<div id="container">
  <ul>
      <li>1</li>
      <li class="hidden">2</li>
      <li>3</li>
      <li class="hidden">4</li>
  </ul>
</div>


问:
How to click on lines in a textarea element
I have this textarea element, and i want each line in the box to be clickable and respond to javascript events, is that possible or am i looking for a different type of element?</p>

答:
A much less intensive version of the multi-div selectable layout could be accomplished with Data Tables.  See the tutorial here

They also offer tutorials on edit-in-place as well as select and delete.  If you're not already using a grid to present data, it's a great tool for UI.


问:
Separate field into different rows
I have a table called tableA, and the id field may stored values with comma at one record.

When I use sql: "select id from tableA", I will get the below result.

I do not know how to separate a row record into several rows like below:

27

19

7

18

...

Is it any hints for the sql script? Thank you.

答:
I'm not confident there isn't a nicer way, but maybe something like this is a good starting point:

```<code>SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(tablea.id, ',', numbers.row), ',', -1)
FROM
tablea INNER JOIN
-- This numbers subquery is taken from @Unreason's answer in https://stackoverflow.com/questions/304461/generate-an-integer-sequence-in-mysql
(
SELECT @row := @row + 1 AS row FROM
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,
(SELECT @row:=0) n) numbers
on numbers.row <= LENGTH(tablea.id)-LENGTH(REPLACE(tablea.id, ',', ''))+1
</code>```

Given tablea.id='27,19,8', SUBSTRING_INDEX(SUBSTRING_INDEX(tablea.id, ',', 1), ',', -1) will return the first element (27) and SUBSTRING_INDEX(SUBSTRING_INDEX(tablea.id, ',', 2), ',', -1) will return the second element (19), and so forth.

Therefore I join that with a list of numbers (in this case my list goes up to 100, so I am assuming a single tablea.id field never has more than 100 comma-separated values, although the details could be changed). The join condition uses LENGTH(tablea.id)-LENGTH(REPLACE(tablea.id, ',', ''))+1 which is a count of how many comma-separated values are in the field.

Here's a db fiddle of it working to play around with.

Title: Separate field into different rows

Body:
I'm not confident there isn't a nicer way, but maybe something like this is a good starting point:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(tablea.id, ',', numbers.row), ',', -1)
FROM
tablea INNER JOIN
-- This numbers subquery is taken from @Unreason's answer in https://stackoverflow.com/questions/304461/generate-an-integer-sequence-in-mysql
(
SELECT @row := @row + 1 AS row FROM
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,
(SELECT @row:=0) n) numbers
on numbers.row <= LENGTH(tablea.id)-LENGTH(REPLACE(tablea.id, ',', ''))+1

Given tablea.id='27,19,8', SUBSTRING_INDEX(SUBSTRING_INDEX(tablea.id, ',', 1), ',', -1) will return the first element (27) and SUBSTRING_INDEX(SUBSTRING_INDEX(tablea.id, ',', 2), ',', -1) will return the second element (19), and so forth.

Therefore I join that with a list of numbers (in this case my list goes up to 100, so I am assuming a single tablea.id field never has more than 100 comma-separated values, although the details could be changed). The join condition uses LENGTH(tablea.id)-LENGTH(REPLACE(tablea.id, ',', ''))+1 which is a count of how many comma-separated values are in the field.

Here's a db fiddle of it working to play around with.


问:
what constitues user gesture
I recently programmed a menu interface for javascript that lets you dynamically add options to it and mostly works with mouseEnter Events . I thne added some basic video Controls to it with request/exit Fullscreen that trigger on one of these mouseEnter events most of the time it displays Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture. however (weird part :) sometimes it works and im not sure how the browser api decides wether an action is a user gesture or not oO any help would be appreciated thanks

答:
Here is the list of events that can trigger "by user activation" as defined by the specs:

change

click

contextmenu

dblclick

mouseup

pointerup

reset

submit

touchend

This is what your error message refers to when they say "a user gesture".

mouseenter is not part of this list.

Most likely, when it worked, it was because one of those event did happen less than a few ms before (IIRC it's 50ms in Chrome currently).

Title: what constitues user gesture