问:
Change strings with different format to dates with the same format in a dataframe
I have a dataframe which looks like this (it has thounds of date rows like this, ranging from years 18xx until 2019)

```<code>                date
1   25 February 1987
2     20 August 1974
3     9 October 1984
4          16-Oct-63
5         13-11-1961
6           03/23/87
7         01.01.1995
8      February 1988
9               1988
10 20050101-20051231
</code>```

I need to change the date column to one date-format (eg.: YYYY-MM-DD, or any other).
Since there are just some Year values as for ID 9, I also have to autofill them. This should always lead to the last day of the particular year. If it ist like ID 8 a month and a year, it should always fill the last day of the particular month (and check if it was a leap year, like it was in 1988 and return in this case something like 1988-02-29). If it is a timeframe like in the last row, it should always cut off the first part and change it to the 31st of December of the given year.
How can I do this?

I thought about using the lubridate package or the anytime package. With lubridate and parse_date or parse_date_time. This even works, but it always fills the missing values for days to the first day of a month and not the last.

```<code>library(lubridate)

date <- c("25 February 1987", "20 August 1974", "9 October 1984", "16-Oct-63", "13-11-1961", "03/23/87", "01.01.1995",
          "February 1988", "1988", "20050101-20051231")

df <- as.data.frame(date)

parse_date(df$date)

parse_date_time(x = df$date,
                orders = c("d m y", "d B Y", "d/m/Y","B Y", "Y", "m/d/y",
                           "Ymd-Ymd"),
                locale = "eng")
</code>```

My actual results

```<code>(parse_date(df$date)):

 [1] "1987-02-25 UTC" "1974-08-20 UTC" "1984-10-09 UTC" "2019-10-16 UTC" "2019-11-13 UTC" "1987-03-23 UTC" "1995-01-01 UTC"
 [8] "1988-02-01 UTC" "1988-01-01 UTC" "2005-12-31 UTC"
</code>```

For the parse_date_time I acutally get an error, due to the last orders "Ymd-Ymd" (If I just test: parse_date("20050101-20051231") it results in "2005-12-31 UTC", which I really want to have!)

