问:
Rails 5 converts object to a string when passing on the params
In Rails 5 I have my sign up page using form_for helper to create a user, which is then directed to my custom confirm page.

```<code>  <%= form_for @user, url: {action: :confirm} do |f| %>
</code>```

In my confirm controller I can access parameters without any problem. This is how they are displayed in the console.

```<code> Parameters: {"utf8"=>"✓",
"authenticity_token"=>"<longBlaString>",
"user"=>{"name"=>"Railsmastanot",
         "email"=>"example@domain.com",
         "password"=>"[FILTERED]",
         "password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}
</code>```

I then use

<%= button_to "Yes", {controller: "users", action: "create",  params: params}, class: 'btn btn-success' %>

to redirect to the actual users#create method. Inside I am trying to access parameters, e.g. params[:user][:email] but get an error

no implicit conversion of Symbol into Integer

Examining console reveals than my parameters hash turned into this:

```<code>Parametes:
 {"authenticity_token"=>"longBlaString",
"commit"=>"Sign up",
"user"=>"email=example@domain.com&name=Railsmastanot&password=
<myActualPassword!>&password_confirmation=<myActualPassword!>",
"utf8"=>"✓"}
</code>```

So the user key no longer holds the hash, but a string. Is this supposed to happen or a bug? If not a bug, what is the correct way to handle this? Am I doing something wrong?

EDIT:

I figured out that params is not actually a hash in Rails 5. If I pass parameters like  params: params.to_unsafe_h it works, but I am not sure this is safe to do.

答:
Ok, I got a good answer here but it didn't really answer the question of what is going on. The root of the problem is the fact that in Rails 5 params returns an object, not a hash. So actually doing params: params.to_unsafe_h in Rails 5 seems to be equivalent to simply params: params in Rails 4. I was told that this is done simply because Rails 5 wants you to be aware of exactly what data you're transmitting so that you don't unwittingly transfer secure data unnecessarily (e.g. passing a whole user object when it's not required). It's an extension of the Strong Parameters feature already implemented in Rails 4.

As far as I see this doesn't really introduce any safety risks in this case, since the params.to_unsafe_h is converted back to parameter object straight away.

Body:
In Rails 5 I have my sign up page using form_for helper to create a user, which is then directed to my custom confirm page.

  <%= form_for @user, url: {action: :confirm} do |f| %>