答:
Using lubridate cheat sheet (https://evoldyn.gitlab.io/evomics-2018/ref-sheets/R_lubridate.pdf)
and by trial and error with dplyr :</p>

```<code>df %>%
        mutate(newdate = parse_date_time(x = date, orders = c("dmy", "mdy", "my", "y")) ) %>%
        mutate(newdate2 = case_when(
                        newdate > today() ~ newdate - 100*365.25*24*3600,
                        is.na(newdate) ~ paste0(substr(x=date, start = 1, stop = 4), "-",
                                                substr(x=date, start = 5, stop = 6), "-",
                                                substr(x=date, start = 7, stop = 8) )
                        %>%
                                parse_date_time(., orders = c("dmy", "mdy", "my", "y", "ymd")),
                        TRUE ~ newdate
        )
        )
</code>```

Body:
I have a dataframe which looks like this (it has thounds of date rows like this, ranging from years 18xx until 2019)

                date
1   25 February 1987
2     20 August 1974
3     9 October 1984
4          16-Oct-63
5         13-11-1961
6           03/23/87
7         01.01.1995
8      February 1988
9               1988
10 20050101-20051231

I need to change the date column to one date-format (eg.: YYYY-MM-DD, or any other).
Since there are just some Year values as for ID 9, I also have to autofill them. This should always lead to the last day of the particular year. If it ist like ID 8 a month and a year, it should always fill the last day of the particular month (and check if it was a leap year, like it was in 1988 and return in this case something like 1988-02-29). If it is a timeframe like in the last row, it should always cut off the first part and change it to the 31st of December of the given year.
How can I do this?

I thought about using the lubridate package or the anytime package. With lubridate and parse_date or parse_date_time. This even works, but it always fills the missing values for days to the first day of a month and not the last.

library(lubridate)

date <- c("25 February 1987", "20 August 1974", "9 October 1984", "16-Oct-63", "13-11-1961", "03/23/87", "01.01.1995",
          "February 1988", "1988", "20050101-20051231")

df <- as.data.frame(date)

parse_date(df$date)

parse_date_time(x = df$date,
                orders = c("d m y", "d B Y", "d/m/Y","B Y", "Y", "m/d/y",
                           "Ymd-Ymd"),
                locale = "eng")

My actual results

(parse_date(df$date)):

 [1] "1987-02-25 UTC" "1974-08-20 UTC" "1984-10-09 UTC" "2019-10-16 UTC" "2019-11-13 UTC" "1987-03-23 UTC" "1995-01-01 UTC"
 [8] "1988-02-01 UTC" "1988-01-01 UTC" "2005-12-31 UTC"

For the parse_date_time I acutally get an error, due to the last orders "Ymd-Ymd" (If I just test: parse_date("20050101-20051231") it results in "2005-12-31 UTC", which I really want to have!)

Body:
Using lubridate cheat sheet (https://evoldyn.gitlab.io/evomics-2018/ref-sheets/R_lubridate.pdf)
and by trial and error with dplyr :

df %>%
        mutate(newdate = parse_date_time(x = date, orders = c("dmy", "mdy", "my", "y")) ) %>%
        mutate(newdate2 = case_when(
                        newdate > today() ~ newdate - 100*365.25*24*3600,
                        is.na(newdate) ~ paste0(substr(x=date, start = 1, stop = 4), "-",
                                                substr(x=date, start = 5, stop = 6), "-",
                                                substr(x=date, start = 7, stop = 8) )
                        %>%
                                parse_date_time(., orders = c("dmy", "mdy", "my", "y", "ymd")),
                        TRUE ~ newdate
        )
        )


来源: stackexchange

问:
Can use openssl instead of Python RSA and Base64 algorithms?
Can use the openssl command to implement equivalent functionality with Python RSA and Base64 algorithms?

For example, the RSA public key and the password to be encrypted are known. The Python algorithm is

```<code>ciphertext = base64.b64encode(PKCS1_v1_5.new(pubkey).encrypt(password.encode('utf-8')))
</code>```

Suppose the password is 123456 and the public key is pubkey.pem. Is the following openssl command equivalent to the Python algorithm?

```<code>echo 123456 | openssl rsautl -encrypt -pubin -inkey pubkey.pem -out ciphertext.txt | openssl enc -e -base64 -in ciphertext.txt -out r.txt
</code>```

The result of r.txt is equivalent to the ciphertext of the Python algorithm?

答:
Yes, it should be, well, if and only if your password is "123456" of course.

The randomization that the PKCS#1 v1.5 padding performs will mean that the ciphertext is always different, of course.

To test: decrypt the ciphertext using the reverse operations and the private key in Python. For more certainty, decrypt using openssl as well.

ContentLicense: CC BY-SA 4.0

Body:
Can use the openssl command to implement equivalent functionality with Python RSA and Base64 algorithms?

For example, the RSA public key and the password to be encrypted are known. The Python algorithm is

ciphertext = base64.b64encode(PKCS1_v1_5.new(pubkey).encrypt(password.encode('utf-8')))

Suppose the password is 123456 and the public key is pubkey.pem. Is the following openssl command equivalent to the Python algorithm?

echo 123456 | openssl rsautl -encrypt -pubin -inkey pubkey.pem -out ciphertext.txt | openssl enc -e -base64 -in ciphertext.txt -out r.txt

The result of r.txt is equivalent to the ciphertext of the Python algorithm?


问:
Validating if variable is int
I have a script to create vlan in cisco switches, and I need the user to input a number to the script.

I'm having trouble to make the script validate if the input is a number(must be int) and if the number is inside the range 2~4094, before it moves to the next steps.

I already wrote the rest of the script.

答:
This should work:

```<code>def validate(num):
    try:
        n = int(num)
        return 2 <= n <= 4094
    except:
        return False
</code>```

The above function returns True if the number is an integer in the specified range, False otherwise.

Title: Validating if variable is int

Body:
This should work:

def validate(num):
    try:
        n = int(num)
        return 2 <= n <= 4094
    except:
        return False

The above function returns True if the number is an integer in the specified range, False otherwise.


问:
jquery toggle not working in chrome but working in IE and firefox
Hi Guys
I have a page where i m displaying text in a span and that span control toggles on click of a button, basically i m using jquery for this. Its working fine on IE and firefox but on chrome when i click on the close button(which is there in the span to toggle it) it does not work for the first time i click on it but works after first click.

please advice, code is below

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Assets/JS/jquery.js"></script>
    <script language="javascript">
        $.showmsg = function (msgEle, msgText, autoHide, isSuccess) {
            var tblMsg;
            var imgType;
            if (isSuccess) {
                imgType = "<img src='Assets/Images/icon_status_success_26x26.gif'/>"
            } else {
                imgType = "<img src='Assets/Images/icon_status_fail_26x26.gif'/>"
            }

            tblMsg = '<div id="container" style="width: 400px;"><b class="rtop"><b class="r1"></b><b class="r2"></b><b class="r3"></b><b class="r4"></b></b><div class="contain"><table width="100%" cellpadding="0" cellspacing="0" border="0" class=""><tr><td style="width:30px;" align="center" valign="middle">' + imgType + '</td><td>' + msgText + '</td><td style="width:30px;" align="center" valign="middle"><a href="javascript:void(0);"  onclick="$(\'#' + msgEle + '\').toggle(50);"><img src="Assets/Images/hide-icon.gif" border="0" alt="Hide" title="Hide"/></a></td></tr></table></div><b class="rbottom"><b class="r4"></b><b class="r3"></b><b class="r2"></b><b class="r1"></b></b></div>';
            $("#" + msgEle).html(tblMsg);
            $("#" + msgEle).show();
            if (autoHide) {
                setTimeout(function () { $('#' + msgEle).fadeOut('normal') }, 10000);
            }
        }

        function Delete1() {
            $.showmsg('spnMessage', "Deleted", false, true);
        }

    </script>
    <style type="text/css">
        .rtop, .rbottom
        {
            display: block;
        }
        .rtop *, .rbottom *
        {
            display: block;
            height: 1px;
            overflow: hidden;
        }
        .r1
        {
            margin: 0 5px;
            background: yellow;
        }
        .r2
        {
            margin: 0 3px;
            background: yellow;
        }
        .r3
        {
            margin: 0 2px;
            background: yellow;
        }
        .r4
        {
            margin: 0 1px;
            height: 2px;
            background: yellow;
        }
        .contain
        {
            background: yellow;
            text-align: left;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <br />
    <br />
    <br />
    <table>
        <tr>
            <td>
                <asp:Button ID="btnDelete" runat="server" Text="Delete"  OnClientClick="Delete1(); return false;" />
            </td>
            <td>
                <span id="spnMessage" style="display: none;"></span>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
</code>```

答: Check this thread jQuery .toggle() not working with TRs in IE</p>

ContentLicense: CC BY-SA 3.0

Body:
Hi Guys
I have a page where i m displaying text in a span and that span control toggles on click of a button, basically i m using jquery for this. Its working fine on IE and firefox but on chrome when i click on the close button(which is there in the span to toggle it) it does not work for the first time i click on it but works after first click.

please advice, code is below

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

                <asp:Button ID="btnDelete" runat="server" Text="Delete"  OnClientClick="Delete1(); return false;" />

    </form>


问:
Using Scheme to calculate Newton-Raphson's
According to Newton-Raphson's:

Xn+1 = Xn - f(Xn) / f'(Xn)

```<code>(newtonRhap x f fx)

(newtonRhap 0.1 sin cos) => 0

(newtonRhap 2.0
            (lambda (x) (- (* x x) x 6))             ; f
            (lambda (x) (- (* 2 x) 1  )) ) => 3      ; f'
</code>```

How can I implement this function?

The routine will stop iteration when the change in solution is less than pre-set  tolerance.

I use a global variable for it, (define TOL 1e-6):

```<code>#lang racket
(define TOL 1e-6)
(define (func f x) (f x))
(define (f x) (- (* x x) x 6))
(define (fx x) (- (* 2 x) 1))
(define x 2.0)
(define (newtonRhap x ff ffx)
    ( (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx)
      (list x) ) )

(display (newtonRhap x (f x) (fx x)) )
</code>```

答:
First, you're missing an if there:

```<code>(define (newtonRhap x ff ffx)
    ( <b>if</b> (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx)
      (list x) ) )</code>```

Without it you would be calling the result of the Boolean test as a function with the following two forms values as arguments (it could work in a lazy functional language with Church-encoded conditionals, but that's besides the point, and Scheme / Racket is not lazy).

Second, and even more crucially, the last two arguments to newtonRhap are functions, but you're treating them as if they were numeric values. Correcting this gives us

```<code>(define (nl x)     ; for debugging insight;
   (newline)       ; for production redefine it as
   (display x)     ;    (define (nl x) x)
   x)

(define (newtonRhap x ff ffx)
  (let ((new-x (nl (- x (/ (ff x) (ffx x))))))  ; Follow The Formula
    ( if (> (abs (- x new-x)) TOL)             ; use abs
      (newtonRhap new-x ff ffx)          ; make next step
      (list new-x) ) ) )        ; return the new x, it's closer to the true result
</code>```

Now we can run

```<code>(display (newtonRhap x f fx))

3.333333333333333
3.019607843137255
3.0000762951094835
3.000000001164153
3.0(3.0)
>
</code>```

Body:
According to Newton-Raphson's:

Xn+1 = Xn - f(Xn) / f'(Xn)

(newtonRhap x f fx)

(newtonRhap 0.1 sin cos) => 0

(newtonRhap 2.0
            (lambda (x) (- (* x x) x 6))             ; f
            (lambda (x) (- (* 2 x) 1  )) ) => 3      ; f'

How can I implement this function?

The routine will stop iteration when the change in solution is less than pre-set  tolerance.

I use a global variable for it, (define TOL 1e-6):

#lang racket
(define TOL 1e-6)
(define (func f x) (f x))
(define (f x) (- (* x x) x 6))
(define (fx x) (- (* 2 x) 1))
(define x 2.0)
(define (newtonRhap x ff ffx)
    ( (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx)
      (list x) ) )

(display (newtonRhap x (f x) (fx x)) )

Body:
First, you're missing an if there:

(define (newtonRhap x ff ffx)
    ( if (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx)
      (list x) ) )

Without it you would be calling the result of the Boolean test as a function with the following two forms values as arguments (it could work in a lazy functional language with Church-encoded conditionals, but that's besides the point, and Scheme / Racket is not lazy).

Second, and even more crucially, the last two arguments to newtonRhap are functions, but you're treating them as if they were numeric values. Correcting this gives us

(define (nl x)     ; for debugging insight;
   (newline)       ; for production redefine it as
   (display x)     ;    (define (nl x) x)
   x)

(define (newtonRhap x ff ffx)
  (let ((new-x (nl (- x (/ (ff x) (ffx x))))))  ; Follow The Formula
    ( if (> (abs (- x new-x)) TOL)             ; use abs
      (newtonRhap new-x ff ffx)          ; make next step
      (list new-x) ) ) )        ; return the new x, it's closer to the true result

Now we can run

(display (newtonRhap x f fx))

3.333333333333333
3.019607843137255
3.0000762951094835
3.000000001164153
3.0(3.0)
>


问:
My code works fine inside the python shell, but not showing anything when running it on my Visual studio code
The code works inside Python shell, but not inside VS Code terminal.
    Can anyone please help me, I am about to go nuts.

```<code>I have tested my code on several ide and it works fine, just on VS

board = ["  " for i in range(9)]

def print_board():
    row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
    row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
    row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])

    print(row1)
    print(row2)
    print(row3)
    print()

def player_move(icon):

    if icon == "X":
        number = 1
    elif icon == "O":
        number = 2

    print("Your turn player {}".format(number))

    choice = int(input("Enter your move (1-9): ").strip())
    if board[choice - 1] == "  ":
        board[choice - 1] = icon
    else:
        print()
        print("That space is taken!")
</code>```

I need to see the board that I have created, it simply does not show anything inside VS code

It simply does not show anything inside the terminal and I don't get any errors.

答:
while you define your print statements in print_board() you never actually call it.

Just add

```<code>print_board()
</code>```

to the end and wherever appropriate.

so your code might look something like:

```<code>import numpy as np

board = [" " for i in range(9)]
icons = {1:"X", 2:"O"}

def print_board(remove=0):
    if remove > 0:
        print('\x1b[1A\x1b[2K'*remove)
    boardString = "| {} | {} | {} |\n"*3
    print(boardString.format(*board))

def player_move(_turn):
    player = np.mod(_turn,2)+1
    print("Your turn player {}".format(player))

    while True:
        choice = int(input("Enter your move (1-9): "))
        if board[choice - 1] == " ":
            board[choice - 1] = icons[player]
            break
        else:
            print('\x1b[1A\x1b[2K'*3)
            print("That space is taken!")

    print_board(7)

print_board()
for turn in range(9):
    player_move(turn)

</code>```

| X | O | X |
| O |   |   |
|   |   |   |

Your turn player 1
Enter your move (1-9):
```
<p>some notes:</p>
<ul>
<li>As shown above, you can replaces the last print of the board and command prompt by utilising VT100 codes for going up a line (<code>\x1b[1A</code>) and removing a line (<code>\x1b[2K</code>) before printing anew</li>
<li>strings can be multiplied (repeated) like lists</li>
</ul>
```In [1]: print('a'*3)
> aaa
```
<ul>
<li>you can add <code>\n</code> for a line break to strings instead of calling <code>print()</code> multiple times</li>
</ul>
```In [25]: print('a\nb')
> a
> b
```
<ul>
<li>you can unpack iterable variables (lists, tuples..) by using <code>*</code> or <code>**</code></li>
</ul>
<pre class="lang-py prettyprint-override"><code>yourDict = {'a':3, 'b':4}
yourList = [1, 2]

yourFun(*yourList, **yourDict )
# is equvivalent to:
yourFun(1, 2, a=3, b=4 )

</code>```

Body:
The code works inside Python shell, but not inside VS Code terminal.
    Can anyone please help me, I am about to go nuts.

I have tested my code on several ide and it works fine, just on VS

board = ["  " for i in range(9)]

def print_board():
    row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
    row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
    row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])

    print(row1)
    print(row2)
    print(row3)
    print()

def player_move(icon):

    if icon == "X":
        number = 1
    elif icon == "O":
        number = 2

    print("Your turn player {}".format(number))

    choice = int(input("Enter your move (1-9): ").strip())
    if board[choice - 1] == "  ":
        board[choice - 1] = icon
    else:
        print()
        print("That space is taken!")

I need to see the board that I have created, it simply does not show anything inside VS code

It simply does not show anything inside the terminal and I don't get any errors.

Body:
while you define your print statements in print_board() you never actually call it.

Just add

print_board()

to the end and wherever appropriate.

so your code might look something like:

import numpy as np

board = [" " for i in range(9)]
icons = {1:"X", 2:"O"}

def print_board(remove=0):
    if remove > 0:
        print('\x1b[1A\x1b[2K'*remove)
    boardString = "| {} | {} | {} |\n"*3
    print(boardString.format(*board))

def player_move(_turn):
    player = np.mod(_turn,2)+1
    print("Your turn player {}".format(player))

    while True:
        choice = int(input("Enter your move (1-9): "))
        if board[choice - 1] == " ":
            board[choice - 1] = icons[player]
            break
        else:
            print('\x1b[1A\x1b[2K'*3)
            print("That space is taken!")

    print_board(7)

print_board()
for turn in range(9):
    player_move(turn)

| X | O | X |
| O |   |   |
|   |   |   |

Your turn player 1
Enter your move (1-9):

some notes:

As shown above, you can replaces the last print of the board and command prompt by utilising VT100 codes for going up a line (\x1b[1A) and removing a line (\x1b[2K) before printing anew

strings can be multiplied (repeated) like lists

In [1]: print('a'*3)
> aaa

you can add \n for a line break to strings instead of calling print() multiple times

In [25]: print('a\nb')
> a
> b

you can unpack iterable variables (lists, tuples..) by using * or **

yourDict = {'a':3, 'b':4}
yourList = [1, 2]

yourFun(*yourList, **yourDict )
# is equvivalent to:
yourFun(1, 2, a=3, b=4 )


问:
What are the benefits of using a sigmoid function?
I am dipping my toe into neural networks and starting with some basic perceptrons. In one video, this guy is explaining how to make a machine that can 'learn' how to distinguish two arrays. He explains the training process, but just shoves all of his inputs and weights into the sigmoid function. I did some research on the sigmoid function and was wondering why it is used in machine learning and why programmers use it to test their inputs.</p>

答:
Sigmoid is one of the possible activation functions. The purpose of an activation function is to squeeze all possible values of whatever magnitude into the same range.

Here's a good article - https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6


问:
PHP Function pt_register
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

```<code>function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

Can anyone walk through this in English for me?

答:
Basically this is a function to take variables out of the predefined global arrays $_SESSION, $_GET, $_POST, $_SERVER, $_COOKIE, and $_ENV and move them into global variables with equivalent names.

For example, if you loaded the page "test.php?value=5" you would normally access that through $_GET['value']. However, you can call:

```<code>pt_register('GET', 'value');
</code>```

And this will create a global variable named $value set to 5. It accepts any number of arguments from the same global array, so for a page "test.php?value=5&another_value=6&yet_another_value=7" you could do:

```<code>pt_register('GET', 'value', 'another_value', 'yet_another_value');
</code>```

To have $value, $another_value, and $yet_another_value all created and assigned to the values they were given in the URL.

As RoBorg said, it's doing a similar job to the old register_globals, but it gives you a little more control over which variables are set.

OwnerDisplayName: HaArD

ContentLicense: CC BY-SA 2.5

Title: PHP Function pt_register

Body:
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}

Can anyone walk through this in English for me?

LastEditorDisplayName: RoBorg

Body:
Basically this is a function to take variables out of the predefined global arrays $_SESSION, $_GET, $_POST, $_SERVER, $_COOKIE, and $_ENV and move them into global variables with equivalent names.

For example, if you loaded the page "test.php?value=5" you would normally access that through $_GET['value']. However, you can call:

pt_register('GET', 'value');

And this will create a global variable named $value set to 5. It accepts any number of arguments from the same global array, so for a page "test.php?value=5&another_value=6&yet_another_value=7" you could do:

pt_register('GET', 'value', 'another_value', 'yet_another_value');

To have $value, $another_value, and $yet_another_value all created and assigned to the values they were given in the URL.

As RoBorg said, it's doing a similar job to the old register_globals, but it gives you a little more control over which variables are set.

OwnerDisplayName: Chad Birch


问:
I want to compare two time values in the format of HR:MIN:SEC. of the type string in c#?
Following is a code that a did in comparison between dates. Is it possible to use that code for strings also. OR Is there any sol?</p>

```<code>        protected void Button1_Click(object sender, EventArgs e)
        {
            int uid = Convert.ToInt32(dlFaculty.SelectedValue);
            string starttime = Convert.ToString((Convert.ToInt32(dlHour.SelectedItem.Text)) + ":" + (Convert.ToInt32(dlMinute.SelectedItem.Text)) + " " + dlAMPM.SelectedItem.Text);
            string endtime = Convert.ToString((Convert.ToInt32(dlHour1.SelectedItem.Text)) + ":" + (Convert.ToInt32(dlMinute1.SelectedItem.Text)) + " " + dlAMPM1.SelectedItem.Text);
            DateTime startdate = Convert.ToDateTime(txtStartDate.Text);
            DateTime enddate = Convert.ToDateTime(txtEndDate.Text);
            DataTable oTable = new DataTable();
            Boolean flag = true;

            string SQL = "select startdate,enddate from BatchMaster where usermasterid=" + uid + " AND starttime='" + starttime + "' AND endtime='" + endtime + "'";

            oTable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL, null);
            //coursemasterid = 0;
            //string s = subjectsid;

            if (oTable.Rows.Count > 0)
            {
                DataRow dr = oTable.Rows[0];
                if ((Convert.ToDateTime(dr["startdate"]) <= startdate && Convert.ToDateTime(dr["enddate"]) >= startdate) || (Convert.ToDateTime(dr["startdate"]) <= enddate && Convert.ToDateTime(dr["enddate"]) >= enddate))
                {
                    //lblavailability.Visible = true;
                    flag = false;
                    // lblavailability.Text = "Not Available.";
                }

                lblavailability.Visible = true;

                if (flag == true)
                {
                    lblavailability.CssClass = "textgreen";
                    lblavailability.Text = "Available.";
                }
                else
                {
                    lblavailability.CssClass = "errorbold";
                    lblavailability.Text = "Not Available.";
                }
            }
            else
            {
                lblavailability.CssClass = "textgreen";
                lblavailability.Visible = true;
                lblavailability.Text = "Available.";
            }

        }
</code>```

答:
You're essentially talking about the behaviour of

Convert.ToDateTime("23:00:10")

As per MSDN "It completes missing month, day, and year information with the current date.", so if you make sure that your time is always in HH and not hh format (that it uses 24h convention), you should be able to use a similar approach to the one above.

That is if you're sure that your code will not span midnight... :)

Body:
Following is a code that a did in comparison between dates. Is it possible to use that code for strings also. OR Is there any sol?

        protected void Button1_Click(object sender, EventArgs e)
        {
            int uid = Convert.ToInt32(dlFaculty.SelectedValue);
            string starttime = Convert.ToString((Convert.ToInt32(dlHour.SelectedItem.Text)) + ":" + (Convert.ToInt32(dlMinute.SelectedItem.Text)) + " " + dlAMPM.SelectedItem.Text);
            string endtime = Convert.ToString((Convert.ToInt32(dlHour1.SelectedItem.Text)) + ":" + (Convert.ToInt32(dlMinute1.SelectedItem.Text)) + " " + dlAMPM1.SelectedItem.Text);
            DateTime startdate = Convert.ToDateTime(txtStartDate.Text);
            DateTime enddate = Convert.ToDateTime(txtEndDate.Text);
            DataTable oTable = new DataTable();
            Boolean flag = true;

            string SQL = "select startdate,enddate from BatchMaster where usermasterid=" + uid + " AND starttime='" + starttime + "' AND endtime='" + endtime + "'";

            oTable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL, null);
            //coursemasterid = 0;
            //string s = subjectsid;

            if (oTable.Rows.Count > 0)
            {
                DataRow dr = oTable.Rows[0];
                if ((Convert.ToDateTime(dr["startdate"]) <= startdate && Convert.ToDateTime(dr["enddate"]) >= startdate) || (Convert.ToDateTime(dr["startdate"]) <= enddate && Convert.ToDateTime(dr["enddate"]) >= enddate))
                {
                    //lblavailability.Visible = true;
                    flag = false;
                    // lblavailability.Text = "Not Available.";
                }

                lblavailability.Visible = true;

                if (flag == true)
                {
                    lblavailability.CssClass = "textgreen";
                    lblavailability.Text = "Available.";
                }
                else
                {
                    lblavailability.CssClass = "errorbold";
                    lblavailability.Text = "Not Available.";
                }
            }
            else
            {
                lblavailability.CssClass = "textgreen";
                lblavailability.Visible = true;
                lblavailability.Text = "Available.";
            }

        }


问:
Identifying duplicates in a table and kicking duplicate records to a another table
I have some employee records in my table and we are identifying duplicates in them based on one field called workno. My data in TABLE_A is shown below

```<code>NAME  WORKNO       DATE
---------------------------
John     30000  09-JAN-2012
Franklin 40000  08-DEC-2014
Alicia   25000  19-JUL-2013
Jennifer 43000  20-JUL-2015
Gary     38000  15-SEP-2016
Joyce    25000  31-JAN-2017
Ahmad    25000  29-MAR-2017
James    55000  10-APR-2017
Jill     43000  12-OCT-2017
Jack     55000  18-JAN-2018
</code>```

Imagine there are close to a million records here. So need help with efficiency

My required output:-

Scenario 1: Keeping the records which has no duplicate(based on workno) in table_A itself. from the above table only John, Franklin and Gary should be there at the end since they have no duplicates with workno.

Scenario 2: the first record for a particular workno(incase of duplicates) should be written to table_B. "Alicia" with workno 25000 would be kicked into Table_B

Scenario 3: After writing the first duplicate to table_B the remaining records should be inserted into table_C. "Joyce" and "Ahmad" with workno would be kicked into table_C

I have tried to write my query which works fine for scenario 1 and 2. Need help if there is a better way if doing. But the insert part throws me error(query part works fine though).

Error report:

SQL Error: ORA-01847: day of month must be between 1 and last day of month
  01847. 00000 -  "day of month must be between 1 and last day of month"
  *Cause:

  *Action:

```<code>Insert into ztempo
Select *
from (SELECT fname, minit, lname, bdate, address, sex, salary, superssn, dno,
             ROW_NUMBER() OVER (PARTITION BY salary ORDER BY rownum) num
      from  Select *
            from ztemp
            where salary in (Select salary from ztemp group by salary having Count(*) > 1)

           )

     )
where num = 1;
</code>```

I guess I can use the same code with some tweaking at the end "where num > 1" for scenario 3. But have problem inserting. Please help

Need help completing it. Thanks in advance.

答:
The error you're getting suggests either the columns in ztempo are not the same order as ztemp or the date column is a varchar2 and contains invalid dates, like "2019-FEB-30".

It's better to explicitly state your columns, like this, in case the tables have the same columns, but in different order:

```<code>insert into ztempo ( fname, minit, ... )
</code>```

You're grouping by salary in your subquery, is that really what you want to do? And I think the order by rownum clause pretty much does nothing.

Body:
I have some employee records in my table and we are identifying duplicates in them based on one field called workno. My data in TABLE_A is shown below

NAME  WORKNO       DATE
---------------------------
John     30000  09-JAN-2012
Franklin 40000  08-DEC-2014
Alicia   25000  19-JUL-2013
Jennifer 43000  20-JUL-2015
Gary     38000  15-SEP-2016
Joyce    25000  31-JAN-2017
Ahmad    25000  29-MAR-2017
James    55000  10-APR-2017
Jill     43000  12-OCT-2017
Jack     55000  18-JAN-2018

Imagine there are close to a million records here. So need help with efficiency

My required output:-

Scenario 1: Keeping the records which has no duplicate(based on workno) in table_A itself. from the above table only John, Franklin and Gary should be there at the end since they have no duplicates with workno.

Scenario 2: the first record for a particular workno(incase of duplicates) should be written to table_B. "Alicia" with workno 25000 would be kicked into Table_B

Scenario 3: After writing the first duplicate to table_B the remaining records should be inserted into table_C. "Joyce" and "Ahmad" with workno would be kicked into table_C

I have tried to write my query which works fine for scenario 1 and 2. Need help if there is a better way if doing. But the insert part throws me error(query part works fine though).

Error report:

SQL Error: ORA-01847: day of month must be between 1 and last day of month
  01847. 00000 -  "day of month must be between 1 and last day of month"
  *Cause:

  *Action:

Insert into ztempo
Select *
from (SELECT fname, minit, lname, bdate, address, sex, salary, superssn, dno,
             ROW_NUMBER() OVER (PARTITION BY salary ORDER BY rownum) num
      from  Select *
            from ztemp
            where salary in (Select salary from ztemp group by salary having Count(*) > 1)

           )

     )
where num = 1;

I guess I can use the same code with some tweaking at the end "where num > 1" for scenario 3. But have problem inserting. Please help

Need help completing it. Thanks in advance.

Body:
The error you're getting suggests either the columns in ztempo are not the same order as ztemp or the date column is a varchar2 and contains invalid dates, like "2019-FEB-30".

It's better to explicitly state your columns, like this, in case the tables have the same columns, but in different order:

insert into ztempo ( fname, minit, ... )

You're grouping by salary in your subquery, is that really what you want to do? And I think the order by rownum clause pretty much does nothing.


问:
C# Writeline that responds with name
I haven't used variables on C# yet so I don't know how I would go about having the next Console.Writeline respond saying, "Hello X, welcome!". Adding the users input to the X.</p>

```<code>Console.WriteLine("What is your name?");
String answer = Console.ReadLine();

if (answer == string)
    Console.WriteLine("Okay , welcome!");
}
</code>```

答:
You can do it in an easy way:</p>

```<code>Console.WriteLine("What is your name?");
string name = Console.ReadLine();

if (answer == string)
    Console.WriteLine($"Okay , welcome {name}!");
</code>```

Title: C# Writeline that responds with name

Body:
I haven't used variables on C# yet so I don't know how I would go about having the next Console.Writeline respond saying, "Hello X, welcome!". Adding the users input to the X.

Console.WriteLine("What is your name?");
String answer = Console.ReadLine();

if (answer == string)
    Console.WriteLine("Okay , welcome!");
}

Body:
You can do it in an easy way:

Console.WriteLine("What is your name?");
string name = Console.ReadLine();

if (answer == string)
    Console.WriteLine($"Okay , welcome {name}!");


问:
how to scrape data individually from  tags using beautifulSoup?
I'm trying to scrape data from elections.in .There are three tables with the same class . below is the HTML from the website