In my confirm controller I can access parameters without any problem. This is how they are displayed in the console.

 Parameters: {"utf8"=>"✓",
"authenticity_token"=>"<longBlaString>",
"user"=>{"name"=>"Railsmastanot",
         "email"=>"example@domain.com",
         "password"=>"[FILTERED]",
         "password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}

I then use

<%= button_to "Yes", {controller: "users", action: "create",  params: params}, class: 'btn btn-success' %>

to redirect to the actual users#create method. Inside I am trying to access parameters, e.g. params[:user][:email] but get an error

no implicit conversion of Symbol into Integer

Examining console reveals than my parameters hash turned into this:

Parametes:
 {"authenticity_token"=>"longBlaString",
"commit"=>"Sign up",
"user"=>"email=example@domain.com&name=Railsmastanot&password=
<myActualPassword!>&password_confirmation=<myActualPassword!>",
"utf8"=>"✓"}

So the user key no longer holds the hash, but a string. Is this supposed to happen or a bug? If not a bug, what is the correct way to handle this? Am I doing something wrong?

EDIT:

I figured out that params is not actually a hash in Rails 5. If I pass parameters like  params: params.to_unsafe_h it works, but I am not sure this is safe to do.


来源: stackexchange

问:
Sql query to eliminate min and max
Lets assume a table to be like

```<code>Acc_nbr  sal1 sal2 sal3 sal4
123          10    20     30   40
124           10   30      40   15
126           16    20      25    16
</code>```

So in the above table i wanted to eliminate the min & max sal columns and only remaining sal columns need to be taken!

Eg: for acc_nbr 123 min sal =10 & max sal = 40
So as per my requirement i need to eliminate both 10 & 40, & need to take only 20&30.
Likewise the same to other acc_nbr's .
Please help.. thanks in advance!

答:
This is a hard problem for various reasons:

Your data is not stored in a proper relational format.  However, even storing the data with one row per salary would not make this much easier.

SQL in general does not have very good "intra-row" manipulation functionality.

MySQL does not offer arrays or easy ways to unpivot the data.

Duplicates and NULL values can be really troublesome.

If I assume that none of the values are NULL and you don't mind getting duplicates when there are ties at the extreme, then the following would work:

```<code>select t.*,
       (case when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
             when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal2
             when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal3
             when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal4
        end) as first_sal,
       (case when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal4
             when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal3
             when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal2
             when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as second_sal
from t;
</code>```

I should note that this problem would be easier in almost any other database.

EDIT:

Golly, you don't mention how many columns you want in the output.  If we just NULL out the extrema, this is easier:

```<code>select t.*,
       (case when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal1,
       (case when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal2,
       (case when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal3,
       (case when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal4
from t;
</code>```

This still assumes that the four sal values are not NULL.

ContentLicense: CC BY-SA 3.0

Title: Sql query to eliminate min and max

Body:
Lets assume a table to be like

Acc_nbr  sal1 sal2 sal3 sal4
123          10    20     30   40
124           10   30      40   15
126           16    20      25    16

So in the above table i wanted to eliminate the min & max sal columns and only remaining sal columns need to be taken!

Eg: for acc_nbr 123 min sal =10 & max sal = 40
So as per my requirement i need to eliminate both 10 & 40, & need to take only 20&30.
Likewise the same to other acc_nbr's .
Please help.. thanks in advance!

Body:
This is a hard problem for various reasons:

Your data is not stored in a proper relational format.  However, even storing the data with one row per salary would not make this much easier.

SQL in general does not have very good "intra-row" manipulation functionality.

MySQL does not offer arrays or easy ways to unpivot the data.

Duplicates and NULL values can be really troublesome.

If I assume that none of the values are NULL and you don't mind getting duplicates when there are ties at the extreme, then the following would work:

select t.*,
       (case when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
             when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal2
             when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal3
             when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal4
        end) as first_sal,
       (case when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal4
             when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal3
             when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal2
             when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as second_sal
from t;

I should note that this problem would be easier in almost any other database.

EDIT:

Golly, you don't mention how many columns you want in the output.  If we just NULL out the extrema, this is easier:

select t.*,
       (case when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal1,
       (case when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal2,
       (case when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal3,
       (case when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
             then sal1
        end) as sal4
from t;

This still assumes that the four sal values are not NULL.


问:
grep for a variable excluding the dot sign
I want to grep a variable excluding those that start with a dot sign. However choosing the -w option for entire word doesn't include a dot sign so instead of only selecting 4 55 48 it also selects 0.4 0.55 5.48.

e.g. $var=1565

input

```<code>A 3.00027 1565
B 3.00026 1565
C -1.1565 5000
</code>```

desired output

```<code>A 3.00027 1565
B 3.00026 1565
</code>```

I have seen solutions to grep for an exact pattern starting with grep, but that doesn't work with a variable.

I have tried adding a space sign before the variable as in lines below but it doesn't give desired output either.

```<code>grep -E -w " $var" input.txt > output.txt #results in empty output
grep -E -w "[:space:]|$var" input.txt > output.txt # gives solutions that include the dot sign
</code>```

答:
```<code>var=1565
cat input.txt|uniq|grep -E ^[A-Z]+.*$var >output.txt
</code>```

here you go, make a pattern and match it with uniq filtered lines.
The desired pattern to match those lines is *1565. I just stored that pattern in a variable.

test this out

```<code>awk -F " " "{if(\$3==$var){print(\$0);}}" input.txt
</code>```

Body:
I want to grep a variable excluding those that start with a dot sign. However choosing the -w option for entire word doesn't include a dot sign so instead of only selecting 4 55 48 it also selects 0.4 0.55 5.48.

e.g. $var=1565

input

A 3.00027 1565
B 3.00026 1565
C -1.1565 5000

desired output

A 3.00027 1565
B 3.00026 1565

I have seen solutions to grep for an exact pattern starting with grep, but that doesn't work with a variable.

I have tried adding a space sign before the variable as in lines below but it doesn't give desired output either.

grep -E -w " $var" input.txt > output.txt #results in empty output
grep -E -w "[:space:]|$var" input.txt > output.txt # gives solutions that include the dot sign

Body:
var=1565
cat input.txt|uniq|grep -E ^[A-Z]+.*$var >output.txt

here you go, make a pattern and match it with uniq filtered lines.
The desired pattern to match those lines is *1565. I just stored that pattern in a variable.

test this out

awk -F " " "{if(\$3==$var){print(\$0);}}" input.txt


问:
Check for username and password in a text file
I have to implement a login system and for this purpose when an account is created i save the data in a text file. the data is in the format {username} {password} {bestScore}. But when it comes to the login and i have more users. My algorithm checks every single line of the text file and if the user exists go to the main menu panel. If the username is wrong open joptionpane telling the user that username is incorrect or same for the password. The thing is that it executes for the first line of the file in all the cases and the while loop breaks. Thats not my idea. I want to check for the username and password match in the entire text file. Not for every line of the file. This is my code (which is not working the way i want) :

```<code>private static final Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+) ([0-9]+)$");
loginButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt"))))) {
                String line = br.readLine();

                while (line != null) {
                    Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(line);

                    if (userNameAndPasswordMatcher.matches()) {
                        String username = userNameAndPasswordMatcher.group(1);
                        String password = userNameAndPasswordMatcher.group(2);
                        String bestScore = userNameAndPasswordMatcher.group(3);

                        String pwd = new String(passField.getPassword());

                        if (username.equals(usernameField.getText()) && !password.equals(pwd)) {
                            int result = JOptionPane.showConfirmDialog(null, "Incorrect password!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                passField.setText("");
                            }
                        }
                        else if (!username.equals(usernameField.getText()) && password.equals(pwd)) {
                            int result = JOptionPane.showConfirmDialog(null, "Incorrect username!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                usernameField.setText("");
                            }
                        }
                        else if (!username.equals(usernameField.getText()) && !password.equals(pwd)) {
                            int result = JOptionPane.showConfirmDialog(null, "This account don't exist!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                usernameField.setText("");
                                passField.setText("");
                            }
                        }
                        else if (username.equals(usernameField.getText()) && password.equals(pwd)) {
                            gd.setCurrentUser(username);
                            gd.setBestScore(Integer.parseInt(bestScore));

                            rdialog = new RedirectingDialog(frame);
                            rdialog.setVisible(true);
                        }
                    }
                    line = br.readLine();
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });
</code>```

Here you can see that in the first line of input i will go to the one of the 4 cases and the while loop will stop. But if the username is on the second line for example i got the Dialog with message "Incorrect username". One of my ideas is to append everything from the file to a StringBuilder and then with .contains to check if username and password exist but i feel it kinda wrong because if i match username and password with contains it will check in the entire text file for combinations. E.g username can be on the first line password can be on the 3rd line and there will be match. Thats not what i want. They have to be on the same line to have the match.

答:
First I think you need to get your requirements precise — then it will be much easier to think about what is right and wrong in the program.

I assume that is the user name is correct, then it will appear exactly once in the file. If the user name is incorrect, it will most likely not appear in the file; however, we cannot rule out the possibility that someone accidentally enters someone else’s user name if the names are somewhat like each other.

In the two cases where !username.equals(usernameField.getText()) you shouldn’t do anything, just continue searching through the file for the correct user name.

Once you find the correct username, you can do what you have to do depending on whether the password is correct or not. After that, if you like you can break out of the loop because you know that you will not find the user name again later in the file.

Finally, if you’ve gone all the way through the file without finding the user name, you should issue the message about the user name being incorrect.

In code, something like this (not tested):

```<code>            boolean userNameFound = false;
            while (line != null) {
                Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(line);

                if (userNameAndPasswordMatcher.matches()) {
                    String username = userNameAndPasswordMatcher.group(1);
                    String password = userNameAndPasswordMatcher.group(2);
                    String bestScore = userNameAndPasswordMatcher.group(3);

                    String pwd = new String(passField.getPassword());

                    if (username.equals(usernameField.getText())) {
                        userNameFound = true;
                        if (password.equals(pwd)) {
                            gd.setCurrentUser(username);
                            gd.setBestScore(Integer.parseInt(bestScore));

                            rdialog = new RedirectingDialog(frame);
                            rdialog.setVisible(true);
                        } else { // password does not match
                            int result = JOptionPane.showConfirmDialog(null, "Incorrect password!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                passField.setText("");
                            }
                        }
                        break;
                    }
                }
            }
            if (! userNameFound) {
                int result = JOptionPane.showConfirmDialog(null, "Incorrect password!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {
                    passField.setText("");
                }
            }
</code>```

Body:
I have to implement a login system and for this purpose when an account is created i save the data in a text file. the data is in the format {username} {password} {bestScore}. But when it comes to the login and i have more users. My algorithm checks every single line of the text file and if the user exists go to the main menu panel. If the username is wrong open joptionpane telling the user that username is incorrect or same for the password. The thing is that it executes for the first line of the file in all the cases and the while loop breaks. Thats not my idea. I want to check for the username and password match in the entire text file. Not for every line of the file. This is my code (which is not working the way i want) :

private static final Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+) ([0-9]+)$");
loginButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt"))))) {
                String line = br.readLine();

                while (line != null) {
                    Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(line);

                    if (userNameAndPasswordMatcher.matches()) {
                        String username = userNameAndPasswordMatcher.group(1);
                        String password = userNameAndPasswordMatcher.group(2);
                        String bestScore = userNameAndPasswordMatcher.group(3);

                        String pwd = new String(passField.getPassword());

                        if (username.equals(usernameField.getText()) && !password.equals(pwd)) {
                            int result = JOptionPane.showConfirmDialog(null, "Incorrect password!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                passField.setText("");
                            }
                        }
                        else if (!username.equals(usernameField.getText()) && password.equals(pwd)) {
                            int result = JOptionPane.showConfirmDialog(null, "Incorrect username!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                usernameField.setText("");
                            }
                        }
                        else if (!username.equals(usernameField.getText()) && !password.equals(pwd)) {
                            int result = JOptionPane.showConfirmDialog(null, "This account don't exist!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                usernameField.setText("");
                                passField.setText("");
                            }
                        }
                        else if (username.equals(usernameField.getText()) && password.equals(pwd)) {
                            gd.setCurrentUser(username);
                            gd.setBestScore(Integer.parseInt(bestScore));

                            rdialog = new RedirectingDialog(frame);
                            rdialog.setVisible(true);
                        }
                    }
                    line = br.readLine();
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });

Here you can see that in the first line of input i will go to the one of the 4 cases and the while loop will stop. But if the username is on the second line for example i got the Dialog with message "Incorrect username". One of my ideas is to append everything from the file to a StringBuilder and then with .contains to check if username and password exist but i feel it kinda wrong because if i match username and password with contains it will check in the entire text file for combinations. E.g username can be on the first line password can be on the 3rd line and there will be match. Thats not what i want. They have to be on the same line to have the match.

Body:
First I think you need to get your requirements precise — then it will be much easier to think about what is right and wrong in the program.

I assume that is the user name is correct, then it will appear exactly once in the file. If the user name is incorrect, it will most likely not appear in the file; however, we cannot rule out the possibility that someone accidentally enters someone else’s user name if the names are somewhat like each other.

In the two cases where !username.equals(usernameField.getText()) you shouldn’t do anything, just continue searching through the file for the correct user name.

Once you find the correct username, you can do what you have to do depending on whether the password is correct or not. After that, if you like you can break out of the loop because you know that you will not find the user name again later in the file.

Finally, if you’ve gone all the way through the file without finding the user name, you should issue the message about the user name being incorrect.

In code, something like this (not tested):

            boolean userNameFound = false;
            while (line != null) {
                Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(line);

                if (userNameAndPasswordMatcher.matches()) {
                    String username = userNameAndPasswordMatcher.group(1);
                    String password = userNameAndPasswordMatcher.group(2);
                    String bestScore = userNameAndPasswordMatcher.group(3);

                    String pwd = new String(passField.getPassword());

                    if (username.equals(usernameField.getText())) {
                        userNameFound = true;
                        if (password.equals(pwd)) {
                            gd.setCurrentUser(username);
                            gd.setBestScore(Integer.parseInt(bestScore));

                            rdialog = new RedirectingDialog(frame);
                            rdialog.setVisible(true);
                        } else { // password does not match
                            int result = JOptionPane.showConfirmDialog(null, "Incorrect password!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                            if (result == JOptionPane.OK_OPTION) {
                                passField.setText("");
                            }
                        }
                        break;
                    }
                }
            }
            if (! userNameFound) {
                int result = JOptionPane.showConfirmDialog(null, "Incorrect password!", "Login incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {
                    passField.setText("");
                }
            }


问:
After jquery auto refresh a div popup doesnt work
I have a jquery which refreshes the div but after refresh the popup doesn't work from the refreshed data.

```<code><script type="text/javascript">
    $(function() {
        $.ajaxSetup ({
            cache: false
        });
        //Refresh trigger `#newORDERx`
        var auto_refreshes = setInterval(function () {$('#newORDERx').load('inc/restAdmin_orders_rcvz.php');}, 1000);
    });
</script>
<div id="newORDERx"></div>
</code>```

When i use it like below then popup works fine but then it doesn't refresh the div.

```<code><script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup ({
            cache: false
            mainClass: 'pp-product-detail' // when i use this then popup works but then doesn't refresh the div
        });
        var auto_refreshes = setInterval(function () {$('#newORDERx').load('inc/restAdmin_orders_rcvz.php');}, 1000);
    });

</script>
</code>```

pp-product-detail class

```<code>AJAX popup

if ($('.pp-product-detail').length) {
   $('.pp-product-detail').magnificPopup({
       type: 'ajax'
   });
}
</code>```

restAdmin_orders_rcvz.php

```<code><div class="col-lg-6">
  <div class="the-menu-item">
    <div class="image-wrap">
      <a class="pp-product-detail" href="product-detail-popup-rest-admin-order-rcv.php?iid=<?php echo $phporder; ?>">
      <img src="images/themenu/img-1.jpg" alt="">
      </a>
    </div>
    <div class="the-menu-body">
      <b><font color='red'> Order # </font> <?php echo $phporder; ?><br>
      <font color='red'> Items Included : </font> <?php echo $lrsa['count']; ?>
      <br><font color='red'>Dated : </font> <?php echo date("d/m/Y", strtotime($phpdates)); ?>
      </b>
    </div>
  </div>
</div>
</code>```

答:
I have just added following file in restAdmin_orders_rcvz.php and its working fine.

```<code><script type="text/javascript" src="js/scripts.js"></script>
</code>```

restAdmin_orders_rcvz.php

```<code><div class="col-lg-6">
  <div class="the-menu-item">
    <div class="image-wrap">
      <a class="pp-product-detail" href="product-detail-popup-rest-admin-order-rcv.php?iid=<?php echo $phporder; ?>">
      <img src="images/themenu/img-1.jpg" alt="">
      </a>
    </div>
    <div class="the-menu-body">
      <b><font color='red'> Order # </font> <?php echo $phporder; ?><br>
      <font color='red'> Items Included : </font> <?php echo $lrsa['count']; ?>
      <br><font color='red'>Dated : </font> <?php echo date("d/m/Y", strtotime($phpdates)); ?>
      </b>
    </div>
  </div>
</div>
</code>```

Body:
I have a jquery which refreshes the div but after refresh the popup doesn't work from the refreshed data.

When i use it like below then popup works fine but then it doesn't refresh the div.

pp-product-detail class

AJAX popup

if ($('.pp-product-detail').length) {
   $('.pp-product-detail').magnificPopup({
       type: 'ajax'
   });
}

restAdmin_orders_rcvz.php

      <a class="pp-product-detail" href="product-detail-popup-rest-admin-order-rcv.php?iid=<?php echo $phporder; ?>">

       Order #  <?php echo $phporder; ?>

       Items Included :  <?php echo $lrsa['count']; ?>

Dated :  <?php echo date("d/m/Y", strtotime($phpdates)); ?>

Body:
I have just added following file in restAdmin_orders_rcvz.php and its working fine.

<script type="text/javascript" src="js/scripts.js"></script>

restAdmin_orders_rcvz.php

<div class="col-lg-6">
  <div class="the-menu-item">
    <div class="image-wrap">
      <a class="pp-product-detail" href="product-detail-popup-rest-admin-order-rcv.php?iid=<?php echo $phporder; ?>">
      <img src="images/themenu/img-1.jpg" alt="">
      </a>
    </div>
    <div class="the-menu-body">
      <b><font color='red'> Order # </font> <?php echo $phporder; ?><br>
      <font color='red'> Items Included : </font> <?php echo $lrsa['count']; ?>
      <br><font color='red'>Dated : </font> <?php echo date("d/m/Y", strtotime($phpdates)); ?>
      </b>
    </div>
  </div>
</div>


问:
Angular 2: property becomes underfined
The problem is that the property which is passed to the view child becomes undefined:

Parent component:

```<code>@Component({
    selector: 'app-searchbox',
    template: `
            <app-artifact-list [artifacts]="searchResults"></app-artifact-list>
    `
})
export class SearchboxComponent implements OnInit {

    // explicitly initialize the property
    // the same effect with constructor initialization
    searchResults: Artifact[] = [new Artifact()];

    constructor(private artifactService: ArtifactService) {
    }

    ngOnInit(): void {
        this.pollService(this.artifactService.findByQuery('guice'));
    }

    private pollService(request: Observable<Artifact[]>) {
        return request.subscribe(this.fillInResults);
    }

    private fillInResults(result: Artifact[]) {
        result.forEach(console.log);
        for (let obj of result) {
            // this.searchResults is undefined! why?
            this.searchResults.push(obj);
        }
    }

}
</code>```

Child component:

```<code>@Component({
    selector: 'app-artifact-list',
    template: `
            <h1>{{_artifacts | json}}</h1>
    `
})
export class ArtifactListComponent implements OnChanges {

    private _artifacts: Artifact[] = [];

    ngOnChanges(changes: SimpleChanges): void {
        console.log('Property changed');
    }

    @Input()
    set artifacts(artifacts: Artifact[]) {
        console.error('Property changed');
        this._artifacts = artifacts;
    }

}
</code>```

During constructor call I see that the property is properly initialized but in the callback method it becomes undefined.

Isn't it somehow related to this? Maybe this.searchResults refers to anything else in the callback?

答:
After some investigation into this when it is used in scope of "function references", I found out that actually this refers to another object. I love javascript :)

So the workaround is:

```<code>private pollService(request: Observable<Artifact[]>) {
    return request.subscribe(
        this.fillInResults.bind(this)
    );
}

private fillInResults(result: any) {
    result.forEach(console.log);
    for (let obj of result) {
        this.searchResults.push(obj);
    }
}
</code>```

Or to use fat arrow function:

```<code>private pollService(request: Observable<Artifact[]>) {
    return request.subscribe(
        result => this.fillInResults(result)
    );
}

private fillInResults(result: any) {
    result.forEach(console.log);
    for (let obj of result) {
        this.searchResults.push(obj);
    }
}
</code>```

See this question for detailed explanation: Angular2 component's “this” is undefined when executing callback function

Title: Angular 2: property becomes underfined

Body:
The problem is that the property which is passed to the view child becomes undefined:

Parent component:

@Component({
    selector: 'app-searchbox',
    template: `
            <app-artifact-list [artifacts]="searchResults"></app-artifact-list>
    `
})
export class SearchboxComponent implements OnInit {

    // explicitly initialize the property
    // the same effect with constructor initialization
    searchResults: Artifact[] = [new Artifact()];

    constructor(private artifactService: ArtifactService) {
    }

    ngOnInit(): void {
        this.pollService(this.artifactService.findByQuery('guice'));
    }

    private pollService(request: Observable<Artifact[]>) {
        return request.subscribe(this.fillInResults);
    }

    private fillInResults(result: Artifact[]) {
        result.forEach(console.log);
        for (let obj of result) {
            // this.searchResults is undefined! why?
            this.searchResults.push(obj);
        }
    }

}

Child component:

@Component({
    selector: 'app-artifact-list',
    template: `