```<code><h3 class="blmap">17th General (Lok Sabha) Election Results 2019 – State Wise</h3>

<table class="tableizer-table">

<thead><tr class="tableizer-firstrow"><th>State</th><th>Party</th><th>Number of Seats</th></tr></thead><tbody>

 <tr><td>Andaman & Nicobar Islands</td><td>Indian National Congress</td><td>1</td></tr>

 <tr><td>Andhra Pradesh</td><td>Yuvajana Sramika Rythu Congress Party</td><td>22</td></tr>

 <tr><td>Andhra Pradesh</td><td>Telugu Desam</td><td>3</td></tr>

 <tr><td>Arunachal Pradesh</td><td>Bharatiya Janata Party</td><td>2</td></tr>

 <tr><td>Assam</td><td>Bharatiya Janata Party</td><td>9</td></tr>

 <tr><td>Assam</td><td>Indian National Congress</td><td>3</td></tr>

 <tr><td>Assam</td><td>All India United Democratic Front</td><td>1</td></tr>
</code>```

I was able to get data and that appears like this,

```<code>    StatePartyNumber of Seats
    Andaman & Nicobar IslandsIndian National Congress1
    Andhra PradeshYuvajana Sramika Rythu Congress Party22
    Andhra PradeshTelugu Desam3
    Arunachal PradeshBharatiya Janata Party2
    AssamBharatiya Janata Party9
    AssamIndian National Congress3
    AssamAll India United Democratic Front1
    AssamIndependent1
    BiharBharatiya Janata Party17
</code>```

I wanted the output like below ,

```<code>    State,Party,Number of Seats
    Andaman & Nicobar Islands, Indian National Congress,1
    Andhra Pradesh,Yuvajana Sramika Rythu Congress Party,22
</code>```

or as a list .

This line of code is giving me the above output

```<code>soup.find_all('table')[1].get_text()
</code>```

This is my code , Github

Please suggest how to achieve that

thanks.

答:
Slightly shorter BeautifulSoup solution:

```<code>from bs4 import BeautifulSoup as soup
d = soup(content, 'html.parser')
headers, data = [i.text for i in d.find_all('th')], [[i.text for i in b.find_all('td')] for b in d.find_all('tr')[1:]]
</code>```

Output:

```<code>['State', 'Party', 'Number of Seats']
[['Andaman & Nicobar Islands', 'Indian National Congress', '1'], ['Andhra Pradesh', 'Yuvajana Sramika Rythu Congress Party', '22'], ['Andhra Pradesh', 'Telugu Desam', '3'], ['Arunachal Pradesh', 'Bharatiya Janata Party', '2'], ['Assam', 'Bharatiya Janata Party', '9'], ['Assam', 'Indian National Congress', '3'], ['Assam', 'All India United Democratic Front', '1']]
</code>```

To write to csv:

```<code>import csv
with open('election_results.csv', 'w') as f:
  write = csv.writer(f)
  write.writerows([headers, *data])
</code>```

Output:

```<code>State,Party,Number of Seats
Andaman & Nicobar Islands,Indian National Congress,1
Andhra Pradesh,Yuvajana Sramika Rythu Congress Party,22
Andhra Pradesh,Telugu Desam,3
Arunachal Pradesh,Bharatiya Janata Party,2
Assam,Bharatiya Janata Party,9
Assam,Indian National Congress,3
Assam,All India United Democratic Front,1
</code>```

Title: how to scrape data individually from <td> tags using beautifulSoup?

Body:
I'm trying to scrape data from elections.in .There are three tables with the same class . below is the HTML from the website

17th General (Lok Sabha) Election Results 2019 – State Wise

State	Party	Number of Seats

Andaman & Nicobar Islands	Indian National Congress	1

Andhra Pradesh	Yuvajana Sramika Rythu Congress Party	22

Andhra Pradesh	Telugu Desam	3

Arunachal Pradesh	Bharatiya Janata Party	2

Assam	Bharatiya Janata Party	9

Assam	Indian National Congress	3

Assam	All India United Democratic Front	1

I was able to get data and that appears like this,

    StatePartyNumber of Seats
    Andaman & Nicobar IslandsIndian National Congress1
    Andhra PradeshYuvajana Sramika Rythu Congress Party22
    Andhra PradeshTelugu Desam3
    Arunachal PradeshBharatiya Janata Party2
    AssamBharatiya Janata Party9
    AssamIndian National Congress3
    AssamAll India United Democratic Front1
    AssamIndependent1
    BiharBharatiya Janata Party17

I wanted the output like below ,

    State,Party,Number of Seats
    Andaman & Nicobar Islands, Indian National Congress,1
    Andhra Pradesh,Yuvajana Sramika Rythu Congress Party,22

or as a list .

This line of code is giving me the above output

soup.find_all('table')[1].get_text()

This is my code , Github

Please suggest how to achieve that

thanks.

Body:
Slightly shorter BeautifulSoup solution:

from bs4 import BeautifulSoup as soup
d = soup(content, 'html.parser')
headers, data = [i.text for i in d.find_all('th')], [[i.text for i in b.find_all('td')] for b in d.find_all('tr')[1:]]

Output:

['State', 'Party', 'Number of Seats']
[['Andaman & Nicobar Islands', 'Indian National Congress', '1'], ['Andhra Pradesh', 'Yuvajana Sramika Rythu Congress Party', '22'], ['Andhra Pradesh', 'Telugu Desam', '3'], ['Arunachal Pradesh', 'Bharatiya Janata Party', '2'], ['Assam', 'Bharatiya Janata Party', '9'], ['Assam', 'Indian National Congress', '3'], ['Assam', 'All India United Democratic Front', '1']]

To write to csv:

import csv
with open('election_results.csv', 'w') as f:
  write = csv.writer(f)
  write.writerows([headers, *data])

Output:

State,Party,Number of Seats
Andaman & Nicobar Islands,Indian National Congress,1
Andhra Pradesh,Yuvajana Sramika Rythu Congress Party,22
Andhra Pradesh,Telugu Desam,3
Arunachal Pradesh,Bharatiya Janata Party,2
Assam,Bharatiya Janata Party,9
Assam,Indian National Congress,3
Assam,All India United Democratic Front,1


问:
How to list the collections of all databases when i am logged in as admin
My goal is to list all Databases with their collections. Same as you login as user admin into robo3T for instance.

There is no problem to use the two commands below. But when I use the listCollections command I just receive the collections of the admin database. But unfortunatley not from all databases of admin user.

```<code>let db =  client.db('admin').admin();
db.command({listDatabases: 1, nameOnly: true}, (err, dbs)=>{});
db.command({listCollections: 1, nameOnly: true}, (err, collections)=>{});

</code>```

Any ideas how to solve that?

答:
I did not need an admin command.

Correct:

let db =  client.db('dbName').admin();

Body:
My goal is to list all Databases with their collections. Same as you login as user admin into robo3T for instance.

There is no problem to use the two commands below. But when I use the listCollections command I just receive the collections of the admin database. But unfortunatley not from all databases of admin user.

let db =  client.db('admin').admin();
db.command({listDatabases: 1, nameOnly: true}, (err, dbs)=>{});
db.command({listCollections: 1, nameOnly: true}, (err, collections)=>{});

Any ideas how to solve that?


问:
How to update a array list sort?
How to update array order?

I have a list with property 'order' and I would like to add an object in an array.

```<code>{id: 1, name: 'abba', order: 0},
{id: 5, name: 'Bingo', order: 1}
{id: 2, name: 'James', order: 2},
{id: 3, name: 'Turbo', order: 3},
{id: 4, name: 'Nano', order: 4}
</code>```

I would like to insert an object in Array and update the order.
The object needs to go in between id: 2 and id:3 and then update the order.

答:
You could find the index, splice the object and update from the given index all items with the index.

var array = [{ id: 1, name: 'abba', order: 0 }, { id: 5, name: 'Bingo', order: 1 }, { id: 2, name: 'James', order: 2 }, { id: 3, name: 'Turbo', order: 3 }, { id: 4, name: 'Nano', order: 4 }],
    object = { id: 7, name: 'Giga', order: -1 },
    insertBeforeId = 3,
    index = array.findIndex(({ id }) => id === insertBeforeId);

array.splice(index, 0, object);

do {
    array[index].order = index;
} while (++index < array.length);

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How to update a array list sort?

Body:
How to update array order?

I have a list with property 'order' and I would like to add an object in an array.

{id: 1, name: 'abba', order: 0},
{id: 5, name: 'Bingo', order: 1}
{id: 2, name: 'James', order: 2},
{id: 3, name: 'Turbo', order: 3},
{id: 4, name: 'Nano', order: 4}

I would like to insert an object in Array and update the order.
The object needs to go in between id: 2 and id:3 and then update the order.

Body:
You could find the index, splice the object and update from the given index all items with the index.

var array = [{ id: 1, name: 'abba', order: 0 }, { id: 5, name: 'Bingo', order: 1 }, { id: 2, name: 'James', order: 2 }, { id: 3, name: 'Turbo', order: 3 }, { id: 4, name: 'Nano', order: 4 }],
    object = { id: 7, name: 'Giga', order: -1 },
    insertBeforeId = 3,
    index = array.findIndex(({ id }) => id === insertBeforeId);

array.splice(index, 0, object);

do {
    array[index].order = index;
} while (++index < array.length);

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Calculate 'next date' with different periods
I have one table called checks. This holds several periods.
For that checks have a term - like each year, every 5 years or every 6 months. They're all written as {number} {years/months/weeks}.

I need a query which gives me the check that is closest in the future from a given starting point in the past (or future).

The following gives me the next_date, but it works only once. If your start_date was on 2016/01/01, and you have a 6 month-check and a yearly check, you would always get a yearly check with the bottom solution, because 2017/01/01 is closest to now.

```<code>select `checks`.*,
IF(SUBSTRING_INDEX(term, ' ', -1) = 'weeks', DATE_ADD('2016-01-01', INTERVAL SUBSTRING_INDEX(term, ' ', 1) week),
IF(SUBSTRING_INDEX(term, ' ', -1) = 'months', DATE_ADD('2016-01-01', INTERVAL SUBSTRING_INDEX(term, ' ', 1) month),
IF(SUBSTRING_INDEX(term, ' ', -1) = 'years', DATE_ADD('2016-01-01', INTERVAL SUBSTRING_INDEX(term, ' ', 1) year), 0)))
as next_date from `checks`
</code>```

In reality, at the time of writing it should give me the 6 months-check - Because that should happen on 06/01/2019, which is closest to my current date (2019/05/27).

Is there a way to determine this in a query?

答:
This seems like a really bad format, but I think you can do:</p>

```<code>select c.*,
       (case when term like '% weeks'
             then date('2016-01-01') + interval (substring_index(term, -2) + 0) weeks
             when term like '% months'
             then date('2016-01-01') + interval (substring_index(term, -2) + 0) month
             when term like '% years'
             then date('2016-01-01') + interval (substring_index(term, -2) + 0) year
      end) as next_date
from checks c
order by next_date asc
limit 1;
</code>```

Body:
I have one table called checks. This holds several periods.
For that checks have a term - like each year, every 5 years or every 6 months. They're all written as {number} {years/months/weeks}.