{{_artifacts | json}}

    `
})
export class ArtifactListComponent implements OnChanges {

    private _artifacts: Artifact[] = [];

    ngOnChanges(changes: SimpleChanges): void {
        console.log('Property changed');
    }

    @Input()
    set artifacts(artifacts: Artifact[]) {
        console.error('Property changed');
        this._artifacts = artifacts;
    }

}

During constructor call I see that the property is properly initialized but in the callback method it becomes undefined.

Isn't it somehow related to this? Maybe this.searchResults refers to anything else in the callback?

Body:
After some investigation into this when it is used in scope of "function references", I found out that actually this refers to another object. I love javascript :)

So the workaround is:

private pollService(request: Observable<Artifact[]>) {
    return request.subscribe(
        this.fillInResults.bind(this)
    );
}

private fillInResults(result: any) {
    result.forEach(console.log);
    for (let obj of result) {
        this.searchResults.push(obj);
    }
}

Or to use fat arrow function:

private pollService(request: Observable<Artifact[]>) {
    return request.subscribe(
        result => this.fillInResults(result)
    );
}

private fillInResults(result: any) {
    result.forEach(console.log);
    for (let obj of result) {
        this.searchResults.push(obj);
    }
}

See this question for detailed explanation: Angular2 component's “this” is undefined when executing callback function


问:
can PHP create a new PHP and access thus the server?
i am quite new to the PHP business and thus please forgive me, if the questions sounds stupid to you. (always ask for forgiveness, never for permission ;) </p>

<p>Nevertheless, my theoretical question: I have a php based website, which is located in web root. This Php allows to create another php file, and its saved also in the web root. Later, i can "request" this newly created php and thus the php will be run. That means for my understanding, as a php script can include/access files outside the web root, I have basically full access to the server via this php-programm. Is it right ? I would be shocked if it is true .... so if I am wrong, what is preventing this access ? </p>

答: This is going to be based on file permissions. If you're on a hosted server, you have permission to change everything on your area of the server (and you'll have a special identity that gives your permission). You should also be able to send requests just about anywhere (which is including/accessing files outside your area). Chances are your special user does not have permission to write outside your dedicated space on the server. This is pretty standard. I'd look into File Permissions, and how they work on webservers if you're interested in learning more.

Body:
i am quite new to the PHP business and thus please forgive me, if the questions sounds stupid to you. (always ask for forgiveness, never for permission ;)

Nevertheless, my theoretical question: I have a php based website, which is located in web root. This Php allows to create another php file, and its saved also in the web root. Later, i can "request" this newly created php and thus the php will be run. That means for my understanding, as a php script can include/access files outside the web root, I have basically full access to the server via this php-programm. Is it right ? I would be shocked if it is true .... so if I am wrong, what is preventing this access ?


问:
Collapsible list with JavaScript
I am trying to implement this code into my website. Basically,

I downloaded the .js file, added to the main folder, and added the following to the head of the HTML file:

Added a trivial list to the HTML file:

```<code><ul class="collapsibleList">
<li>
Test 1
<ul>
<li>Yes</li>
</ul>
</li>
<li>
Test 2
<ul>
<li>No</li>
</ul>
</li>
</ul>
</code>```

and added some styling to the CSS, to have a plus/minus icon when the tree is closed/open:

```<code>.collapsibleList li{
list-style-image: url(images/plus.svg);
cursor: auto;
}

li.collapsibleListOpen{
list-style-image: url(images/minus.svg);
cursor: pointer;
}

li.collapsibleListClosed{
list-style-image: url(images/plus.svg);
cursor: pointer;
}
</code>```

Yet, the code does not work. This seems to be because I need to "apply" the function to the given element. As the page states:

The apply function turns any list with the class ‘collapsibleList’ into a tree view and collapses its sub-lists:

```<code>1 // make the appropriate lists collapsible
2 CollapsibleLists.apply();
</code>```

This function should generally be called immediately after page load, using code such as runOnLoad.

But then I got lost. I checked the referred page, added the RunOnLoad js to the page too, but still nothing.

This must be a trivial issue. As you could guess, I know next to nothing of JS. I just want to add a nice collapsible tree, which has different symbols when open and closed. JS seems to be the only choice here.

UPDATE: I went to the source code of the page I am getting the code from, because the author shows one example of a collapsible list. Then, I implemented his code into mine. In particular, I added the following into my head:

```<code><script>var runOnLoad=function(c,o,d,e){function x(){for(e=1;c.length;)c.shift()()}o[d]?(document[d]('DOMContentLoaded',x,0),o[d]('load',x,0)):o.attachEvent('onload',x);return function(t){e?o.setTimeout(t,0):c.push(t)}}([],window,'addEventListener');</script>
<script type="text/javascript">
</code>```

This was the bit that I thought I was missing. Yet, I can't make it work!
      runOnLoad(function(){ CollapsibleLists.apply(); });

```<code></script>
</code>```

答:
You can use this instead:

```<code>document.addEventListener("DOMContentLoaded", function(event) {
    //your code to run since DOM is loaded and ready
    CollapsibleLists.apply();
});
</code>```

if you're using jQuery:

```<code>$(document).ready(function(){
 CollapsibleLists.apply();
})
</code>```

Title: Collapsible list with JavaScript

Body:
I am trying to implement this code into my website. Basically,

I downloaded the .js file, added to the main folder, and added the following to the head of the HTML file:

Added a trivial list to the HTML file:

Test 1

Yes

Test 2

No

and added some styling to the CSS, to have a plus/minus icon when the tree is closed/open:

.collapsibleList li{
list-style-image: url(images/plus.svg);
cursor: auto;
}

li.collapsibleListOpen{
list-style-image: url(images/minus.svg);
cursor: pointer;
}

li.collapsibleListClosed{
list-style-image: url(images/plus.svg);
cursor: pointer;
}

Yet, the code does not work. This seems to be because I need to "apply" the function to the given element. As the page states:

The apply function turns any list with the class ‘collapsibleList’ into a tree view and collapses its sub-lists:

1 // make the appropriate lists collapsible
2 CollapsibleLists.apply();

This function should generally be called immediately after page load, using code such as runOnLoad.

But then I got lost. I checked the referred page, added the RunOnLoad js to the page too, but still nothing.

This must be a trivial issue. As you could guess, I know next to nothing of JS. I just want to add a nice collapsible tree, which has different symbols when open and closed. JS seems to be the only choice here.

UPDATE: I went to the source code of the page I am getting the code from, because the author shows one example of a collapsible list. Then, I implemented his code into mine. In particular, I added the following into my head:

Body:
You can use this instead:

document.addEventListener("DOMContentLoaded", function(event) {
    //your code to run since DOM is loaded and ready
    CollapsibleLists.apply();
});

if you're using jQuery:

$(document).ready(function(){
 CollapsibleLists.apply();
})


问:
Get internal byte array from ByteArrayInputStream
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?

Thanks,

答:
With the library Apache COmmons IO (http://commons.apache.org/io/) you can use the IOUtils.toByteArray(java.io.InputStream input)

Edit : ok, I didn't understood the question... no copy...
Maybe something like :

```<code>byte[] buf = new byte[n];
ByteArrayInputStream input = new ByteArrayInputStream(buf);
</code>```

will allow you to keep a reference to the buffer used by the input stream

ContentLicense: CC BY-SA 2.5

Body:
With the library Apache COmmons IO (http://commons.apache.org/io/) you can use the IOUtils.toByteArray(java.io.InputStream input)

Edit : ok, I didn't understood the question... no copy...
Maybe something like :

byte[] buf = new byte[n];
ByteArrayInputStream input = new ByteArrayInputStream(buf);

will allow you to keep a reference to the buffer used by the input stream

ContentLicense: CC BY-SA 4.0


问:
Pygame: set absolute sound volume using multiple channels
I need to set different volumes for the right and left ears for a sound at every iteration of a loop. And I represent sound for left and right ears by using two channels one, for each ear.

However, based on the documentation every time set_volume is called it sets volume at a percentage of the previous value.

```<code> channel1.set_volume(0.0, 0.5) # sets at 0.5
 channel1.set_volume(0.0, 0.5) # sets at 0.5 * 0.5 = 0.25
</code>```

I currently avoid this problem by calling channel.play at every iteration of the loop, which resets the volume to 1. However it also just restarts the sound file at every iteration. Is there a better way to do this?

```<code># Current implementation
while True:
   chan1.play(sound)
   chan1.set_volume(volLeft, 0.0)

   chan2.play(sound)
   chan2.set_volume(0.0, volRight)
</code>```

There is a similar question (Setting volume globally in pygame.Sound module). I tried manipulating the volume of two different sound variables but the volumes don't change on the right and left ear

If this is not possible in pygame, do you know of any other python sound libraries in which this is possible?

Thank you

答:
I manipulated the volume by assigning a Sound object to each channel and setting the volume for that sound object</p>

```<code># initialise variables
sound = pygame.mixer.Sound(sound_path)
sound_2 = pygame.mixer.Sound(sound_path)
chan1 = pygame.mixer.Channel(0)
chan2 = pygame.mixer.Channel(1)

# set channel to max
chan1.set_volume(1, 0)
chan2.set_volume(0, 1)

# set sound to initial value
sound.set_volume(0)
sound2.set_volume(0)

chan1.play(sound, 50, 0, 0)
chan2.play(sound2, 50, 0, 0)

while True:

   volLeft = getLeftVol()
   volRight = getRightVol()

   # change volume of sound every iteration
   sound.set_volume(volLeft)
   sound2.set_volume(volRight)

   if isDone:
      break
</code>```

Body:
I need to set different volumes for the right and left ears for a sound at every iteration of a loop. And I represent sound for left and right ears by using two channels one, for each ear.

However, based on the documentation every time set_volume is called it sets volume at a percentage of the previous value.

 channel1.set_volume(0.0, 0.5) # sets at 0.5
 channel1.set_volume(0.0, 0.5) # sets at 0.5 * 0.5 = 0.25

I currently avoid this problem by calling channel.play at every iteration of the loop, which resets the volume to 1. However it also just restarts the sound file at every iteration. Is there a better way to do this?

# Current implementation
while True:
   chan1.play(sound)
   chan1.set_volume(volLeft, 0.0)

   chan2.play(sound)
   chan2.set_volume(0.0, volRight)

There is a similar question (Setting volume globally in pygame.Sound module). I tried manipulating the volume of two different sound variables but the volumes don't change on the right and left ear

If this is not possible in pygame, do you know of any other python sound libraries in which this is possible?

Thank you

Body:
I manipulated the volume by assigning a Sound object to each channel and setting the volume for that sound object

# initialise variables
sound = pygame.mixer.Sound(sound_path)
sound_2 = pygame.mixer.Sound(sound_path)
chan1 = pygame.mixer.Channel(0)
chan2 = pygame.mixer.Channel(1)

# set channel to max
chan1.set_volume(1, 0)
chan2.set_volume(0, 1)

# set sound to initial value
sound.set_volume(0)
sound2.set_volume(0)

chan1.play(sound, 50, 0, 0)
chan2.play(sound2, 50, 0, 0)

while True:

   volLeft = getLeftVol()
   volRight = getRightVol()

   # change volume of sound every iteration
   sound.set_volume(volLeft)
   sound2.set_volume(volRight)

   if isDone:
      break


问:
Adding new StoryBoard to UITabbarController
I have many storyboards in my app. Earlier my app was not a UITabBar based app but now i decided to go in  a more UITabBar way. Now i want to add my storyboards to my UITabBarController. I opened one storyboard and embed that in the UITabBarController, but now i don't know how i can add other storybord's first UIViewControllers to my Tabbar. I don't have any tabBarController Property etc.

Any idea how i can add different story boards to one UITabBarController

答:
Swift 3 for N8P's answer: implementing TabBarController using multiple storyboards.

```<code>   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let tabBar = UITabBarController()
    tabBar.viewControllers = self.getArrayOfViewControllers()
    self.customiseTabItems(tabBar: tabBar.tabBar)
    // set tabBar as root

    self.window?.rootViewController = tabBar
    self.window?.makeKeyAndVisible()
    return true
}
</code>```

see example

Body:
Swift 3 for N8P's answer: implementing TabBarController using multiple storyboards.

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let tabBar = UITabBarController()
    tabBar.viewControllers = self.getArrayOfViewControllers()
    self.customiseTabItems(tabBar: tabBar.tabBar)
    // set tabBar as root

    self.window?.rootViewController = tabBar
    self.window?.makeKeyAndVisible()
    return true
}

see example


问:
Grails refresh chart
I'm using a morris.js pie chart in my grails project and now i try to count an int after a button click and refresh the chart. But if i use "redirect" it refresh the whole site.
So is there a recommended way to refresh only the chart?

gsp:

```<code><g:form controller="blankTest">
    <g:actionSubmit value="Update" action="action"/>
</g:form>
<div id="myfirstchart" style="height: 250px;"></div>

<g:javascript id="test">
    new Morris.Donut({
        // ID of the element in which to draw the chart.
        element: 'myfirstchart',

        label: 'Test',

        resize: true,

        colors : ['#00ff00', '#ff0000', '#ffff00'],

        data: [
            { label: 'Number1', value: ${number}},
            { label: 'Number2', value: ${number1}},
            { label: 'Number3', value: ${number2}}
        ],
    });
</g:javascript>
</code>```

Controller:

```<code>int number = 0

def index() {
    [number: number, number1: 34, number2: 8]
}

def action() {
    number++
    redirect view: 'index'
}
</code>```

答:
The idea is creating a request by an ajax call, which will give you a response that you will use for updating your Morris donut.

So you could use your form for creating a ajax call. You have two options:

Using remote tags (out of the box on 1.x and 2.x grails versions, or with remote tags plugin on grails 3.x. Using a remote form, you could update a piece of your html code with the response from an action, which renders a template.

Implementing your own ajax method, recommended for a well code implementation, cause a remote ajax grails tag appends js code on your HTML. It is not good at all (a front-end dev will kill you and a kitty cat also :) ), and is deprecated.

This ajax request has to return you a new data model, could be in a JSON format and you can update your donut with the method js setData.

```<code><g:form name="form" controller="blankTest">
    <input type="submit" value="Update"/>
</g:form>
<div id="myfirstchart" style="height: 250px;"></div>

<g:javascript id="test">
    //we will need this reference for updating it
    var donut = new Morris.Donut({
        // ID of the element in which to draw the chart.
        element: 'myfirstchart',

        label: 'Test',

        resize: true,

        colors : ['#00ff00', '#ff0000', '#ffff00'],

        data: [
            { label: 'Number1', value: ${number}},
            { label: 'Number2', value: ${number1}},
            { label: 'Number3', value: ${number2}}
        ],
    });

$(document).ready(function(){
   $('#form').submit(function(event){
       event.preventDefault(); //blocks native form submit

       $.ajax('${createLink(controller: 'blankTest', action: 'action')}', {
           success: function (data) {
               var response = $.parseJSON(data);
               donut.setData(response); //updating the donut with json response
           }
       });
   });

});
</g:javascript>
</code>```

And your action should be something like this

```<code>def action() {
    number++
    List result = [
       [label: 'Number1', value: number],
       [label: 'Number2', value: number1],
       [label: 'Number3', value: number2]
    ]

    render result as JSON
}
</code>```

For more complex JSON's consider use JSON views if you are using Grails greater than v.3.1

Title: Grails refresh chart

Body:
I'm using a morris.js pie chart in my grails project and now i try to count an int after a button click and refresh the chart. But if i use "redirect" it refresh the whole site.
So is there a recommended way to refresh only the chart?

gsp:

<g:form controller="blankTest">
    <g:actionSubmit value="Update" action="action"/>
</g:form>

<g:javascript id="test">
    new Morris.Donut({
        // ID of the element in which to draw the chart.
        element: 'myfirstchart',

        label: 'Test',

        resize: true,

        colors : ['#00ff00', '#ff0000', '#ffff00'],

        data: [
            { label: 'Number1', value: ${number}},
            { label: 'Number2', value: ${number1}},
            { label: 'Number3', value: ${number2}}
        ],
    });
</g:javascript>

Controller:

int number = 0

def index() {
    [number: number, number1: 34, number2: 8]
}

def action() {
    number++
    redirect view: 'index'
}

Body:
The idea is creating a request by an ajax call, which will give you a response that you will use for updating your Morris donut.

So you could use your form for creating a ajax call. You have two options:

Using remote tags (out of the box on 1.x and 2.x grails versions, or with remote tags plugin on grails 3.x. Using a remote form, you could update a piece of your html code with the response from an action, which renders a template.

Implementing your own ajax method, recommended for a well code implementation, cause a remote ajax grails tag appends js code on your HTML. It is not good at all (a front-end dev will kill you and a kitty cat also :) ), and is deprecated.

This ajax request has to return you a new data model, could be in a JSON format and you can update your donut with the method js setData.

<g:form name="form" controller="blankTest">
    <input type="submit" value="Update"/>
</g:form>
<div id="myfirstchart" style="height: 250px;"></div>

<g:javascript id="test">
    //we will need this reference for updating it
    var donut = new Morris.Donut({
        // ID of the element in which to draw the chart.
        element: 'myfirstchart',

        label: 'Test',

        resize: true,

        colors : ['#00ff00', '#ff0000', '#ffff00'],

        data: [
            { label: 'Number1', value: ${number}},
            { label: 'Number2', value: ${number1}},
            { label: 'Number3', value: ${number2}}
        ],
    });

$(document).ready(function(){
   $('#form').submit(function(event){
       event.preventDefault(); //blocks native form submit

       $.ajax('${createLink(controller: 'blankTest', action: 'action')}', {
           success: function (data) {
               var response = $.parseJSON(data);
               donut.setData(response); //updating the donut with json response
           }
       });
   });

});
</g:javascript>

And your action should be something like this

def action() {
    number++
    List result = [
       [label: 'Number1', value: number],
       [label: 'Number2', value: number1],
       [label: 'Number3', value: number2]
    ]

    render result as JSON
}

For more complex JSON's consider use JSON views if you are using Grails greater than v.3.1


问:
Decomposing tuples in function arguments
In python I can do this:

def f((a, b)):
    return a + b

d = (1, 2)
f(d)
```

<p>Here the passed in tuple is being decomposed while its being passed to <code>f</code>.</p>

<p>Right now in scala I am doing this:</p>

<pre class="lang-scala prettyprint-override"><code>def f(ab: (Int, Int)): Int = {
    val (a, b) = ab
    a + b
}