I need a query which gives me the check that is closest in the future from a given starting point in the past (or future).

The following gives me the next_date, but it works only once. If your start_date was on 2016/01/01, and you have a 6 month-check and a yearly check, you would always get a yearly check with the bottom solution, because 2017/01/01 is closest to now.

select `checks`.*,
IF(SUBSTRING_INDEX(term, ' ', -1) = 'weeks', DATE_ADD('2016-01-01', INTERVAL SUBSTRING_INDEX(term, ' ', 1) week),
IF(SUBSTRING_INDEX(term, ' ', -1) = 'months', DATE_ADD('2016-01-01', INTERVAL SUBSTRING_INDEX(term, ' ', 1) month),
IF(SUBSTRING_INDEX(term, ' ', -1) = 'years', DATE_ADD('2016-01-01', INTERVAL SUBSTRING_INDEX(term, ' ', 1) year), 0)))
as next_date from `checks`

In reality, at the time of writing it should give me the 6 months-check - Because that should happen on 06/01/2019, which is closest to my current date (2019/05/27).

Is there a way to determine this in a query?

Body:
This seems like a really bad format, but I think you can do:

select c.*,
       (case when term like '% weeks'
             then date('2016-01-01') + interval (substring_index(term, -2) + 0) weeks
             when term like '% months'
             then date('2016-01-01') + interval (substring_index(term, -2) + 0) month
             when term like '% years'
             then date('2016-01-01') + interval (substring_index(term, -2) + 0) year
      end) as next_date
from checks c
order by next_date asc
limit 1;


问:
How can I convert this for loop to java 8 stream analog
How can I convert this code to java 8 stream.

Tried to use for each, but failed. For loop code is working.

```<code>for(RestrictedInstrument restrictedInstrument : restrictedInstruments){
    List<Identifier> identifierList = restrictedInstrument.getIdentifier();
    setTicker(matrix, identifierList);
}
</code>```

setTicker() method should be called with matrix Object and identifierList.

答:
You can stream the list and then simply pass consumer which just calls setTicker function.</p>

```<code> restrictedInstruments.stream()
.forEach(identifierList -> setTicker(matrix, identifierList.getIdentifier()));
</code>```

Body:
How can I convert this code to java 8 stream.

Tried to use for each, but failed. For loop code is working.

for(RestrictedInstrument restrictedInstrument : restrictedInstruments){
    List<Identifier> identifierList = restrictedInstrument.getIdentifier();
    setTicker(matrix, identifierList);
}

setTicker() method should be called with matrix Object and identifierList.

Body:
You can stream the list and then simply pass consumer which just calls setTicker function.

 restrictedInstruments.stream()
.forEach(identifierList -> setTicker(matrix, identifierList.getIdentifier()));


问:
Matplotlib savefig cuts off pyplot table
I want to make some summarizing visualization + statistics of a data column.
I want to combine two or more subplots with a descriptive table and save the figure locally.
However, when saving the plot, a part of the table gets cropped.

When I do the following

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

column=np.random.normal(size=10000)
df=pd.DataFrame(column, columns=["Price"])

summary = (
        df.describe()
        .append((df.isnull().sum()/len(df)*100)
        .rename('nans %'))
        .iloc[:,0].to_frame()
        )
fig, (ax_distplot) = plt.subplots(1, 1, figsize=(25, 12))

#Distplot with summarizing table
sns.distplot(df.loc[:,"Price"], hist=True, bins=30, kde=False, ax=ax_distplot)
ax_distplot.set(ylabel='Count')
tab = ax_distplot.table(cellText=np.around(summary.values, decimals=2),
                        rowLabels=summary.index,
                        colLabels=summary.columns, loc="right",
                        bbox=[1.15, .2, 0.25, 0.8])

</code>```

I get:

When saving it locally with the following command

```<code>plt.savefig("Price.pdf", bbox_inches="tight")
</code>```

Yields:

I have tried

```<code>plt.subplots_adjust(right=0.85)
</code>```

without any luck.

答:
This is an error in how the table bounding box is calculated. You may open an issue about it.

In the meantime drawing the canvas manually (and hence twice) solves this.

```<code>fig.canvas.draw()
plt.savefig("price.png", bbox_inches="tight")
</code>```

Body:
I want to make some summarizing visualization + statistics of a data column.
I want to combine two or more subplots with a descriptive table and save the figure locally.
However, when saving the plot, a part of the table gets cropped.

When I do the following

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

column=np.random.normal(size=10000)
df=pd.DataFrame(column, columns=["Price"])

summary = (
        df.describe()
        .append((df.isnull().sum()/len(df)*100)
        .rename('nans %'))
        .iloc[:,0].to_frame()
        )
fig, (ax_distplot) = plt.subplots(1, 1, figsize=(25, 12))

#Distplot with summarizing table
sns.distplot(df.loc[:,"Price"], hist=True, bins=30, kde=False, ax=ax_distplot)
ax_distplot.set(ylabel='Count')
tab = ax_distplot.table(cellText=np.around(summary.values, decimals=2),
                        rowLabels=summary.index,
                        colLabels=summary.columns, loc="right",
                        bbox=[1.15, .2, 0.25, 0.8])

I get:

When saving it locally with the following command

plt.savefig("Price.pdf", bbox_inches="tight")

Yields:

I have tried

plt.subplots_adjust(right=0.85)

without any luck.

Body:
This is an error in how the table bounding box is calculated. You may open an issue about it.

In the meantime drawing the canvas manually (and hence twice) solves this.

fig.canvas.draw()
plt.savefig("price.png", bbox_inches="tight")


答:
try:
    val = int(user_input)
    print("user input is an int")
except ValueError:
    print("user_input is not an int")
```

Title: Validating if variable is int

Body:
I have a script to create vlan in cisco switches, and I need the user to input a number to the script.

I'm having trouble to make the script validate if the input is a number(must be int) and if the number is inside the range 2~4094, before it moves to the next steps.

I already wrote the rest of the script.


问:
How to do this cycle in Django-templates?
How can I make a cycle like this in django

```<code>for i in arr:
    for j in arr[i]:
        pass
</code>```

I tried this:

```<code>{% for i in arr %}
     {% for j in arr[i] %}

     {% endfor %}
{% endfor %}
</code>```

答:
Try using the following</p>

```<code>{% for i in arr %}
     {% for j in i %}

     {% endfor %}
{% endfor %}
</code>```

Body:
How can I make a cycle like this in django

for i in arr:
    for j in arr[i]:
        pass

I tried this:

{% for i in arr %}
     {% for j in arr[i] %}

     {% endfor %}
{% endfor %}

Body:
Try using the following

{% for i in arr %}
     {% for j in i %}

     {% endfor %}
{% endfor %}


问:
succesive onPreviewFrame byte[]
I am capturing the onPreviewFrame in a byte[] and then saving this to compare with the next captured frame.   Although the camera is pointed to an area with no change happening and I can see on the display that there is no change succesive frames element by elemnet are different.  Any suggestion why this should be so?   Also I only want the grayscale and I understand that the first height * width bytes are grayscale data, is this correct></p>

答: Statistically, there cannot be an exact match. Check out Image comparison - fast algorithm for a way of comparing images.</p>

Title: succesive onPreviewFrame byte[]


问:
How to convert an If Statement to a Ternary Operator expression
I am working with Java version "1.8.0_171".  I am trying to convert this simple If statement to a ternary expression/operator:

```<code>private String player;   // a class variable
.     .    .     .     .     .    .    .     .     .
public String switchPlayer(String player) {
    if(this.player == "X")
        this.player = "O";
    else
        this.player = "X";
    return player;
}
</code>```

I tried to replace the If statement in this method with the following ternary statement:

player == "X" ? "O" : "X";

Java flags the == “X” in this statement  with the following error:

```<code>Multiple markers at this line
- Type mismatch: cannot convert from String to
 boolean
- Syntax error on token "==", invalid
 AssignmentOperator
</code>```

This is the quick fix that Eclipse suggests:

```<code>String dummy = player == "X" ? "O" : "X";
</code>```

It seems a bit strange but, the ternary operator in Java has a left-side variable assignment requirement.  The only error that I receive now is a simple warning that I am not using the variable dummy anywhere else in my code.

I am just going to use the simple If statement because the refactor value here is of small significance.  I thought that I would post this anyway to see if there is any feedback from the community.

答:
I think it'll work if you tried:</p>

```<code>this.player = this.player == "X"? "O" : "X";
</code>```

Body:
I am working with Java version "1.8.0_171".  I am trying to convert this simple If statement to a ternary expression/operator:

private String player;   // a class variable
.     .    .     .     .     .    .    .     .     .
public String switchPlayer(String player) {
    if(this.player == "X")
        this.player = "O";
    else
        this.player = "X";
    return player;
}

I tried to replace the If statement in this method with the following ternary statement:

player == "X" ? "O" : "X";

Java flags the == “X” in this statement  with the following error:

Multiple markers at this line
- Type mismatch: cannot convert from String to
 boolean
- Syntax error on token "==", invalid
 AssignmentOperator

This is the quick fix that Eclipse suggests:

String dummy = player == "X" ? "O" : "X";

It seems a bit strange but, the ternary operator in Java has a left-side variable assignment requirement.  The only error that I receive now is a simple warning that I am not using the variable dummy anywhere else in my code.

I am just going to use the simple If statement because the refactor value here is of small significance.  I thought that I would post this anyway to see if there is any feedback from the community.

Body:
I think it'll work if you tried:

this.player = this.player == "X"? "O" : "X";


问:
Run Configuration
I'm a new to Intellij + Gradle integration. I created a sample Java gradle project. When I create a new Configuration to try run my test main, it automatically make it a gradle task. Say if I want to run the Configuration as Java command line, instead of gradle task, is there a way to do that?

Thanks,

答:
IntelliJ + Gradle does not create new gradle tasks in this case - IntelliJ is using the Gradle integration and knows how to create a configuration that you can run from Gradle. If you want to run the unit tests with Gradle from the command line, here are a few examples:

```<code># Executes all tests in SomeTestClass
gradle test --tests SomeTestClass

# Executes a single specified test in SomeTestClass
gradle test --tests SomeTestClass.someSpecificMethod

gradle test --tests SomeTestClass.*someMethod*
</code>```

More can be found on the Gradle website.

Title: Run Configuration

Body:
IntelliJ + Gradle does not create new gradle tasks in this case - IntelliJ is using the Gradle integration and knows how to create a configuration that you can run from Gradle. If you want to run the unit tests with Gradle from the command line, here are a few examples:

# Executes all tests in SomeTestClass
gradle test --tests SomeTestClass

# Executes a single specified test in SomeTestClass
gradle test --tests SomeTestClass.someSpecificMethod

gradle test --tests SomeTestClass.*someMethod*

More can be found on the Gradle website.


答: You can create a simple "Application" configuration as described here: https://www.jetbrains.com/help/idea/creating-and-editing-run-debug-configurations.html</p>

Title: Run Configuration

Body:
I'm a new to Intellij + Gradle integration. I created a sample Java gradle project. When I create a new Configuration to try run my test main, it automatically make it a gradle task. Say if I want to run the Configuration as Java command line, instead of gradle task, is there a way to do that?

Thanks,


问:
Is C++17 std::shared_mutex not available yet?
Looking at C++ compiler support, it appears that the untimed version of std::shared_mutex is available in GCC 5.0+. However, even with gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04), and compiling with -std=c++1z, a simple initialization of a shared mutex ends up with:

```<code>error: ‘shared_mutex’ in namespace ‘std’ does not name a type
        std::shared_mutex mutex_;
</code>```

And no, I have already included the proper header: #include <shared_mutex>.

It can't locate the proper header, because it does not seem to exist. Actually, the linker uses the library locate at /usr/include/c++/5/shared_mutex, which contains only the implementation of the std::shared_timed_mutex (like the C++14 standard).

I have installed gcc-5 and g++-5 by adding the repository at ppa:ubuntu-toolchain-r/test and using update-alternatives to properly set up their bins.

Is there something I can do to compile my code correctly using the newest C++17 standard? And probably is a stupid question to ask, but is it too early to start using -std=c++1z even if it should be already supported? Because it is supported, right?

答:
follow this link to install/upgrade to the latest version of GCC and G++. http://tuxamito.com/wiki/index.php/Installing_newer_GCC_versions_in_Ubuntu

I have tried it on my ubuntu and successful.

Body:
Looking at C++ compiler support, it appears that the untimed version of std::shared_mutex is available in GCC 5.0+. However, even with gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04), and compiling with -std=c++1z, a simple initialization of a shared mutex ends up with:

error: ‘shared_mutex’ in namespace ‘std’ does not name a type
        std::shared_mutex mutex_;

And no, I have already included the proper header: #include <shared_mutex>.

It can't locate the proper header, because it does not seem to exist. Actually, the linker uses the library locate at /usr/include/c++/5/shared_mutex, which contains only the implementation of the std::shared_timed_mutex (like the C++14 standard).

I have installed gcc-5 and g++-5 by adding the repository at ppa:ubuntu-toolchain-r/test and using update-alternatives to properly set up their bins.

Is there something I can do to compile my code correctly using the newest C++17 standard? And probably is a stupid question to ask, but is it too early to start using -std=c++1z even if it should be already supported? Because it is supported, right?


问:
How can I remove the first and last Node from doubly linked list?
I have a homework to write a method that will remove the FIRST Node and return its value in a doubly linked list in O(1), and one more method to remove the LAST Node in doubly linked list and return its value in O(1). This is what I did so far.</p>

```<code>class DoubleList<T>
{
    DNode _start;
    DNode _end;

    public void AddFirst(T value)
    {
        DNode tmp = new DNode(value);
        tmp._next = _start;
        tmp._prev = null;
        if (_start != null)
        {
            _start._prev = tmp;
        }
        _start = tmp;
        if (_start._next == null)
            _end = tmp;
    }

    public void AddLast(DoubleList<T> doubleyList, T value)
    {
        DNode tmp = new DNode(value);
        if (_start == null)
        {
            AddFirst(value);
            return;
        }
        DNode lastNode = GetLastNode(doubleyList);
        lastNode._next = tmp;
        tmp._prev = lastNode;
        _end._next = tmp;
        _end = tmp;
    }
}
</code>```

答:
There is already a class doubleList in C# that have these methods.

Check this link : https://learn.microsoft.com/fr-fr/dotnet/api/system.collections.generic.linkedlist-1?view=netframework-4.8

Body:
I have a homework to write a method that will remove the FIRST Node and return its value in a doubly linked list in O(1), and one more method to remove the LAST Node in doubly linked list and return its value in O(1). This is what I did so far.

class DoubleList<T>
{
    DNode _start;
    DNode _end;

    public void AddFirst(T value)
    {
        DNode tmp = new DNode(value);
        tmp._next = _start;
        tmp._prev = null;
        if (_start != null)
        {
            _start._prev = tmp;
        }
        _start = tmp;
        if (_start._next == null)
            _end = tmp;
    }

    public void AddLast(DoubleList<T> doubleyList, T value)
    {
        DNode tmp = new DNode(value);
        if (_start == null)
        {
            AddFirst(value);
            return;
        }
        DNode lastNode = GetLastNode(doubleyList);
        lastNode._next = tmp;
        tmp._prev = lastNode;
        _end._next = tmp;
        _end = tmp;
    }
}


问:
Arduino with A9 - troubleshooting AT commands
I am programming an Arduino with an A9 which has the ability to take AT commands directly. I'm using the following code, which allows me to enter commands:

```<code>void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(8,OUTPUT);
  digitalWrite(5, HIGH);
  digitalWrite(4, LOW);
  digitalWrite(8, HIGH);
  delay(3000);
  digitalWrite(8, LOW);
  Serial.println("A7 Power ON!");
}

void loop()
{
    char dat;
    if(Serial1.available()){
        dat = Serial1.read();
        Serial.print(dat);
    }
    if(Serial.available()){
        dat = Serial.read();
        Serial1.print(dat);
    }
}
</code>```

I can see that it's registered:

AT+CREG?

+CREG: 2,3,"A5FA","5CB4",0

and that it is in plaintext SMS mode:

AT+CMGF=?

+CMGF:(0,1)

OK

AT+CMGF=1

OK

but attempts to send and receive messages get a CMS ERROR 500 and 300 respectively:

AT+CMGS="0584413829"

test sms
    +CMS ERROR: 500

AT+CMGL="ALL"

+CMS ERROR: 300

Anyone have any ideas? I'm at my wits' end.

答:
for the error 300 it means:

Mobile equipment (ME) failure.

where Mobile equipment refers to the mobile
device that communicates with the wireless network

the 500 is an unknown error, did you break the GSM module maybe?

Body:
I am programming an Arduino with an A9 which has the ability to take AT commands directly. I'm using the following code, which allows me to enter commands:

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(8,OUTPUT);
  digitalWrite(5, HIGH);
  digitalWrite(4, LOW);
  digitalWrite(8, HIGH);
  delay(3000);
  digitalWrite(8, LOW);
  Serial.println("A7 Power ON!");
}

void loop()
{
    char dat;
    if(Serial1.available()){
        dat = Serial1.read();
        Serial.print(dat);
    }
    if(Serial.available()){
        dat = Serial.read();
        Serial1.print(dat);
    }
}

I can see that it's registered:

AT+CREG?

+CREG: 2,3,"A5FA","5CB4",0

and that it is in plaintext SMS mode:

AT+CMGF=?

+CMGF:(0,1)

OK

AT+CMGF=1

OK

but attempts to send and receive messages get a CMS ERROR 500 and 300 respectively:

AT+CMGS="0584413829"

test sms
    +CMS ERROR: 500

AT+CMGL="ALL"

+CMS ERROR: 300

Anyone have any ideas? I'm at my wits' end.


问:
Difficulty installing RSpec on Windows
I'm trying to get started with RSpec. I already had Ruby 1.8.7 installed on my Windows 7 machine.

So I typed gem install rspec and that seemed to work. But if I type spec in the command line, the command is not found. My path currently includes the bin folder in my RUBY_HOME.

If I look into the C:\Users\Eric\.gem\specs\rubygems.org%80\quick\Marshal.4.8 directory, I do see four RSpec files such as rspec-core-2.5.0.gemspec. Nevertheless, the spec command fails even in this directory.

What needs to be done to install RSpec correctly? It would seem like a path issue, but I have been unable to find a directory where the spec command works, so I can't figure what to add to my path.

答: There's no spec command in RSpec 2. Try rake spec or rspec spec.

Title: Difficulty installing RSpec on Windows


问:
Problem when adding a slider in the front page : admin panel works like I added a new slider
Not  working  add my slider in my  front page.. Admin panel working  like  I add new  slider. That is  working  but  front page  is  not  working.

Undefined variable: sliders (View: C:\xampp\htdocs\Ecommerce\resources\views\front\layouts\slider.blade.php) (View: C:\xampp\htdocs\Ecommerce\resources\views\front\layouts\slider.blade.php) (View: C:\xampp\htdocs\Ecommerce\resources\views\front\layouts\slider.blade.php)

答: The reason is you have defined a undefined variable at view. You may not passing the values into the variable from controller. So please update the question with the relevant controller and the code of the relevant view.</p>


问:
DataTables fixed headers misaligned with columns in wide tables

Problem

When using the sScrollX, sScrollXInner and/or sScrollY to achieve a fixed header table with its inner content scrolling, the headers of the table go out of alignment with the rest of the body in Chrome and IE. Firefox, on the other hand, displays them perfectly.

Using the version 1.9.4, as far as I can tell, this issue only occurs when there is a lot of data with fluctuating widths, and with words that are very long/unwrappable combined in the same columns as small ones. Also, the table in question needs to be fairly wide.

All these factors are demonstrated in this fiddle:

Output

Chrome:

IE:

Firefox

Suggested Solutions

These solutions have been suggested before but have had no effect on my implementation. Owing to some of these suggestions, I setup a clean plain vanilla demo as I wanted to ensure that no other code was contributing to this effect.

turn-off/remove all my css

setTimeout( function () { oTable.fnAdjustColumnSizing(); }, 10 );

calling oTable.fnFilter( "x",0 ) and oTable.fnFilter( "",0 ) in that order

"sScrollXInner": "100%"

get rid of all widths

The only solution that I found to the misaligned headers was taking out sScrollX and sScrollY, but this can't be counted as a solution as you lose the fixed header/inner content scrolling functionality. So sadly it's a temporary hack, not a fix!

Note

To edit/play with the latest fiddle.

I have tried various combinations which can be observed in the revision history of the fiddle by using the link http://jsfiddle.net/pratik136/etL73/#REV# where 1 <= #REV# <= 12

History

StackO

This question has been asked before: jQuery Datatables Header Misaligned With Vertical Scrolling

but the vital difference is that the OP of that question mentioned that they were able to fix the issue if all CSS was removed, which is untrue in my case, and I have tried a few permutations, thus thought the question worthy of a repost.

External

This issue has also been flagged on the DataTables forum:

http://datatables.net/forums/discussion/7395/sscrolly-and-sscrollx-broken/p1

http://datatables.net/forums/discussion/7778/vertical-scrolling-messes-up-column-header-alignment#Item_1

http://datatables.net/forums/discussion/3835/width-columns-problem-in-chrome-safari/p1

My bug report: http://datatables.net/forums/discussion/12491/datatables-header-alignment-issue-refresh#Item_1

This issue has driven me nuts! Please contribute your thoughts!

答: After trying everything I could, I just added "autoWidth": true and it worked for me.


问:
Keep flutter sensors listening on locked screen
I've been working with the flutter sensors plugin and works pretty well until I lock the screen.
What I'm currently doing is listening the accelerometer events and create a post request after that.
I need to do this even with the screen locked, or even better, with the app running in background.
Do I need to create a MethodChannel and go native? or there is any way to do this with flutter?</p>

答: You'll likely need to use platform channels considering you want to do this in the background. This would require operating on a separate isolate. There is an article listed in the documentation though I know others have had issues with it functioning on iOS and it's using objective c rather than swift. </p>


问:
unable to import tensorflow on Mac
I'm trying to install tensorflow on my MacBook Pro but I keep getting this error message when I run any code that has import tensorflow. I am using Python 3.7.3 on macOS Mojave.

I learnt from some other solutions online how to solve the problem like try pip install tensorflow==2.0.0-alpha0 --ignore-installed. It worked for some but not for me.

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

data = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = data.load_data()
```

答:
install anaconda and try this:

Create Virtual Environment

```<code>conda create --name tensorflow-env python=3.7.3
</code>```

Activate the environment

```<code>activate tensorflow-env
</code>```

Install tensorflow

```<code>pip install --upgrade tensorflow
</code>```

Test your installation

```<code>import tensorflow as tf
hello = tf.constant("hello TensorFlow!")
sess=tf.Session()
print sess.run(hello)
</code>```

output:

"hello TensorFlow!"

Title: unable to import tensorflow on Mac

Body:
install anaconda and try this:

Create Virtual Environment

conda create --name tensorflow-env python=3.7.3

Activate the environment

activate tensorflow-env

Install tensorflow

pip install --upgrade tensorflow

Test your installation

import tensorflow as tf
hello = tf.constant("hello TensorFlow!")
sess=tf.Session()
print sess.run(hello)

output:

"hello TensorFlow!"


问:
Validating if variable is int
I have a script to create vlan in cisco switches, and I need the user to input a number to the script.

I'm having trouble to make the script validate if the input is a number(must be int) and if the number is inside the range 2~4094, before it moves to the next steps.

I already wrote the rest of the script.

答:
You can use str.isdecimal() to check if string contains only digits.

```<code>inp = input("Enter number: ")
if inp.isdecimal():
    n = int(inp)
else:
    print("Not a number")
</code>```

If you need function:

```<code>def validate(inp):
    return isinstance(inp, str) and inp.isdecimal()

inp = input("Enter number: ")
print(validate(inp))
</code>```

Title: Validating if variable is int

Body:
You can use str.isdecimal() to check if string contains only digits.

inp = input("Enter number: ")
if inp.isdecimal():
    n = int(inp)
else:
    print("Not a number")

If you need function:

def validate(inp):
    return isinstance(inp, str) and inp.isdecimal()

inp = input("Enter number: ")
print(validate(inp))


问:
How to get the outputs from a CONNECT platform internal programatic call?
When using internal node call on CONNECT platform as described in the following answer: How to make a node call from another node in a package on CONNECT platform, how would one go about getting the outputs of that call?</p>

答:
platform.call returns a Promise object, so you would basically need to do something like this:

platform.call('/whatever', { param: 'stuff' })
  .then(response => {
    //
    // handle the response.
    // - `response.output` will denote which output of the node's signature was
    //    activated,
    // - `response.data` will be the data sent to that output,
    // - `response.control` will be the control output of the node according to its
    //    signature.
    //
  })
  .catch(error => {
  //
  // whatever error handling logic.
  //
  });
```

for a refresher on node signatures, outputs, control outputs, etc., perhaps take a look here:
https://medium.com/connect-platform/connect-platform-basic-concepts-543b79c3094e

Body:
platform.call returns a Promise object, so you would basically need to do something like this:

platform.call('/whatever', { param: 'stuff' })
  .then(response => {
    //
    // handle the response.
    // - `response.output` will denote which output of the node's signature was
    //    activated,
    // - `response.data` will be the data sent to that output,
    // - `response.control` will be the control output of the node according to its
    //    signature.
    //
  })
  .catch(error => {
  //
  // whatever error handling logic.
  //
  });

for a refresher on node signatures, outputs, control outputs, etc., perhaps take a look here:
https://medium.com/connect-platform/connect-platform-basic-concepts-543b79c3094e


问:
Can a thread be accessed from two forms in a Windows forms application
I wish to run a thread to update the Image in the picturebox . The image is streamed form the camera.
I require to stream images to two pictureboxes in two different forms, but one at a time.
Is it possible to create a single thread which can be accessed by both forms.

I think a backgroundworker would be appropriate. But how do I update the images in the picturebox of the respective forms?

I am using VC++ CLI/CLR

答: What I think you wanna do is this: when creating the new form, send to the constructer the first form as an object , then , and make a setter/ getter or just make the thread public, then you can "access" it from both forms as you requested.</p>


问:
JSON Schema: How to extend with more properties?
Let's say I have a simple JSON like:

```<code>"values": {
    "A": 0,
    "B": 0,
    "C": 0,
    "D": 0,
    "E": 0,
}
</code>```

A, B, C are part of the basic schema T1 while D,E are part of an extending schema T2. Therefore the schema T1 has 3 properties while T2 has 5 properties. I would like to avoid write A,B,C twice, in both schemas.

Is there anyway in JSON Schema to extend the list of properties?

答:
If you want to split out your schemas in a way which reflects extending objects, where some of your schemas have additionalProperties: false, you need to hoist up the additionalProperties: false.

You can use a definition in each schema to define the object without additionalProperties: false, then the root schema allOf reference the definition with additionalProperties: true. Then in the other schemas, you can reference the previous schema's definition.

Unfortunately, it's a limitation with draft-7. In draft-8, it is possible to do what you want with a new keyword, but it's not published yet.

Body:
Let's say I have a simple JSON like:

"values": {
    "A": 0,
    "B": 0,
    "C": 0,
    "D": 0,
    "E": 0,
}

A, B, C are part of the basic schema T1 while D,E are part of an extending schema T2. Therefore the schema T1 has 3 properties while T2 has 5 properties. I would like to avoid write A,B,C twice, in both schemas.

Is there anyway in JSON Schema to extend the list of properties?


问:
configuration management tool to automate the property files
Any configuration management tool in the market to automate the property file for the different environments, lets say i have one complete configuration files with key and values but for the other environments the values will differ so am just trying to look out if this could be done easily like template or csv or any other valuable approach.</p>

答: You can use Sparrow6 automation DSL to populate configuration files using embedded templater. You can go even further and utilize Tomtit task runner that integrates with Sparrow6 and provides environments feature for these very types of tasks.</p>


问:
Why does my Singleton Module seem to have two instances?

The Problem

I am trying to create a Singleton which stores information that can only be accessed with Setters and Getters.  I like to keep my code as short and clean as possible so I am always looking for the shortest way of writing things.  While this works in most places, in others I tend to create some not so explainable (to me) errors.

So,.. when importing my module for testing I use:

```<code>const { ports, instance: activeConfig } = require('./activeConfig')
</code>```

ports should be my Getter.  I wanted to avoid having to always write out activeConfig.ports when possible.  I thought for the most part this was working in my test until I tried to reset my values.

A few things I have observed:

When I run activeConfig.ports my getter is activated. I can see this before log result 1, 2 and 3.

When I run just ports my getter is NOT activated. I can see from log result 1a, 2a and 3a that nothing is run inside the Singleton. But I still get results.

When I set a new values I can see inside the Singleton my value for _myPorts does change.  The result for both methods also is as I expected.

However, after I reset my values this behavior no longer stays consistent.  While activeConfig.ports provides the expected result, ports does not. I am not sure where log 3a gets this result from and why it differs from log result 3.

I have apparently built in some sort of instability but my JavaScript skills are not strong enough to pinpoint the problem.  I have tried googling all variations of "JavaScript Singleton Getter Export" but cant seem to find an example that covers my specific use case.

If anyone could help me fix my code it would be greatly appreciated.  Also, little things like the correct terminology or links to advanced examples would really be appreciated.  :)

My main focus is to be able to import getters in a single require command!

I have simplified this example, but I would like to be able to do this with x number of getters.

I am not looking for work-arounds like:

```<code>const activeConfig = require('./activeConfig')
const ports = activeConfig.ports
</code>```

or

```<code>const ports = require('./activeConfig').ports
</code>```

This would require one line per getter and I am trying to avoid this exact situations. (Especially with 10+ getters)

I would really like to know if there is a correct way of doing this.  :)

The Code

```<code>'use strict'
let activeConfig = (function () {
  const _defPorts = {
    http: 80,
    https: 443,
    secure: false
  }

  let _myPorts = {..._defPorts}

  let _setPorts = function (value) {
    console.log('SP->', _myPorts)
    if (value) {
      Object.keys(value).forEach((key) => {
        if (typeof _myPorts[key] !== 'undefined') {
          _myPorts[key] = value[key]
        }
      })
    }
    console.log('SP=>', _myPorts)
  }

  let _resetConfig = function () {
      console.log('RC->', _myPorts)
      _myPorts = {..._defPorts}
      console.log('RC=>', _myPorts)
    }

  return {
    setPorts: _setPorts,
    resetConfig: _resetConfig,
    get instance() {
      return activeConfig
    },
    get ports() {
      console.log('GP->', _myPorts)
      return _myPorts
    },
    set ports(value) {
      return _setPorts(value)
    }
  }
})()
module.exports = activeConfig
</code>```

The Test Code

```<code>'use strict'
const {
    ports,
    instance: activeConfig
} = require('./activeConfig')

console.log('1 ->', activeConfig.ports)
console.log('1a->', ports)
activeConfig
    .setPorts({
        secure: true,
        http: 8080
    })

console.log('2 ->', activeConfig.ports)
console.log('2a->', ports)
console.log('RESET')
activeConfig.resetConfig()
console.log('3 ->', activeConfig.ports)
console.log('3a->', ports)
</code>```

The Log

```<code>GP-> { http: 80, https: 443, secure: false }
GP-> { http: 80, https: 443, secure: false }
1 -> { http: 80, https: 443, secure: false }
1a-> { http: 80, https: 443, secure: false }
SP-> { http: 80, https: 443, secure: false }
SP=> { http: 8080, https: 443, secure: true }
GP-> { http: 8080, https: 443, secure: true }
2 -> { http: 8080, https: 443, secure: true }
2a-> { http: 8080, https: 443, secure: true }
RESET
RC-> { http: 8080, https: 443, secure: true }
RC=> { http: 80, https: 443, secure: false }
GP-> { http: 80, https: 443, secure: false }
3 -> { http: 80, https: 443, secure: false }
3a-> { http: 8080, https: 443, secure: true }
</code>```

答:
Object destructuring is just syntactic sugar around property access:

```<code> const { port } = obj;
 // equals
 const port = obj.port;
</code>```

so at the time you destructure, you do access the getter. Changing port changes the local variable. It does not get reflected to the object, and thus does not trigger the setter.

There is no real way to use getters / setters in that way (okay, lets forget about with).

Instead, you could manually trigger unreal setters:

```<code>  const obj = {
    port: { set(_v) { return this._v = _v; }, get() { return this._v; } }
  };

 const { port } = obj;
 port.set(10);
</code>```

Body:
The Problem

I am trying to create a Singleton which stores information that can only be accessed with Setters and Getters.  I like to keep my code as short and clean as possible so I am always looking for the shortest way of writing things.  While this works in most places, in others I tend to create some not so explainable (to me) errors.

So,.. when importing my module for testing I use:

const { ports, instance: activeConfig } = require('./activeConfig')

ports should be my Getter.  I wanted to avoid having to always write out activeConfig.ports when possible.  I thought for the most part this was working in my test until I tried to reset my values.

A few things I have observed:

When I run activeConfig.ports my getter is activated. I can see this before log result 1, 2 and 3.

When I run just ports my getter is NOT activated. I can see from log result 1a, 2a and 3a that nothing is run inside the Singleton. But I still get results.

When I set a new values I can see inside the Singleton my value for _myPorts does change.  The result for both methods also is as I expected.

However, after I reset my values this behavior no longer stays consistent.  While activeConfig.ports provides the expected result, ports does not. I am not sure where log 3a gets this result from and why it differs from log result 3.

I have apparently built in some sort of instability but my JavaScript skills are not strong enough to pinpoint the problem.  I have tried googling all variations of "JavaScript Singleton Getter Export" but cant seem to find an example that covers my specific use case.

If anyone could help me fix my code it would be greatly appreciated.  Also, little things like the correct terminology or links to advanced examples would really be appreciated.  :)

My main focus is to be able to import getters in a single require command!

I have simplified this example, but I would like to be able to do this with x number of getters.

I am not looking for work-arounds like:

const activeConfig = require('./activeConfig')
const ports = activeConfig.ports

or

const ports = require('./activeConfig').ports

This would require one line per getter and I am trying to avoid this exact situations. (Especially with 10+ getters)

I would really like to know if there is a correct way of doing this.  :)

The Code

'use strict'
let activeConfig = (function () {
  const _defPorts = {
    http: 80,
    https: 443,
    secure: false
  }

  let _myPorts = {..._defPorts}

  let _setPorts = function (value) {
    console.log('SP->', _myPorts)
    if (value) {
      Object.keys(value).forEach((key) => {
        if (typeof _myPorts[key] !== 'undefined') {
          _myPorts[key] = value[key]
        }
      })
    }
    console.log('SP=>', _myPorts)
  }

  let _resetConfig = function () {
      console.log('RC->', _myPorts)
      _myPorts = {..._defPorts}
      console.log('RC=>', _myPorts)
    }

  return {
    setPorts: _setPorts,
    resetConfig: _resetConfig,
    get instance() {
      return activeConfig
    },
    get ports() {
      console.log('GP->', _myPorts)
      return _myPorts
    },
    set ports(value) {
      return _setPorts(value)
    }
  }
})()
module.exports = activeConfig

The Test Code

'use strict'
const {
    ports,
    instance: activeConfig
} = require('./activeConfig')

console.log('1 ->', activeConfig.ports)
console.log('1a->', ports)
activeConfig
    .setPorts({
        secure: true,
        http: 8080
    })

console.log('2 ->', activeConfig.ports)
console.log('2a->', ports)
console.log('RESET')
activeConfig.resetConfig()
console.log('3 ->', activeConfig.ports)
console.log('3a->', ports)

The Log

GP-> { http: 80, https: 443, secure: false }
GP-> { http: 80, https: 443, secure: false }
1 -> { http: 80, https: 443, secure: false }
1a-> { http: 80, https: 443, secure: false }
SP-> { http: 80, https: 443, secure: false }
SP=> { http: 8080, https: 443, secure: true }
GP-> { http: 8080, https: 443, secure: true }
2 -> { http: 8080, https: 443, secure: true }
2a-> { http: 8080, https: 443, secure: true }
RESET
RC-> { http: 8080, https: 443, secure: true }
RC=> { http: 80, https: 443, secure: false }
GP-> { http: 80, https: 443, secure: false }
3 -> { http: 80, https: 443, secure: false }
3a-> { http: 8080, https: 443, secure: true }

Body:
Object destructuring is just syntactic sugar around property access:

 const { port } = obj;
 // equals
 const port = obj.port;

so at the time you destructure, you do access the getter. Changing port changes the local variable. It does not get reflected to the object, and thus does not trigger the setter.

There is no real way to use getters / setters in that way (okay, lets forget about with).

Instead, you could manually trigger unreal setters:

  const obj = {
    port: { set(_v) { return this._v = _v; }, get() { return this._v; } }
  };

 const { port } = obj;
 port.set(10);


问:
top 5 highest only specific rows
I have this in my column A and column B is the number after the text.

```<code>Access rights
Question    2
Total - Access rights   2
Adobe software
Error   1
Total - Adobe software  1
Autorisaties
Question    1
Total - Autorisaties    1
AX
Question    13
Error   14
Total - AX  27
Backup
Question    1
Total - Backup  1
Computer
Question    4
Error   6
Total - Computer    10
</code>```

Right now I have this formula:

=INDEX($A$2:$A28;MATCH(1;INDEX(($B$2:$B$28=LARGE($B$2:$B$28;ROWS(D$1:D1)))*(COUNTIF(D$1:D1;$A$2:$A$28)=0););0))

to get the largest value. So in this case the first line is Total AX.
And when I drag that formula down it says error because that is the 2nd largest number.

What I want is that it look looks at the total - value so in this case it should first by Total -AX and then Total -computer and then total access rights and than the rest because some of them are showing 1 as total

答:
To give you an idea:

Formula in E1:

```<code>=INDEX($A$1:$A$10,MATCH(LARGE((ISNUMBER(SEARCH("Total - ",$A$1:$A$10))*($B$1:$B$10)),ROW()),$B$1:$B$10,0))
</code>```

Enter through CtrlShiftEnter

Drag down....

EDIT

In case you have duplicates, an helper column would be advisable IMO. Like so:

Formula in E1:

```<code>=LARGE((ISNUMBER(SEARCH("Total - ",$A$1:$A$10))*($B$1:$B$10)),ROW())
</code>```

Formula in F1:

```<code>=INDEX($A$1:$A$10,SMALL(IF(E1=$B$1:$B$10,ROW($A$1:$A$10)-ROW($A$1)+1),COUNTIF($E$1:E1,E1)))
</code>```

Both being array formulas entered through CtrlShiftEnter

Title: top 5 highest only specific rows

Body:
I have this in my column A and column B is the number after the text.

Access rights
Question    2
Total - Access rights   2
Adobe software
Error   1
Total - Adobe software  1
Autorisaties
Question    1
Total - Autorisaties    1
AX
Question    13
Error   14
Total - AX  27
Backup
Question    1
Total - Backup  1
Computer
Question    4
Error   6
Total - Computer    10

Right now I have this formula:

=INDEX($A$2:$A28;MATCH(1;INDEX(($B$2:$B$28=LARGE($B$2:$B$28;ROWS(D$1:D1)))*(COUNTIF(D$1:D1;$A$2:$A$28)=0););0))

to get the largest value. So in this case the first line is Total AX.
And when I drag that formula down it says error because that is the 2nd largest number.

What I want is that it look looks at the total - value so in this case it should first by Total -AX and then Total -computer and then total access rights and than the rest because some of them are showing 1 as total

Body:
To give you an idea:

Formula in E1:

=INDEX($A$1:$A$10,MATCH(LARGE((ISNUMBER(SEARCH("Total - ",$A$1:$A$10))*($B$1:$B$10)),ROW()),$B$1:$B$10,0))

Enter through CtrlShiftEnter

Drag down....

EDIT

In case you have duplicates, an helper column would be advisable IMO. Like so:

Formula in E1:

=LARGE((ISNUMBER(SEARCH("Total - ",$A$1:$A$10))*($B$1:$B$10)),ROW())

Formula in F1:

=INDEX($A$1:$A$10,SMALL(IF(E1=$B$1:$B$10,ROW($A$1:$A$10)-ROW($A$1)+1),COUNTIF($E$1:E1,E1)))

Both being array formulas entered through CtrlShiftEnter


问:
What is the proper way to completely print out a list in Python
I'm trying to create a simple program to print out the binary number of any given number under 255. I have everything working except printing out the final list.

I have a list called keyList and I've tried searching for an answer, but haven't found anything helpful. I assume you could use

print(keyList) or print(keyList[])

Variable Creation:

```<code>n = input("Enter Deciaml Number:")

def binaryKey(n):
    n = 0
    keyList = []

</code>```

Printing Snippet:

```<code>print(keyList[])
</code>```

No matter what I try changing, I always get the error: NameError: name 'keyList' is not defined This makes me think that my list name is wrong, but clearly it isn't.

答:
You have declared kelist inside a function which you never used.
This is working example:

```<code>keylist = []
keylist.append('3')
keylist.append('2')
keylist.append('1')
print(keylist)
</code>```

Output:

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

Body:
I'm trying to create a simple program to print out the binary number of any given number under 255. I have everything working except printing out the final list.

I have a list called keyList and I've tried searching for an answer, but haven't found anything helpful. I assume you could use

print(keyList) or print(keyList[])

Variable Creation:

n = input("Enter Deciaml Number:")

def binaryKey(n):
    n = 0
    keyList = []

Printing Snippet:

print(keyList[])

No matter what I try changing, I always get the error: NameError: name 'keyList' is not defined This makes me think that my list name is wrong, but clearly it isn't.

Body:
You have declared kelist inside a function which you never used.
This is working example:

keylist = []
keylist.append('3')
keylist.append('2')
keylist.append('1')
print(keylist)

Output:

['3', '2', '1']


问:
Empty object with union type in graphQL
When I' using union type in my graphQL schema I use it typically like this:

```<code>const documentTypeDefs = gql`
 union TestType = TypeExample1 | TypeExample2

 type Document {
   exampleKey: TestType
 }
`
</code>```

Then I resolve it like this:

```<code>  TestType: {
    __resolveType(obj) {
     if(obj.property1) {
       return 'TypeExample1';
     }

     if(obj.property2) {
       return 'TypeExample2';
     }

    return null;
  },
}
</code>```

But sometimes I'm getting empty object in my resolving function (ie. obj is {}). I thought returning null or undefined will do the job but unfortunately I'm getting error:

```<code>"Abstract type ItemsType must resolve to an Object type at runtime for field Document.exampleKey with value {}, received \"{}\". Either the ItemsType type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."
</code>```

How can I resolve empty object then?
Thank you!

答:
If an empty object is being passed to __resolveType, that means your field is resolving to an empty object. That means either the value being returned inside your resolver is an empty object, or else the Promise returned is resolving to one.

If you're working with a field that returns a List, it's also possible for just one of the items being returned to be an empty object. This is particularly likely when working with MongoDB if one of the documents you're getting is actually empty or at least missing the fields you've specified in your mongoose schema.

Title: Empty object with union type in graphQL

Body:
When I' using union type in my graphQL schema I use it typically like this:

const documentTypeDefs = gql`
 union TestType = TypeExample1 | TypeExample2

 type Document {
   exampleKey: TestType
 }
`

Then I resolve it like this:

  TestType: {
    __resolveType(obj) {
     if(obj.property1) {
       return 'TypeExample1';
     }

     if(obj.property2) {
       return 'TypeExample2';
     }

    return null;
  },
}

But sometimes I'm getting empty object in my resolving function (ie. obj is {}). I thought returning null or undefined will do the job but unfortunately I'm getting error:

"Abstract type ItemsType must resolve to an Object type at runtime for field Document.exampleKey with value {}, received \"{}\". Either the ItemsType type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."

How can I resolve empty object then?
Thank you!