val d = (1, 2)
f(d)
</code>```

Is there something I can do here so that the decomposition happens while the arguments are passed in? Just curious.

答:
```<code>object RandomExperiments extends App{
  def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
  takeTuple(1,3)
  takeTuple((1,3))
  takeTuple(((1,3)))

}
</code>```

prints:

```<code>(1,3) 1
(1,3) 1
(1,3) 1
</code>```

Body:
In python I can do this:

def f((a, b)):
    return a + b

d = (1, 2)
f(d)

Here the passed in tuple is being decomposed while its being passed to f.

Right now in scala I am doing this:

def f(ab: (Int, Int)): Int = {
    val (a, b) = ab
    a + b
}

val d = (1, 2)
f(d)

Is there something I can do here so that the decomposition happens while the arguments are passed in? Just curious.

Body:
object RandomExperiments extends App{
  def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
  takeTuple(1,3)
  takeTuple((1,3))
  takeTuple(((1,3)))

}

prints:

(1,3) 1
(1,3) 1
(1,3) 1


问:
Forms authentication: disable redirect to the login page
I have an application that uses ASP.NET Forms Authentication. For the most part, it's working great, but I'm trying to add support for a simple API via an .ashx file. I want the ashx file to have optional authentication (i.e. if you don't supply an Authentication header, then it just works anonymously). But, depending on what you do, I want to require authentication under certain conditions.

I thought it would be a simple matter of responding with status code 401 if the required authentication was not supplied, but it seems like the Forms Authentcation module is intercepting that and responding with a redirect to the login page instead. What I mean is, if my ProcessRequest method looks like this:

```<code>public void ProcessRequest(HttpContext context)
{
    Response.StatusCode = 401;
    Response.StatusDescription = "Authentication required";
}
</code>```

Then instead of getting a 401 error code on the client, like I expect, I'm actually getting a 302 redirect to the login page.

For nornal HTTP traffic, I can see how that would be useful, but for my API page, I want the 401 to go through unmodified so that the client-side caller can respond to it programmatically instead.

Is there any way to do that?

答:
I don't know how that Response.End() worked for you. I tried it with no joy, then looked at MSDN for Response.End(): 'stops execution of the page, and raises the EndRequest event'.

For what it's worth my hack was:

```<code>_response.StatusCode = 401;
_context.Items["401Override"] = true;
_response.End();
</code>```

Then in Global.cs add an EndRequest handler (which will get called after Authentication HTTPModule):

```<code>protected void Application_EndRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Items["401Override"] != null)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.StatusCode = 401;
    }
}
</code>```

Body:
I have an application that uses ASP.NET Forms Authentication. For the most part, it's working great, but I'm trying to add support for a simple API via an .ashx file. I want the ashx file to have optional authentication (i.e. if you don't supply an Authentication header, then it just works anonymously). But, depending on what you do, I want to require authentication under certain conditions.

I thought it would be a simple matter of responding with status code 401 if the required authentication was not supplied, but it seems like the Forms Authentcation module is intercepting that and responding with a redirect to the login page instead. What I mean is, if my ProcessRequest method looks like this:

public void ProcessRequest(HttpContext context)
{
    Response.StatusCode = 401;
    Response.StatusDescription = "Authentication required";
}

Then instead of getting a 401 error code on the client, like I expect, I'm actually getting a 302 redirect to the login page.

For nornal HTTP traffic, I can see how that would be useful, but for my API page, I want the 401 to go through unmodified so that the client-side caller can respond to it programmatically instead.

Is there any way to do that?

Body:
I don't know how that Response.End() worked for you. I tried it with no joy, then looked at MSDN for Response.End(): 'stops execution of the page, and raises the EndRequest event'.

For what it's worth my hack was:

_response.StatusCode = 401;
_context.Items["401Override"] = true;
_response.End();

Then in Global.cs add an EndRequest handler (which will get called after Authentication HTTPModule):

protected void Application_EndRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Items["401Override"] != null)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.StatusCode = 401;
    }
}


问:
Cannot compile code using an enum declared in a templated base class [C++]
The following code (included in a single header file) is simple demonstration of the problem I encounter:

```<code>template <class T>
class A
{
public:
    enum Type
    {
        ONE,
        TWO
    };

    A( Type tp = ONE ):tp(tp) {

    }

protected:
    Type tp;
};

template <class T>
class B : public A<T>
{

    B( Type _tp ):A<T>(_tp) {

    }

};
</code>```

This produces the compilation error (in Clang)

```<code>Untitled 2.cpp:24:4: error: unknown type name 'Type'
        B(Type _tp ):A<T>(_tp) {
          ^
1 error generated.
</code>```

If I instead move the enum outside the scope of A, or remove the templatization of A and B, then the above code compiles.

答:
If your enum is going to be that simple, it would probably be best to simply move it outside A<T>, as you already indicated worked -- you could keep it in a namespace if you'd like. Otherwise, the enum is inside the class A<T> and so inside B, Type in an incomplete name. Instead,

```<code>template <class T>
class B : public A<T>
{

    B( typename A<T>::Type _tp )
      : A<T>(_tp)
    {
    }

};
</code>```

The typename keyword is required because A is templated.

Body:
The following code (included in a single header file) is simple demonstration of the problem I encounter:

template <class T>
class A
{
public:
    enum Type
    {
        ONE,
        TWO
    };

    A( Type tp = ONE ):tp(tp) {

    }

protected:
    Type tp;
};

template <class T>
class B : public A<T>
{

    B( Type _tp ):A<T>(_tp) {

    }

};

This produces the compilation error (in Clang)

Untitled 2.cpp:24:4: error: unknown type name 'Type'
        B(Type _tp ):A<T>(_tp) {
          ^
1 error generated.

If I instead move the enum outside the scope of A, or remove the templatization of A and B, then the above code compiles.

Body:
If your enum is going to be that simple, it would probably be best to simply move it outside A<T>, as you already indicated worked -- you could keep it in a namespace if you'd like. Otherwise, the enum is inside the class A<T> and so inside B, Type in an incomplete name. Instead,

template <class T>
class B : public A<T>
{

    B( typename A<T>::Type _tp )
      : A<T>(_tp)
    {
    }

};

The typename keyword is required because A is templated.


问:
how to check if a string contains only lower case letters and numbers?
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

```<code>if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):
</code>```

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

答:
Define a function that applies your rules using sets for membership testing .

```<code>import string
lower = set(string.ascii_lowercase)
digits = set(string.digits)
def valid(s):
    '''Test string for valid characters, and composition'''

    s = set(s)
    invalid = s.difference(lower, digits)
    both = s.intersection(lower) and s.intersection(digits)
    return bool(both and not invalid)
</code>```

Usage:

```<code>>>> valid('12234')
False
>>> valid('abcde')
False
>>> valid('A123')
False
>>> valid('a$1')
False
>>> valid('1a')
True
>>>
</code>```

Body:
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

Body:
Define a function that applies your rules using sets for membership testing .

import string
lower = set(string.ascii_lowercase)
digits = set(string.digits)
def valid(s):
    '''Test string for valid characters, and composition'''

    s = set(s)
    invalid = s.difference(lower, digits)
    both = s.intersection(lower) and s.intersection(digits)
    return bool(both and not invalid)

Usage:

>>> valid('12234')
False
>>> valid('abcde')
False
>>> valid('A123')
False
>>> valid('a$1')
False
>>> valid('1a')
True
>>>


问:
why is my tab separation not working?
I am trying to tab separate three variables as follows:

```<code>single_element = str(pos) + "\t" + str(ref) + "\t" +str(alt)
</code>```

the output I get with print(single_element) is:

```<code>pos\tref\talt
</code>```

but what I would like is:

```<code>pos    ref    alt
</code>```

答:
You could use expandtabs to specify the tabstop

```<code>print(single_element.expandtabs(8))
</code>```

Title: why is my tab separation not working?

Body:
I am trying to tab separate three variables as follows:

single_element = str(pos) + "\t" + str(ref) + "\t" +str(alt)

the output I get with print(single_element) is:

pos\tref\talt

but what I would like is:

pos    ref    alt

Body:
You could use expandtabs to specify the tabstop

print(single_element.expandtabs(8))


问:
Generating multiplication questions in Java
The code should output a table for Farenheit and Celsius</p>

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.println();
</code>```

答:
Simplest way would be do while loop.  Example: </p>

```<code>do{
    // What you want to repeat and make sure to change have way to get out of loop like this:
    System.out.print("Want more questions yes or no? ");
    question = scanner.next();
}while(question.equals("yes") || question.equals("y"));
</code>```

Body:
The code should output a table for Farenheit and Celsius

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.println();

Body:
Simplest way would be do while loop.  Example:

do{
    // What you want to repeat and make sure to change have way to get out of loop like this:
    System.out.print("Want more questions yes or no? ");
    question = scanner.next();
}while(question.equals("yes") || question.equals("y"));


问:
JQuery - why does live work but click doesn't?
We have a page with this structure:

```<code><script type="text/javascript" src="/js/lots.of.javascript.js"></script>
<jsp:include page="html.jsp"/>
</code>```

The JavaScript has lots of $(function(){...} blocks.  In one block we tried a $("#mylink").click(...) but this did NOT work.  However the corresponding .live('click' DID work.  Why is this?

Update: More specifically I am assuming the click and live statements ARE running after the link has been added to the DOM as the link is included in the html.jsp file and the statements are executed in $(function(){...} blocks...  So given this I'm not sure why click wouldn't work...

答: It is probably that the element with id #mylink is created later and not at the time the DOM becomes ready.

Body:
We have a page with this structure:

<jsp:include page="html.jsp"/>

The JavaScript has lots of $(function(){...} blocks.  In one block we tried a $("#mylink").click(...) but this did NOT work.  However the corresponding .live('click' DID work.  Why is this?

Update: More specifically I am assuming the click and live statements ARE running after the link has been added to the DOM as the link is included in the html.jsp file and the statements are executed in $(function(){...} blocks...  So given this I'm not sure why click wouldn't work...


问:
Using snprintf to fill struct
can someone tell me why variables in struct are overwriting?

output is:

```<code>Buffor is: 1.name , struct is: 1.name
Buffor is: 2.name , struct is: 2.name
Buffor is: 3.name , struct is: 3.name
3.name
3.name
3.name
</code>```

```<code>    int i = 1;
    char buffor[100];
    int n = 3;

    struct person * data;
    data = (struct person *) malloc(n * sizeof(struct person));

    while (i <= n) {
        snprintf(buffor, sizeof(buffor), "%d.name", i);
        data[i - 1].firstname =buffor;
        printf("Buffor is: %s , struct is: %s \n", buffor, data[i - 1].firstname);
        i++;
    }

    for (int i = 0; i < n; i++) {
        printf("%s \n", data[i].firstname);
    }
    return 0;
}
</code>```

答:
You need to allocate memory for firstname property of every single struct. Copying strings will just copy the pointer. Instead of

```<code>data[i - 1].firstname = buffor;
</code>```

you need something like this:

```<code>data[i - 1].firstname = (char*)malloc(strlen(buffor) + 1);
strcpy(data[i - 1].firstname, buffor);
</code>```

Title: Using snprintf to fill struct

Body:
can someone tell me why variables in struct are overwriting?

output is:

Buffor is: 1.name , struct is: 1.name
Buffor is: 2.name , struct is: 2.name
Buffor is: 3.name , struct is: 3.name
3.name
3.name
3.name

    int i = 1;
    char buffor[100];
    int n = 3;

    struct person * data;
    data = (struct person *) malloc(n * sizeof(struct person));

    while (i <= n) {
        snprintf(buffor, sizeof(buffor), "%d.name", i);
        data[i - 1].firstname =buffor;
        printf("Buffor is: %s , struct is: %s \n", buffor, data[i - 1].firstname);
        i++;
    }

    for (int i = 0; i < n; i++) {
        printf("%s \n", data[i].firstname);
    }
    return 0;
}

Body:
You need to allocate memory for firstname property of every single struct. Copying strings will just copy the pointer. Instead of

data[i - 1].firstname = buffor;

you need something like this:

data[i - 1].firstname = (char*)malloc(strlen(buffor) + 1);
strcpy(data[i - 1].firstname, buffor);


问:
dinner cost calculator trouble converting string to integer
I'm using parseInt to convert .values from strings to numbers. However, if the user inputs a decimal value the output is NaN. Here is my code:

```<code>Dinner Cost:<input type="text" id="cost" /><br /><br />
Tax Rate:<input type="text" id="taxRate" /><br /><br />

<button id="btn">Determine Total Costs</button><br /><br />

<p id="para"></p>

document.getElementById("btn").addEventListener('click', totalCosts);

function totalCosts() {

  var dinnerCosts = document.getElementById("cost").value;
  var taxRate = document.getElementById("taxRate").value;
  taxRate = parseInt(taxRate);
  dinnerCosts = parseInt(dinnerCosts);

  var taxCost = dinnerCosts * taxRate;
  var totalCost = dinnerCosts + taxCost;

  return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}
</code>```

What am I doing wrong? Is there a more rational way to convert these default strings into numbers instead of parseInt?

Thanks!

答:
You can use the Number constructor directly without instantiating it to return a literal number. Alternatively you could use parseFloat

document.getElementById("btn").addEventListener('click', totalCosts);

function totalCosts() {

  var dinnerCosts = document.getElementById("cost").value;
  var taxRate = document.getElementById("taxRate").value;
  taxRate = Number(taxRate);
  dinnerCosts = Number(dinnerCosts);

  var taxCost = dinnerCosts * taxRate;
  var totalCost = dinnerCosts + taxCost;

  return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Dinner Cost:<input type="text" id="cost" /><br /><br />
Tax Rate:<input type="text" id="taxRate" /><br /><br />

<button id="btn">Determine Total Costs</button><br /><br />

<p id="para"></p></code>```

Body:
I'm using parseInt to convert .values from strings to numbers. However, if the user inputs a decimal value the output is NaN. Here is my code:

Dinner Cost:<input type="text" id="cost" />

Tax Rate:<input type="text" id="taxRate" />

<button id="btn">Determine Total Costs</button>

document.getElementById("btn").addEventListener('click', totalCosts);

function totalCosts() {

  var dinnerCosts = document.getElementById("cost").value;
  var taxRate = document.getElementById("taxRate").value;
  taxRate = parseInt(taxRate);
  dinnerCosts = parseInt(dinnerCosts);

  var taxCost = dinnerCosts * taxRate;
  var totalCost = dinnerCosts + taxCost;

  return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}

What am I doing wrong? Is there a more rational way to convert these default strings into numbers instead of parseInt?

Thanks!

Body:
You can use the Number constructor directly without instantiating it to return a literal number. Alternatively you could use parseFloat

document.getElementById("btn").addEventListener('click', totalCosts);

function totalCosts() {

  var dinnerCosts = document.getElementById("cost").value;
  var taxRate = document.getElementById("taxRate").value;
  taxRate = Number(taxRate);
  dinnerCosts = Number(dinnerCosts);

  var taxCost = dinnerCosts * taxRate;
  var totalCost = dinnerCosts + taxCost;

  return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}

Dinner Cost:<input type="text" id="cost" /><br /><br />
Tax Rate:<input type="text" id="taxRate" /><br /><br />

<button id="btn">Determine Total Costs</button><br /><br />

<p id="para"></p>


问:
How can I make page slide onto the screen when button is clicked?
I basically have a menu that slides onto the screen when you press a button. And on the menu I have a few buttons that currently don't do anything. What I want them to do is whenever a user clicks on a button I want the page to slide in from the bottom of the screen. I have tried to do this myself but for some reason it just closes the menu whenever I press one of the buttons.

Here is what I have so far.

//About Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#about").on('click', expand);

//Projects Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#projects").on('click', expand);

//Contact Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#contact").on('click', expand);

//Menu Transition
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: blue;
  z-index: 1000;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: black;
  z-index: 1000;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: white;
  z-index: 1000;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(60, 106, 152, 0.8);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #d66863;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

Title

 home

 about

 projects

 contact

```

答: make the width in .menu css 100% </p>

Body:
I basically have a menu that slides onto the screen when you press a button. And on the menu I have a few buttons that currently don't do anything. What I want them to do is whenever a user clicks on a button I want the page to slide in from the bottom of the screen. I have tried to do this myself but for some reason it just closes the menu whenever I press one of the buttons.

Here is what I have so far.

//About Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#about").on('click', expand);

//Projects Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#projects").on('click', expand);

//Contact Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#contact").on('click', expand);

//Menu Transition
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: blue;
  z-index: 1000;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: black;
  z-index: 1000;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: white;
  z-index: 1000;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(60, 106, 152, 0.8);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #d66863;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

Title

 home

 about

 projects

 contact

Body: make the width in .menu css 100%


问:
Is it possible to write good and understandable code without any comments?
Can any one suggest what is the best way to write good code that is understandable without a single line of comments?</p>

答:
I think code can be self-documenting to a large degree, and I think it's crucial, but reading even well-written code can be like looking at cells of the human body with a microscope.  It sometimes takes comments to really explain the big picture of how pieces of the system fit together, especially if it solves a really complex and difficult problem.

Think about special data structures.  If all that computer scientists had ever published about data structures were well-written code, few would really understand the relative benefit of one data structure over another -- because Big-O runtime of any given operation is sometimes just not obvious from reading the code.  That's where the math and amortized analysis presented in articles come in.


答:
You need to add a do while() loop to continue with the questions, for example:

```<code>static Scanner input;
static Scanner scanner;
static String question;

public static void main(String[] args) {
    do {
        int number1 = (int) (Math.random() * 10);
        int number2 = (int) (Math.random() * 10);
        input = new Scanner(System.in);
        System.out.print("What is " + number1 + " * " + number2 + "? ");
        int answer = input.nextInt();
        while ((number1 * number2) != answer) {
            System.out.print("Incorrect. Please try again. What is "
                    + number1 + " * " + number2 + "? ");
            answer = input.nextInt();
        }
        if ((number1 * number2) == answer) {
            System.out.println("Correct. Nice work!");
            System.out.println("Want more questions yes or no? ");
            scanner = new Scanner(System.in);
            question = scanner.next();
        }
    } while (question.toLowerCase().equals("yes") ||
            question.toLowerCase().equals("y"));
}
</code>```

Title: Generating multiplication questions in Java

Body:
You need to add a do while() loop to continue with the questions, for example:

static Scanner input;
static Scanner scanner;
static String question;

public static void main(String[] args) {
    do {
        int number1 = (int) (Math.random() * 10);
        int number2 = (int) (Math.random() * 10);
        input = new Scanner(System.in);
        System.out.print("What is " + number1 + " * " + number2 + "? ");
        int answer = input.nextInt();
        while ((number1 * number2) != answer) {
            System.out.print("Incorrect. Please try again. What is "
                    + number1 + " * " + number2 + "? ");
            answer = input.nextInt();
        }
        if ((number1 * number2) == answer) {
            System.out.println("Correct. Nice work!");
            System.out.println("Want more questions yes or no? ");
            scanner = new Scanner(System.in);
            question = scanner.next();
        }
    } while (question.toLowerCase().equals("yes") ||
            question.toLowerCase().equals("y"));
}


问:
How to extract portion of a line in ruby?
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

```<code>line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end
</code>```

... but is there any other way of doing this?

答:
This is a way to extract, from an arbitrary string, a substring that represents a time in the given format. I've assumed there is at most one such substring in the string.

```<code>require 'time'

R = /
    (?:#{Date::ABBR_DAYNAMES.join('|')})\s
              # match day name abbreviation in non-capture group. space
    (?:#{Date::MONTHNAMES[1,12].join('|')})\s
              # match month name in non-capture group, space
    \d{1,2}\s # match one or two digits, space
    \d{2}:    # match two digits, colon
    \d{2}:    # match two digits, colon
    \d{2}\s   # match two digits, space
    \d{4}     # match 4 digits
    (?!\d)    # do not match digit (negative lookahead)
    /x        # free-spacing regex def mode
  # /
  #  (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s
  #   (?:January|February|March|...|November|December)\s
  # \d{1,2}\s
  # \d{2}:
  # \d{2}:
  # \d{2}\s
  # \d{4}
  # (?!\d)
  # /x
</code>```

```<code>def extract_time(str)
  s = str[R]
  return nil if s.nil?
  (DateTime.strptime(s, "%a %B %e %H:%M:%S %Y") rescue nil) ? s : nil
end

str = "start eating breakfast at Sat April 1 07:30:37 2017"
extract_time(str)
  #=> "Sat April 1 07:30:37 2017"

str = "go back to sleep at Cat April 1 07:30:37 2017"
extract_time(str)
  #=> nil
</code>```

Alternatively, if there is a match against R, but Time#strptime raises an exception (meaning s is not a valid time for the given time format) one could raise an exception to advise the user.

Body:
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

Body:
This is a way to extract, from an arbitrary string, a substring that represents a time in the given format. I've assumed there is at most one such substring in the string.

require 'time'

R = /
    (?:#{Date::ABBR_DAYNAMES.join('|')})\s
              # match day name abbreviation in non-capture group. space
    (?:#{Date::MONTHNAMES[1,12].join('|')})\s
              # match month name in non-capture group, space
    \d{1,2}\s # match one or two digits, space
    \d{2}:    # match two digits, colon
    \d{2}:    # match two digits, colon
    \d{2}\s   # match two digits, space
    \d{4}     # match 4 digits
    (?!\d)    # do not match digit (negative lookahead)
    /x        # free-spacing regex def mode
  # /
  #  (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s
  #   (?:January|February|March|...|November|December)\s
  # \d{1,2}\s
  # \d{2}:
  # \d{2}:
  # \d{2}\s
  # \d{4}
  # (?!\d)
  # /x

def extract_time(str)
  s = str[R]
  return nil if s.nil?
  (DateTime.strptime(s, "%a %B %e %H:%M:%S %Y") rescue nil) ? s : nil
end

str = "start eating breakfast at Sat April 1 07:30:37 2017"
extract_time(str)
  #=> "Sat April 1 07:30:37 2017"

str = "go back to sleep at Cat April 1 07:30:37 2017"
extract_time(str)
  #=> nil

Alternatively, if there is a match against R, but Time#strptime raises an exception (meaning s is not a valid time for the given time format) one could raise an exception to advise the user.


问:
Subst in a list
I will give an example to explain my problem: I have a list in the form list1:[x*y*z,x*z,y]. Now I have another list, list2:[1,2,3]. What I'm trying to do is substitute the value list2[1], i.e. 1, into the x variable of my list1, the value list2[2] into the y variable of my list1, and so on. The output should be   [1*2*3,1*3,2] or [6,3,2]. Note that both lists have the same length.

What I tried to do is:

```<code>list3:for i:1 thru length(list2) do (subst(list2[i],list1[i])
</code>```

But it didn't work. How can I do this?

Thanks in advance,

Best regards.

Title: Subst in a list

Body:
I will give an example to explain my problem: I have a list in the form list1:[x*y*z,x*z,y]. Now I have another list, list2:[1,2,3]. What I'm trying to do is substitute the value list2[1], i.e. 1, into the x variable of my list1, the value list2[2] into the y variable of my list1, and so on. The output should be   [1*2*3,1*3,2] or [6,3,2]. Note that both lists have the same length.

What I tried to do is:

list3:for i:1 thru length(list2) do (subst(list2[i],list1[i])

But it didn't work. How can I do this?

Thanks in advance,

Best regards.

Body:
(%i1) list1: [x*y*z,x*z,y] $
(%i2) kk: ['x, 'y, 'z] $
(%i3) vv: [ 1,  2,  3] $
(%i4) sl: maplist(lambda([k, v], k = v), kk, vv) $
(%i5) subst(sl, list1);
(%o5)                              [6, 3, 2]


问:
Advice on using unless requisite in a salt state file
As part of a salt state file I am installing nghttp2.

So far I have the following code in my .sls

```<code>install_nghttp2:
  cmd.run:
    - name: |
        cd /tmp
        wget https://github.com/nghttp2/nghttp2/releases/download/v1.16.0/nghttp2-1.16.0.tar.gz
        tar -xf nghttp2-1.16.0.tar.gz
        cd ./nghttp2-1.16.0
        ./configure
        make
        make install
    - shell: /bin/bash
    - require:
      - pkg: install_nghttp2_deps
    - unless: test -x /tmp/nghttp2-1.16.0
</code>```

I'm a little wary of the - unless requisite and was wondering if anyone had a better way to check nghttp2 hasn't already been installed? I'd rather do something to check it hasn't been installed rather than just check whether it's been downloaded - unless (pun intended...kinda) anyone has a better suggestion?

答:
Since you compile specific version and you do not install it with package manager, I think you are doing it right.

Maybe better option to check if the program is installed would be to use different command in unless requisite.

For example you can use nghttpd --version or with full path, where the binary is stored /usr/sbin/nghttpd --version.

Other good option is to use which nghttpd.

Body:
As part of a salt state file I am installing nghttp2.

So far I have the following code in my .sls

install_nghttp2:
  cmd.run:
    - name: |
        cd /tmp
        wget https://github.com/nghttp2/nghttp2/releases/download/v1.16.0/nghttp2-1.16.0.tar.gz
        tar -xf nghttp2-1.16.0.tar.gz
        cd ./nghttp2-1.16.0
        ./configure
        make
        make install
    - shell: /bin/bash
    - require:
      - pkg: install_nghttp2_deps
    - unless: test -x /tmp/nghttp2-1.16.0

I'm a little wary of the - unless requisite and was wondering if anyone had a better way to check nghttp2 hasn't already been installed? I'd rather do something to check it hasn't been installed rather than just check whether it's been downloaded - unless (pun intended...kinda) anyone has a better suggestion?


问:
Cannot read property 'handleClick' of undefined when using map
I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

```<code>handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });
...
</code>```

答:
Use arrow function as map callback to preserve component context (otherwise this inside the callback will not point to the component instance):

```<code>render(){
   var userNodes = this.props.posts.map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });
</code>```

Body:
I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (

 this.handleClick(user)}>
           {user.postId}
           {user.title}
           {user.body}

       )
   });
...

Body:
Use arrow function as map callback to preserve component context (otherwise this inside the callback will not point to the component instance):

render(){
   var userNodes = this.props.posts.map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });